_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
|
---|---|---|---|---|---|---|---|---|
4e307f0de705f59cc5985764e21b2a944c3c681ebabfbb892d1d106ff548fe74 | oreillymedia/etudes-for-erlang | powers.erl | %% @author J D Eisenberg <>
%% @doc Functions for raising a number to an integer power
and finding the Nth root of a number using Newton 's method .
2013 J D Eisenberg
%% @version 0.1
-module(powers).
-export([raise/2]).
@doc Raise a number X to an integer power N.
Any number to the power 0 equals 1 .
Any number to the power 1 is that number itself .
When N is positive , is equal to X times X^(N - 1 )
When N is negative , is equal to 1.0 / X^N
-spec(raise(number(), integer()) -> number()).
raise(_, 0) -> 1;
raise(X, 1) -> X;
raise(X, N) when N > 0 -> X * raise(X, N - 1);
raise(X, N) when N < 0 -> 1 / raise(X, -N).
| null | https://raw.githubusercontent.com/oreillymedia/etudes-for-erlang/07200372503a8819f9fcc2856f8cb82451be7b48/code/ch04-03/powers.erl | erlang | @author J D Eisenberg <>
@doc Functions for raising a number to an integer power
@version 0.1 | and finding the Nth root of a number using Newton 's method .
2013 J D Eisenberg
-module(powers).
-export([raise/2]).
@doc Raise a number X to an integer power N.
Any number to the power 0 equals 1 .
Any number to the power 1 is that number itself .
When N is positive , is equal to X times X^(N - 1 )
When N is negative , is equal to 1.0 / X^N
-spec(raise(number(), integer()) -> number()).
raise(_, 0) -> 1;
raise(X, 1) -> X;
raise(X, N) when N > 0 -> X * raise(X, N - 1);
raise(X, N) when N < 0 -> 1 / raise(X, -N).
|
81ffdb5854708babe4a134debdd18868de340a8dda14f24dd88bf1e4a13eda33 | JustusAdam/language-haskell | T0157.hs | SYNTAX TEST " source.haskell " " Specialise pragma "
# SPECIALIZE [ 0 ] hammeredLookup : : [ ( Widget , value ) ] - > Widget - > value #
-- ^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
^^^^^^ ^^^^^^ storage.type.haskell
^^^^^ ^^^^^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
-- ^^^^^^^^^^^^^^ - meta.preprocessor.haskell
{-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-}
-- ^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
-- ^^ entity.name.function.infix.haskell
^^^ ^^^ storage.type.haskell
^ ^ ^ ^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
# SPECIALIZE INLINE [ ~2 ] ( ! :) : : Arr ( a , b ) - > Int - > ( a , b ) #
-- ^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
-- ^^^^^^ keyword.other.preprocessor.pragma.haskell
-- ^^ entity.name.function.infix.haskell
^^^ ^^^ storage.type.haskell
^ ^ ^ ^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
instance (Eq a) => Eq (Foo a) where {
# SPECIALISE [ 1 ] instance ( Foo [ ( Int , Bar ) ] ) #
-- ^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
-- ^^^^^^^^ keyword.other.instance.haskell
^^ ^^^ ^^^ storage.type.haskell
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
}
| null | https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0157.hs | haskell | ^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
^^^^^^^^^^^^^^ - meta.preprocessor.haskell
# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #
^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
^^ entity.name.function.infix.haskell
^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
^^^^^^ keyword.other.preprocessor.pragma.haskell
^^ entity.name.function.infix.haskell
^^^^^^^^^^ keyword.other.preprocessor.pragma.haskell
^^^^^^^^ keyword.other.instance.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell | SYNTAX TEST " source.haskell " " Specialise pragma "
# SPECIALIZE [ 0 ] hammeredLookup : : [ ( Widget , value ) ] - > Widget - > value #
^^^^^^ ^^^^^^ storage.type.haskell
^^^^^ ^^^^^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
^^^ ^^^ storage.type.haskell
^ ^ ^ ^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
# SPECIALIZE INLINE [ ~2 ] ( ! :) : : Arr ( a , b ) - > Int - > ( a , b ) #
^^^ ^^^ storage.type.haskell
^ ^ ^ ^ variable.other.generic-type.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.preprocessor.haskell
instance (Eq a) => Eq (Foo a) where {
# SPECIALISE [ 1 ] instance ( Foo [ ( Int , Bar ) ] ) #
^^ ^^^ ^^^ storage.type.haskell
}
|
02ad0257a93038ba5fe006c512a97329c0e12dca8673ac29d10ba6610a66c6ac | mishadoff/project-euler | problem063.clj | (ns project-euler)
(defn pow [n e]
(reduce *' (repeat e n)))
Elapsed time : 4.921157 msecs
(defn euler-063 []
(loop [powers (iterate inc 1)
[x & xs] (map #(pow % (first powers)) (iterate inc 1)) sum 0 hit false]
(let [n (quot x (pow 10 (dec (first powers))))]
(cond (< n 1) (recur powers xs sum hit)
(< n 10) (recur powers xs (inc sum) true)
:else (if hit (recur (rest powers)
(map #(pow % (second powers)) (iterate inc 1))
sum false) sum))))) | null | https://raw.githubusercontent.com/mishadoff/project-euler/45642adf29626d3752227c5a342886b33c70b337/src/project_euler/problem063.clj | clojure | (ns project-euler)
(defn pow [n e]
(reduce *' (repeat e n)))
Elapsed time : 4.921157 msecs
(defn euler-063 []
(loop [powers (iterate inc 1)
[x & xs] (map #(pow % (first powers)) (iterate inc 1)) sum 0 hit false]
(let [n (quot x (pow 10 (dec (first powers))))]
(cond (< n 1) (recur powers xs sum hit)
(< n 10) (recur powers xs (inc sum) true)
:else (if hit (recur (rest powers)
(map #(pow % (second powers)) (iterate inc 1))
sum false) sum))))) |
|
6dee1d42091fa77cf06ca8ca7e3e5ac7c84b55294a75b1fa27d44d333cfc875e | brendanzab/language-garden | Lang_Clos.ml | (** {0 Closure converted functional language}
Unlike {!FunLang}, this language makes an explicit distinction between the
‘code’ of closures, and the captured variables they close over.
*)
(** {1 Syntax} *)
type ty =
| BoolType (** [ Bool ] *)
| IntType (** [ Int ] *)
| CodeType of ty * ty * ty (** [ Code(t_env, t1, t2) ] *)
| TupleType of ty list (** [ (t1, ... tn) ] *)
| ClosType of ty * ty (** [ t1 -> t2 ] *)
type tm =
| Var of int
| Let of string * ty * tm * tm
| BoolLit of bool
| IntLit of int
| PrimApp of Prim.t * tm list
| CodeLit of ty * (string * ty) * tm (** [ fun env x => e ] *)
| TupleLit of tm list (** [ (e1, ..., en) ] *)
| TupleProj of tm * int (** [ e.n ] *)
* [ clos(e1 , e2 ) ]
| ClosApp of tm * tm (** [ e1 e2 ] *)
* { 1 Pretty printing }
let rec pp_ty fmt =
function
| ClosType (param_ty, body_ty) ->
Format.fprintf fmt "%a -> %a"
pp_atomic_ty param_ty
pp_ty body_ty
| ty ->
pp_atomic_ty fmt ty
and pp_atomic_ty fmt =
function
| BoolType -> Format.fprintf fmt "Bool"
| IntType -> Format.fprintf fmt "Int"
| CodeType (env_ty, param_ty, body_ty) ->
Format.fprintf fmt "@[Code(%a,@ %a,@ %a)@]"
pp_ty env_ty
pp_ty param_ty
pp_ty body_ty
| TupleType tys ->
Format.fprintf fmt "@[{%a}@]"
(Format.pp_print_list pp_ty ~pp_sep:(fun fmt () -> Format.fprintf fmt ",@ ")) tys
| ty ->
Format.fprintf fmt "@[(%a)@]" pp_ty ty
let pp_name_ann fmt (name, ty) =
Format.fprintf fmt "@[<2>@[%s :@]@ %a@]" name pp_ty ty
let pp_param fmt (name, ty) =
Format.fprintf fmt "@[<2>(@[%s :@]@ %a)@]" name pp_ty ty
let rec pp_tm names fmt = function
| Let _ as tm ->
let rec go names fmt = function
| Let (name, def_ty, def, body) ->
Format.fprintf fmt "@[<2>@[let %a@ :=@]@ @[%a;@]@]@ %a"
pp_name_ann (name, def_ty)
(pp_tm names) def
(go (name :: names)) body
| tm -> Format.fprintf fmt "@[%a@]" (pp_tm names) tm
in
go names fmt tm
| CodeLit (env_ty, (name, param_ty), body) ->
Format.fprintf fmt "@[@[fun@ %a@ %a@ =>@]@ %a@]"
pp_param ("env", env_ty)
pp_param (name, param_ty)
(pp_tm [name; "env"]) body
| tm ->
pp_add_tm names fmt tm
and pp_add_tm names fmt = function
| PrimApp (`Add, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ +@ %a@]"
(pp_mul_tm names) arg1
(pp_add_tm names) arg2
| PrimApp (`Sub, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ -@ %a@]"
(pp_mul_tm names) arg1
(pp_add_tm names) arg2
| tm ->
pp_mul_tm names fmt tm
and pp_mul_tm names fmt = function
| PrimApp (`Mul, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ *@ %a@]"
(pp_app_tm names) arg1
(pp_mul_tm names) arg2
| tm ->
pp_app_tm names fmt tm
and pp_app_tm names fmt = function
| ClosApp (head, arg) ->
Format.fprintf fmt "@[%a@ %a@]"
(pp_app_tm names) head
(pp_proj_tm names) arg
| PrimApp (`Neg, [arg]) ->
Format.fprintf fmt "@[-%a@]"
(pp_atomic_tm names) arg
| tm ->
pp_proj_tm names fmt tm
and pp_proj_tm names fmt = function
| TupleProj (head, label) ->
Format.fprintf fmt "@[%a.%i@]"
(pp_proj_tm names) head
label
| tm ->
pp_atomic_tm names fmt tm
and pp_atomic_tm names fmt = function
| Var index ->
Format.fprintf fmt "%s" (List.nth names index)
| BoolLit true -> Format.fprintf fmt "true"
| BoolLit false -> Format.fprintf fmt "false"
| IntLit i -> Format.fprintf fmt "%i" i
| ClosLit (code, env) ->
Format.fprintf fmt "@[<2>clos(%a,@ %a)@]"
(pp_tm names) code
(pp_tm names) env
| TupleLit tms ->
Format.fprintf fmt "@[{%a}@]"
(Format.pp_print_list (pp_tm names) ~pp_sep:(fun fmt () -> Format.fprintf fmt ",@ ")) tms
FIXME : Will loop forever on invalid primitive applications
| tm -> Format.fprintf fmt "@[(%a)@]" (pp_tm names) tm
module Semantics = struct
(** {1 Values} *)
type vtm =
| BoolLit of bool
| IntLit of int
| CodeLit of ty * (string * ty) * tm (** [ fun env x => e ] *)
| TupleLit of vtm list (** [ (v1, ..., v2) ] *)
| ClosLit of vtm * vtm (** [ clos(v1, v2) ] *)
(** {1 Evaluation} *)
let rec eval env : tm -> vtm =
function
| Var index -> List.nth env index
| Let (_, _, def, body) ->
let def = eval env def in
eval (def :: env) body
| BoolLit b -> BoolLit b
| IntLit i -> IntLit i
| PrimApp (prim, args) ->
prim_app prim (List.map (eval env) args)
| CodeLit (env_ty, (name, param_ty), body) ->
CodeLit (env_ty, (name, param_ty), body)
| TupleLit tms ->
TupleLit (List.map (eval env) tms)
| TupleProj (head, label) ->
let head = eval env head in
tuple_proj head label
| ClosLit (code, env') ->
ClosLit (eval env code, eval env env')
| ClosApp (head, arg) ->
let head = eval env head in
let arg = eval env arg in
clos_app head arg
(** {1 Eliminators} *)
and prim_app prim args =
match prim, args with
| `Neg, [IntLit t1] -> IntLit (-t1)
| `Add, [IntLit t1; IntLit t2] -> IntLit (t1 + t2)
| `Sub, [IntLit t1; IntLit t2] -> IntLit (t1 - t2)
| `Mul, [IntLit t1; IntLit t2] -> IntLit (t1 * t2)
| _, _ -> invalid_arg "invalid prim application"
and tuple_proj head label =
match head with
| TupleLit vtms -> List.nth vtms label
| _ -> invalid_arg "expected tuple"
and clos_app head arg =
match head with
| ClosLit (CodeLit (_, _, body), env) -> eval [arg; env] body
| _ -> invalid_arg "expected closure"
end
module Validation = struct
let rec check context tm expected_ty =
match tm, expected_ty with
| tm, expected_ty ->
let ty = synth context tm in
if ty = expected_ty then () else
invalid_arg
(Format.asprintf "@[<v 2>@[mismatched types:@]@ @[expected: %a@]@ @[found: %a@]@]"
pp_ty expected_ty
pp_ty ty)
and synth context tm =
match tm with
| Var index ->
begin match List.nth_opt context index with
| Some ty -> ty
| None -> invalid_arg "unbound variable"
end
| Let (_, _, def, body) ->
let def_ty = synth context def in
synth (def_ty :: context) body
| BoolLit _ -> BoolType
| IntLit _ -> IntType
| PrimApp (`Neg, [t]) ->
check context t IntType;
IntType
| PrimApp ((`Add | `Sub | `Mul), [t1; t2]) ->
check context t1 IntType;
check context t2 IntType;
IntType
| PrimApp _ ->
invalid_arg "invalid prim application"
| CodeLit (env_ty, (_, param_ty), body) ->
(* Code literals capture no variables from the surrounding context, so
the body of the closure is synthesised in a new context that assumes
only the parameter and the environment. *)
let body_ty = synth [param_ty; env_ty] body in
CodeType (env_ty, param_ty, body_ty)
| TupleLit tms ->
TupleType (List.map (synth context) tms)
| TupleProj (head, label) ->
begin match synth context head with
| TupleType tys ->
begin match List.nth_opt tys label with
| Some ty -> ty
| None ->
invalid_arg
(Format.asprintf "projected %i on a tuple with %i elements"
label (List.length tys))
end
| ty ->
invalid_arg
(Format.asprintf "expected tuple but found term of type %a" pp_ty ty)
end
| ClosLit (code, env) ->
begin match synth context code with
| CodeType (env_ty, param_ty, body_ty) ->
check context env env_ty;
ClosType (param_ty, body_ty)
| ty ->
invalid_arg
(Format.asprintf "expected code but found term of type %a" pp_ty ty)
end
| ClosApp (head, arg) ->
begin match synth context head with
| ClosType (param_ty, body_ty) ->
check context arg param_ty;
body_ty
| ty ->
invalid_arg
(Format.asprintf "expected closure but found term of type %a" pp_ty ty)
end
end
| null | https://raw.githubusercontent.com/brendanzab/language-garden/a2737cd9869f5fbbba0a7cac9a460fca952b40df/compile-closure-conv/lib/Lang_Clos.ml | ocaml | * {0 Closure converted functional language}
Unlike {!FunLang}, this language makes an explicit distinction between the
‘code’ of closures, and the captured variables they close over.
* {1 Syntax}
* [ Bool ]
* [ Int ]
* [ Code(t_env, t1, t2) ]
* [ (t1, ... tn) ]
* [ t1 -> t2 ]
* [ fun env x => e ]
* [ (e1, ..., en) ]
* [ e.n ]
* [ e1 e2 ]
* {1 Values}
* [ fun env x => e ]
* [ (v1, ..., v2) ]
* [ clos(v1, v2) ]
* {1 Evaluation}
* {1 Eliminators}
Code literals capture no variables from the surrounding context, so
the body of the closure is synthesised in a new context that assumes
only the parameter and the environment. |
type ty =
type tm =
| Var of int
| Let of string * ty * tm * tm
| BoolLit of bool
| IntLit of int
| PrimApp of Prim.t * tm list
* [ clos(e1 , e2 ) ]
* { 1 Pretty printing }
let rec pp_ty fmt =
function
| ClosType (param_ty, body_ty) ->
Format.fprintf fmt "%a -> %a"
pp_atomic_ty param_ty
pp_ty body_ty
| ty ->
pp_atomic_ty fmt ty
and pp_atomic_ty fmt =
function
| BoolType -> Format.fprintf fmt "Bool"
| IntType -> Format.fprintf fmt "Int"
| CodeType (env_ty, param_ty, body_ty) ->
Format.fprintf fmt "@[Code(%a,@ %a,@ %a)@]"
pp_ty env_ty
pp_ty param_ty
pp_ty body_ty
| TupleType tys ->
Format.fprintf fmt "@[{%a}@]"
(Format.pp_print_list pp_ty ~pp_sep:(fun fmt () -> Format.fprintf fmt ",@ ")) tys
| ty ->
Format.fprintf fmt "@[(%a)@]" pp_ty ty
let pp_name_ann fmt (name, ty) =
Format.fprintf fmt "@[<2>@[%s :@]@ %a@]" name pp_ty ty
let pp_param fmt (name, ty) =
Format.fprintf fmt "@[<2>(@[%s :@]@ %a)@]" name pp_ty ty
let rec pp_tm names fmt = function
| Let _ as tm ->
let rec go names fmt = function
| Let (name, def_ty, def, body) ->
Format.fprintf fmt "@[<2>@[let %a@ :=@]@ @[%a;@]@]@ %a"
pp_name_ann (name, def_ty)
(pp_tm names) def
(go (name :: names)) body
| tm -> Format.fprintf fmt "@[%a@]" (pp_tm names) tm
in
go names fmt tm
| CodeLit (env_ty, (name, param_ty), body) ->
Format.fprintf fmt "@[@[fun@ %a@ %a@ =>@]@ %a@]"
pp_param ("env", env_ty)
pp_param (name, param_ty)
(pp_tm [name; "env"]) body
| tm ->
pp_add_tm names fmt tm
and pp_add_tm names fmt = function
| PrimApp (`Add, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ +@ %a@]"
(pp_mul_tm names) arg1
(pp_add_tm names) arg2
| PrimApp (`Sub, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ -@ %a@]"
(pp_mul_tm names) arg1
(pp_add_tm names) arg2
| tm ->
pp_mul_tm names fmt tm
and pp_mul_tm names fmt = function
| PrimApp (`Mul, [arg1; arg2]) ->
Format.fprintf fmt "@[%a@ *@ %a@]"
(pp_app_tm names) arg1
(pp_mul_tm names) arg2
| tm ->
pp_app_tm names fmt tm
and pp_app_tm names fmt = function
| ClosApp (head, arg) ->
Format.fprintf fmt "@[%a@ %a@]"
(pp_app_tm names) head
(pp_proj_tm names) arg
| PrimApp (`Neg, [arg]) ->
Format.fprintf fmt "@[-%a@]"
(pp_atomic_tm names) arg
| tm ->
pp_proj_tm names fmt tm
and pp_proj_tm names fmt = function
| TupleProj (head, label) ->
Format.fprintf fmt "@[%a.%i@]"
(pp_proj_tm names) head
label
| tm ->
pp_atomic_tm names fmt tm
and pp_atomic_tm names fmt = function
| Var index ->
Format.fprintf fmt "%s" (List.nth names index)
| BoolLit true -> Format.fprintf fmt "true"
| BoolLit false -> Format.fprintf fmt "false"
| IntLit i -> Format.fprintf fmt "%i" i
| ClosLit (code, env) ->
Format.fprintf fmt "@[<2>clos(%a,@ %a)@]"
(pp_tm names) code
(pp_tm names) env
| TupleLit tms ->
Format.fprintf fmt "@[{%a}@]"
(Format.pp_print_list (pp_tm names) ~pp_sep:(fun fmt () -> Format.fprintf fmt ",@ ")) tms
FIXME : Will loop forever on invalid primitive applications
| tm -> Format.fprintf fmt "@[(%a)@]" (pp_tm names) tm
module Semantics = struct
type vtm =
| BoolLit of bool
| IntLit of int
let rec eval env : tm -> vtm =
function
| Var index -> List.nth env index
| Let (_, _, def, body) ->
let def = eval env def in
eval (def :: env) body
| BoolLit b -> BoolLit b
| IntLit i -> IntLit i
| PrimApp (prim, args) ->
prim_app prim (List.map (eval env) args)
| CodeLit (env_ty, (name, param_ty), body) ->
CodeLit (env_ty, (name, param_ty), body)
| TupleLit tms ->
TupleLit (List.map (eval env) tms)
| TupleProj (head, label) ->
let head = eval env head in
tuple_proj head label
| ClosLit (code, env') ->
ClosLit (eval env code, eval env env')
| ClosApp (head, arg) ->
let head = eval env head in
let arg = eval env arg in
clos_app head arg
and prim_app prim args =
match prim, args with
| `Neg, [IntLit t1] -> IntLit (-t1)
| `Add, [IntLit t1; IntLit t2] -> IntLit (t1 + t2)
| `Sub, [IntLit t1; IntLit t2] -> IntLit (t1 - t2)
| `Mul, [IntLit t1; IntLit t2] -> IntLit (t1 * t2)
| _, _ -> invalid_arg "invalid prim application"
and tuple_proj head label =
match head with
| TupleLit vtms -> List.nth vtms label
| _ -> invalid_arg "expected tuple"
and clos_app head arg =
match head with
| ClosLit (CodeLit (_, _, body), env) -> eval [arg; env] body
| _ -> invalid_arg "expected closure"
end
module Validation = struct
let rec check context tm expected_ty =
match tm, expected_ty with
| tm, expected_ty ->
let ty = synth context tm in
if ty = expected_ty then () else
invalid_arg
(Format.asprintf "@[<v 2>@[mismatched types:@]@ @[expected: %a@]@ @[found: %a@]@]"
pp_ty expected_ty
pp_ty ty)
and synth context tm =
match tm with
| Var index ->
begin match List.nth_opt context index with
| Some ty -> ty
| None -> invalid_arg "unbound variable"
end
| Let (_, _, def, body) ->
let def_ty = synth context def in
synth (def_ty :: context) body
| BoolLit _ -> BoolType
| IntLit _ -> IntType
| PrimApp (`Neg, [t]) ->
check context t IntType;
IntType
| PrimApp ((`Add | `Sub | `Mul), [t1; t2]) ->
check context t1 IntType;
check context t2 IntType;
IntType
| PrimApp _ ->
invalid_arg "invalid prim application"
| CodeLit (env_ty, (_, param_ty), body) ->
let body_ty = synth [param_ty; env_ty] body in
CodeType (env_ty, param_ty, body_ty)
| TupleLit tms ->
TupleType (List.map (synth context) tms)
| TupleProj (head, label) ->
begin match synth context head with
| TupleType tys ->
begin match List.nth_opt tys label with
| Some ty -> ty
| None ->
invalid_arg
(Format.asprintf "projected %i on a tuple with %i elements"
label (List.length tys))
end
| ty ->
invalid_arg
(Format.asprintf "expected tuple but found term of type %a" pp_ty ty)
end
| ClosLit (code, env) ->
begin match synth context code with
| CodeType (env_ty, param_ty, body_ty) ->
check context env env_ty;
ClosType (param_ty, body_ty)
| ty ->
invalid_arg
(Format.asprintf "expected code but found term of type %a" pp_ty ty)
end
| ClosApp (head, arg) ->
begin match synth context head with
| ClosType (param_ty, body_ty) ->
check context arg param_ty;
body_ty
| ty ->
invalid_arg
(Format.asprintf "expected closure but found term of type %a" pp_ty ty)
end
end
|
023416ae93837b2cde32fa5026ad334802678b3eaf013d866aaca2835595a0a9 | plumatic/grab-bag | main_local.clj | (ns crane.main-local
"Entry point for local crane operations."
(:use plumbing.core)
(:require
[schema.core :as s]
[plumbing.classpath :as classpath]
[crane.config :as config]
[crane.core :as crane]
crane.task))
(defn resolve-task [x]
(ns-resolve 'crane.task (symbol x)))
(defn main [project-name [task config-sym & args]]
(crane/init-main!)
(let [ec2-creds (config/read-dot-crane)
env (keyword config-sym)]
(if (= :global env)
(apply @(resolve-task task)
ec2-creds args)
(apply @(resolve-task task)
ec2-creds
(config/abstract-config
(config/enved-config-spec
(config/str->config-spec
(classpath/read-from-classpath
(format "%s/config.clj"
(.replace ^String project-name "-" "_"))))
env)
project-name)
args)))
(when-not (= task "run")
(System/exit 0)))
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/crane/src/crane/main_local.clj | clojure | (ns crane.main-local
"Entry point for local crane operations."
(:use plumbing.core)
(:require
[schema.core :as s]
[plumbing.classpath :as classpath]
[crane.config :as config]
[crane.core :as crane]
crane.task))
(defn resolve-task [x]
(ns-resolve 'crane.task (symbol x)))
(defn main [project-name [task config-sym & args]]
(crane/init-main!)
(let [ec2-creds (config/read-dot-crane)
env (keyword config-sym)]
(if (= :global env)
(apply @(resolve-task task)
ec2-creds args)
(apply @(resolve-task task)
ec2-creds
(config/abstract-config
(config/enved-config-spec
(config/str->config-spec
(classpath/read-from-classpath
(format "%s/config.clj"
(.replace ^String project-name "-" "_"))))
env)
project-name)
args)))
(when-not (= task "run")
(System/exit 0)))
|
|
58e3d727f3cd689aebdd29a05297aec3cebe03f1e407b7b486dbbc6822c54899 | Gbury/archsat | superposition.ml | This file is free software , part of Archsat . See file " LICENSE " for more details .
This module uses unitary supperposition to
unify terms modulo equality .
For a reference , see :
' E , a brainiac theorem prover ' by .
This module uses unitary supperposition to
unify terms modulo equality.
For a reference, see :
'E, a brainiac theorem prover' by shulz.
*)
module C = Set.Make(Mapping)
(* Types *)
(* ************************************************************************ *)
type side = Left | Right
type lit =
| Empty
| Eq of Expr.term * Expr.term
| Neq of Expr.term * Expr.term
(* Type of reasons for clauses. *)
type reason =
| Hyp of Expr.formula option * Mapping.t
| Fresh of clause * Mapping.t
| ER of clause * Mapping.t
| ES of pointer * pointer * Mapping.t
| SN of pointer * pointer * Mapping.t
| SP of pointer * pointer * Mapping.t
| RN of pointer * pointer * Mapping.t
| RP of pointer * pointer * Mapping.t
| MN of pointer * pointer * Mapping.t
| MP of pointer * pointer * Mapping.t
Type for unit clauses , i.e clauses with at most one equation
and clause = {
id : int; (* Unique id (for printing and tracking through logs) *)
lit : lit; (* Contents of the clause *)
map : C.t; (* Current mapping for variables & meta-variables *)
reason : reason; (* Reason of the clause *)
weight of the clause ( clauses with lesser
weight are selected first )
weight are selected first) *)
depth : int; (* Depth of the inference chain that leads to this clause. *)
rewrites : (* List of rewrites used to reach this clause. *)
(Expr.formula * Mapping.t) list Lazy.t;
}
and pointer = {
clause : clause;
side : side;
path : Position.t;
}
(* Weight computing *)
(* ************************************************************************ *)
let rec term_size acc = function
| { Expr.term = Expr.App (_, _, l) } ->
List.fold_left term_size (acc + 1) l
| _ -> acc + 1
(* Alpha-renaming *)
(* ************************************************************************ *)
let bind_leaf_ty _ ty acc =
match ty with
| { Expr.ty = Expr.TyApp _ } -> raise Exit
| { Expr.ty = Expr.TyVar v } ->
if Mapping.Var.mem_ty acc v then raise Exit
else Mapping.Var.bind_ty acc v Expr.Ty.base
| { Expr.ty = Expr.TyMeta m } ->
if Mapping.Meta.mem_ty acc m then raise Exit
else Mapping.Meta.bind_ty acc m Expr.Ty.base
let bind_leaf_term _ term acc =
match term with
| { Expr.term = Expr.App _ } -> raise Exit
| { Expr.term = Expr.Var v } ->
if Mapping.Var.mem_term acc v then raise Exit
else Mapping.Var.bind_term acc v (Expr.Term.of_id v)
| { Expr.term = Expr.Meta m } ->
if Mapping.Meta.mem_term acc m then raise Exit
else Mapping.Meta.bind_term acc m (Expr.Term.of_meta m)
let is_alpha m =
try
let _ = Mapping.fold
~ty_var:bind_leaf_ty
~ty_meta:bind_leaf_ty
~term_var:bind_leaf_term
~term_meta:bind_leaf_term
m Mapping.empty
in true
with Exit -> false
(* Substitutions *)
(* ************************************************************************ *)
let simpl_mapping = Mapping.remove_refl
(* can s be composed with another mapping to be equal/included in s' *)
let match_subst s s' =
let aux get f_match x t acc =
let t' = get s' x in
f_match acc t t'
in
let ty_var = aux Mapping.Var.get_ty Match.ty in
let ty_meta = aux Mapping.Meta.get_ty Match.ty in
let term_var = aux Mapping.Var.get_term Match.term in
let term_meta = aux Mapping.Meta.get_term Match.term in
Mapping.fold ~ty_var ~term_var ~ty_meta ~term_meta s Mapping.empty
let (<) s t =
try
let _ = match_subst s t in
true
with
| Not_found
| Match.Impossible_ty _
| Match.Impossible_term _ -> false
let (<<) t t' =
C.for_all (fun s' -> C.exists (fun s -> s < s') t) t'
(* Mapping composition *)
let compose_set set rho =
C.map (Mapping.apply rho) set
(* Mapping merging *)
let merge_aux s s' =
let aux get f_match x t acc =
match get s' x with
| t' -> f_match acc t t'
| exception Not_found -> acc
in
let ty_var = aux Mapping.Var.get_ty Unif.Robinson.ty in
let ty_meta = aux Mapping.Meta.get_ty Unif.Robinson.ty in
let term_var = aux Mapping.Var.get_term Unif.Robinson.term in
let term_meta = aux Mapping.Meta.get_term Unif.Robinson.term in
Mapping.fold ~ty_var ~term_var ~ty_meta ~term_meta s Mapping.empty
let merge s s' =
match merge_aux s s' with
| exception Unif.Robinson.Impossible_ty _ -> None
| exception Unif.Robinson.Impossible_term _ -> None
| rho ->
let aux ~eq ~f = function
| None, None -> assert false
| Some x, None
| None, Some x -> Some (f x)
| Some x, Some y ->
let x' = f x in
let y' = f y in
assert (eq x' y');
Some x'
in
let rho' = Mapping.stretch (Mapping.stretch rho s) s' in
let aux_ty _ opt opt' =
aux ~eq:Expr.Ty.equal ~f:(Mapping.apply_ty rho') (opt, opt') in
let aux_term _ opt opt' =
aux ~eq:Expr.Term.equal ~f:(Mapping.apply_term rho') (opt, opt') in
Some (rho', Mapping.merge
~ty_var:aux_ty ~ty_meta:aux_ty
~term_var:aux_term ~term_meta:aux_term
s s')
let merge_set set set' =
C.fold (fun s acc ->
C.fold (fun s' acc' ->
match merge s s' with
| None -> acc'
| Some s'' -> s'' :: acc'
) set' acc) set []
(* Free variables in clauses *)
(* ************************************************************************ *)
let clause_mapped_vars map =
C.fold (fun m acc ->
match Mapping.codomain m with
| (fv, ([], [])) -> Expr.Id.merge_fv fv acc
| _ ->
(* All meta-variable should be bound to variables, so no meta-variables
should appear in the codomain of the mappings *)
Util.error "Meta-variable in codomain of a map in superposisiton";
assert false
) map ([], [])
let clause_fv a b map =
let mapped_vars = clause_mapped_vars map in
let free_vars = Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b) in
let l, l' = Expr.Id.remove_fv free_vars mapped_vars in
List.fold_left (fun m v ->
Mapping.Var.bind_ty m v (Expr.Ty.of_id v))
(List.fold_left (fun m v ->
Mapping.Var.bind_term m v (Expr.Term.of_id v)) Mapping.empty l') l
(* Clauses *)
(* ************************************************************************ *)
(* Misc functions on clauses *)
let is_eq c =
match c.lit with
| Eq _ -> true
| Neq _ | Empty -> false
(* Comparison of clauses *)
let _discr = function
| Empty -> 0
| Eq _ -> 1
| Neq _ -> 2
let compare c c' =
match c.lit, c'.lit with
| Empty, Empty -> C.compare c.map c'.map
| Eq (a, b), Eq (a', b')
| Neq (a, b), Neq (a', b') ->
CCOrd.(Expr.Term.compare a a'
<?> (Expr.Term.compare, b, b')
<?> (C.compare, c.map, c'.map))
| x, y -> Pervasives.compare (_discr x) (_discr y)
(* Printing of clauses *)
let rec pp_id fmt c =
match c.reason with
| Fresh (c', _) -> Format.fprintf fmt "~%a" pp_id c'
| _ -> Format.fprintf fmt "C%d" c.id
let pp_pos fmt pos =
let dir = if pos.side = Left then "→" else "←" in
Format.fprintf fmt "%a%s%a" pp_id pos.clause dir Position.print pos.path
let pp_reason fmt c =
match c.reason with
| Hyp _ -> Format.fprintf fmt "hyp"
| Fresh (c, _) -> Format.fprintf fmt "Fresh(%a)" pp_id c
| ER (d, _) -> Format.fprintf fmt "ER(%a)" pp_id d
| SN (d, e, _) -> Format.fprintf fmt "SN(%a;%a)" pp_pos d pp_pos e
| SP (d, e, _) -> Format.fprintf fmt "SP(%a;%a)" pp_pos d pp_pos e
| ES (d, e, _) -> Format.fprintf fmt "ES(%a;%a)" pp_pos d pp_pos e
| RN (d, e, _) -> Format.fprintf fmt "RN(%a;%a)" pp_pos d pp_pos e
| RP (d, e, _) -> Format.fprintf fmt "RP(%a;%a)" pp_pos d pp_pos e
| MN (d, e, _) -> Format.fprintf fmt "ME(%a;%a)" pp_pos d pp_pos e
| MP (d, e, _) -> Format.fprintf fmt "ME(%a;%a)" pp_pos d pp_pos e
let pp_cmp ~pos fmt (a, b) =
let s = Comparison.to_string (Lpo.compare a b) in
let s' =
if pos then s
else CCString.flat_map (function
| '=' -> "≠" | c -> CCString.of_char c) s
in
Format.fprintf fmt "%s" s'
let pp_lit fmt c =
match c.lit with
| Empty -> Format.fprintf fmt "∅"
| Eq (a, b) ->
Format.fprintf fmt "@[%a@ %a@ %a@]"
Expr.Print.term a (pp_cmp ~pos:true) (a, b) Expr.Print.term b
| Neq (a, b) ->
Format.fprintf fmt "@[%a@ %a@ %a@]"
Expr.Print.term a (pp_cmp ~pos:false) (a, b) Expr.Print.term b
let pp_map fmt map =
C.iter (fun m -> Format.fprintf fmt "@,[%a]" Mapping.print m) map
let debug_map fmt map =
C.iter (fun m -> Format.fprintf fmt "@,[%a]" Mapping.debug m) map
let pp fmt (c:clause) =
Format.fprintf fmt "@[<hov 2>%a[%d]@,@,[%a]@,[%a]%a@]"
pp_id c c.depth pp_reason c pp_lit c pp_map c.map
let pp_hyps fmt c =
match c.reason with
| Hyp _ -> ()
| ER (c, _) | Fresh (c, _) ->
Format.fprintf fmt "%a" pp c
| SN (d, e, _) | SP (d, e, _)
| RN (d, e, _) | RP (d, e, _)
| MN (d, e, _) | MP (d, e, _)
| ES (d, e, _) ->
Format.fprintf fmt "%a@\n%a" pp d.clause pp e.clause
Heuristics for clauses . Currently uses the size of terms .
NOTE : currently , weight does not take the subst into account so that
clauses that might be merged have the same weight and thus are
added together .
TODO : merge clauses in the queue ?
TODO : better heuristic for clause selection .
NOTE: currently, weight does not take the subst into account so that
clauses that might be merged have the same weight and thus are
added together.
TODO: merge clauses in the queue ?
TODO: better heuristic for clause selection.
*)
let compute_weight = function
| Empty -> -1
| Eq (a, b) -> 2 * (term_size (term_size 0 b) a)
| Neq (a, b) -> 1 * (term_size (term_size 0 b) a)
Disequalities have smaller weight because we are more interested
in them ( better chance to apply rule ER , and get a solution )
in them (better chance to apply rule ER, and get a solution) *)
let compute_depth = function
Hypotheses are at depth 0 .
| Hyp _ -> 1
(* If the reason is ER, then the resulting clause is the empty clause,
which we always want*)
| ER _ -> 0
Superposition steps increase depth
| SN (c, c', _) | SP (c, c', _)
-> max c.clause.depth c'.clause.depth + 1
(* Fresh clauses shouldn't increa depths. *)
| Fresh (c, _) -> c.depth
(* Don't increase the depth for simplifications steps. *)
| ES (c, c', _)
| RN (c, c', _) | RP (c, c', _)
| MN (c, c', _) | MP (c, c', _)
-> max c.clause.depth c'.clause.depth
let leq_cl c c' =
c.weight <= c'.weight || (
c.weight = c'.weight &&
C.cardinal c.map >= C.cardinal c'.map
)
TODO : use sets of rewrites to save some space
let map_rewrites m l =
let apply m m' =
let tmp = Mapping.apply m m' in
if Mapping.equal tmp m' then m' else tmp
in
List.map (fun (f, m') -> (f, apply m m')) l
let rec compute_rewrites = function
| Hyp (f, m) ->
if Mapping.is_empty m then [] else
begin match f with
| Some formula -> [formula, m]
| None ->
Util.error "Clause with free_vars but no tagged formula";
[]
end
| Fresh (c', m) | ER (c', m)
-> map_rewrites m (Lazy.force c'.rewrites)
| ES (p, p', m)
| SN (p, p', m) | SP (p, p', m)
| RN (p, p', m) | RP (p, p', m)
| MN (p, p', m) | MP (p, p', m)
-> map_rewrites m (Lazy.force p.clause.rewrites @
Lazy.force p'.clause.rewrites)
(* Clauses *)
let mk_cl =
let i = ref 0 in
(fun lit map reason ->
incr i;
let weight = compute_weight lit in
let depth = compute_depth reason in
let rewrites = lazy (compute_rewrites reason) in
let res = { id = !i; lit; map; reason; weight; depth; rewrites } in
Obsolete , now that there are rewrite rules
assert (
let lty , lt = match lit with
| Empty - > [ ] , [ ]
| Eq ( a , b )
| Neq ( a , b ) - > Expr . Id.merge_fv ( Expr.Term.fv a ) ( Expr.Term.fv b )
in
let b = ( fun m - >
let ( ( vty , vt ) , m ) = Mapping.codomain m in
m = ( [ ] , [ ] ) & &
CCList.subset ~eq : . Id. Ttype.equal lty vty & &
CCList.subset ~eq : . Id. Ty.equal lt vt
) map in
if not b then " % a " pp res ;
b
) ;
assert (
let lty,lt = match lit with
| Empty -> [], []
| Eq (a, b)
| Neq (a, b) -> Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b)
in
let b = C.for_all (fun m ->
let ((vty,vt), m) = Mapping.codomain m in
m = ([], []) &&
CCList.subset ~eq:Expr.Id.Ttype.equal lty vty &&
CCList.subset ~eq:Expr.Id.Ty.equal lt vt
) map in
if not b then Util.debug "%a" pp res;
b
);
*)
res
)
let ord a b = if Expr.Term.compare a b <= 0 then a, b else b, a
let mk_empty map clause mgu =
mk_cl Empty map (ER (clause, mgu))
let mk_eq a b map reason =
let c, d = ord a b in
mk_cl (Eq (c, d)) map reason
let mk_neq a b map reason =
let c, d = ord a b in
mk_cl (Neq (c, d)) map reason
(* Clause freshening *)
(* ************************************************************************ *)
let counter = ref 0
let new_ty_var =
(fun () -> incr counter; Expr.Id.ttype (Format.sprintf "?%d" !counter))
let new_var =
(fun ty -> incr counter; Expr.Id.ty (Format.sprintf "?%d" !counter) ty)
let fresh a b map =
assert (Expr.Term.fm a = ([], []));
assert (Expr.Term.fm b = ([], []));
let tys, terms = Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b) in
let m =
List.fold_left (fun acc v ->
Mapping.Var.bind_term acc v (
Expr.Term.of_id @@ new_var (Mapping.apply_ty acc Expr.(v.id_type)))
) (List.fold_left (fun acc v ->
Mapping.Var.bind_ty acc v (Expr.Ty.of_id @@ new_ty_var ())
) Mapping.empty tys) terms
in
let m = C.fold (CCFun.flip Mapping.stretch) map
(Mapping.expand (Mapping.expand m a) b) in
Util.debug " @[<hv 2 > fresh:@ % a@ % a " Mapping.print m pp_map map ;
m, (Mapping.apply_term m a), (Mapping.apply_term m b), (compose_set map m)
let freshen c =
match c.lit with
| Empty -> c
| Eq (a, b)
| Neq (a, b) ->
let f = if is_eq c then mk_eq else mk_neq in
let r, a', b', m' = fresh a b c.map in
f a' b' m' (Fresh (c, r))
(* Clause pointers *)
(* ************************************************************************ *)
let compare_side a b = match a, b with
| Left, Left | Right, Right -> 0
| Left, Right -> -1 | Right, Left -> 1
let compare_pointer pc pc' =
match compare pc.clause pc'.clause with
| 0 -> begin match compare_side pc.side pc'.side with
| 0 -> Position.compare pc.path pc'.path
| x -> x
end
| x -> x
Supperposition state
(* ************************************************************************ *)
module M = Map.Make(Expr.Term)
module Q = CCHeap.Make(struct type t = clause let leq = leq_cl end)
module Q = struct
type t = {
top : clause list ;
bot : clause list ;
}
let empty = {
top = [ ] ;
bot = [ ] ;
}
let fold f acc q =
let acc ' = List.fold_left f acc q.top in
List.fold_left f acc ' q.bot
let insert c q =
{ q with bot = c : : }
let rec take q =
match q.top with
| x : : r - > Some ( { q with top = r } , x )
| [ ] - >
begin match with
| [ ] - > None
| l - > take { top = List.rev l ; bot = [ ] }
end
end
module Q = struct
type t = {
top : clause list;
bot : clause list;
}
let empty = {
top = [];
bot = [];
}
let fold f acc q =
let acc' = List.fold_left f acc q.top in
List.fold_left f acc' q.bot
let insert c q =
{ q with bot = c :: q.bot }
let rec take q =
match q.top with
| x :: r -> Some ({q with top = r }, x)
| [] ->
begin match q.bot with
| [] -> None
| l -> take { top = List.rev l; bot = [] }
end
end
*)
module S = Set.Make(struct type t = clause let compare = compare end)
module I = Index.Make(struct type t = pointer let compare = compare_pointer end)
type rules = {
er : bool; es : bool;
sn : bool; sp : bool;
rn : bool; rp : bool;
mn : bool; mp : bool;
}
let mk_rules ~default
?(er=default) ?(es=default)
?(sn=default) ?(sp=default)
?(rn=default) ?(rp=default)
?(mn=default) ?(mp=default)
() =
{
er; es;
sn; sp;
rn; rp;
mn; mp;
}
type t = {
queue : Q.t;
clauses : S.t;
generated : S.t;
rules : rules;
root_pos_index : I.t;
root_neg_index : I.t;
inactive_index : I.t;
max_depth : int;
section : Section.t;
callback :
((Expr.formula * Mapping.t) list -> Mapping.t list -> unit) option;
}
let all_rules = {
er = true;
es = true;
sn = true;
sp = true;
rp = true;
rn = true;
mn = true;
mp = true;
}
let empty ?(max_depth=0) ?(rules=all_rules) ?callback section = {
queue = Q.empty;
clauses = S.empty;
generated = S.empty;
section; callback; rules; max_depth;
root_pos_index = I.empty (Section.make ~parent:section "pos_index");
root_neg_index = I.empty (Section.make ~parent:section "neg_index");
inactive_index = I.empty (Section.make ~parent:section "all_index");
}
let fold_subterms f e side clause i =
Position.Term.fold (fun i path t -> f t { path; side; clause } i) i e
let change_state_aux f_set f_index c t eq a b =
let l = match Lpo.compare a b with
| Comparison.Lt -> [b, Right] | Comparison.Gt -> [a, Left]
| Comparison.Incomparable -> [a, Left; b, Right]
| Comparison.Eq -> []
in
{ t with
clauses = f_set c t.clauses;
root_pos_index =
if eq then
List.fold_left (fun i (t, side) ->
f_index t { path = Position.root; side; clause = c } i)
t.root_pos_index l
else
t.root_pos_index;
root_neg_index =
if not eq then
List.fold_left (fun i (t, side) ->
f_index t { path = Position.root; side; clause = c } i)
t.root_neg_index l
else
t.root_neg_index;
inactive_index =
List.fold_left (fun i (t, side) ->
fold_subterms f_index t side c i) t.inactive_index l;
}
let change_state f_set f_index c t =
match c.lit with
| Eq (a, b) -> change_state_aux f_set f_index c t true a b
| Neq (a, b) -> change_state_aux f_set f_index c t false a b
| Empty -> { t with clauses = f_set c t.clauses }
let add_clause = change_state S.add I.add
let rm_clause = change_state S.remove I.remove
(* Symbol precedence *)
(* ************************************************************************ *)
module Symbols = Set.Make(Expr.Id.Const)
let rec term_symbols acc = function
| { Expr.term = Expr.Var _ }
| { Expr.term = Expr.Meta _ } -> acc
| { Expr.term = Expr.App (f, _, l) } ->
List.fold_left term_symbols (Symbols.add f acc) l
let clause_symbols acc c =
match c.lit with
| Empty -> acc
| Eq (a, b) | Neq (a, b) ->
term_symbols (term_symbols acc a) b
let set_symbols t =
let s = Symbols.empty in
let s' = Q.fold clause_symbols s t.queue in
S.fold (CCFun.flip clause_symbols) t.clauses s'
let pp_precedence fmt t =
let s = set_symbols t in
let l = Symbols.elements s in
let sep fmt () = Format.fprintf fmt " <@ " in
CCFormat.list ~sep Expr.Id.Const.print fmt l
(* Help functions *)
(* ************************************************************************ *)
let extract pos =
match pos.side, pos.clause.lit with
| Left, (Eq (a, b) | Neq (a, b))
| Right, (Eq (b, a) | Neq (b, a)) -> a, b
| _, Empty -> assert false
(* Perform an equality resolution, i.e rule ER *)
let do_resolution ~section acc clause =
match clause.lit with
| Eq _ | Empty -> acc
| Neq (s, t) ->
let sigma = clause.map in
begin match Unif.Robinson.term Mapping.empty s t with
| mgu ->
let mgu = C.fold (CCFun.flip Mapping.stretch) sigma mgu in
mk_empty (compose_set sigma mgu) clause mgu :: acc
| exception Unif.Robinson.Impossible_ty _ -> acc
| exception Unif.Robinson.Impossible_term _ -> acc
end
Perform a superposition , i.e either rule SN or SP
[ active ] is ( the position of ) the equality used to perform the substitution ,
[ inactive ] is ( the position of ) the clause the substitution is being performed on
[ mgu ] is the subtitution that unifies [ active ] and [ inactive ]
TODO : check the LPO constraints iff it really need to be checked
i.e. only when the ordering failed on the non - instanciated clause
[active] is (the position of) the equality used to perform the substitution,
[inactive] is (the position of) the clause the substitution is being performed on
[mgu] is the subtitution that unifies [active] and [inactive]
TODO: check the LPO constraints iff it really need to be checked
i.e. only when the ordering failed on the non-instanciated clause
*)
let do_supp acc sigma'' active inactive =
assert (is_eq active.clause);
assert (Position.equal active.path Position.root);
let p = inactive.path in
let s, t = extract active in
let u, v = extract inactive in
let sigma = active.clause.map in
let sigma' = inactive.clause.map in
let m = List.fold_left Mapping.expand sigma'' [s; t; u; v] in
let m = C.fold (CCFun.flip Mapping.stretch) sigma m in
let m = C.fold (CCFun.flip Mapping.stretch) sigma' m in
(* Merge the substitutions. *)
let res1 = compose_set sigma m in
let res2 = compose_set sigma' m in
let l = merge_set res1 res2 in
Util.debug " @[<v 2 > supp:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print m ;
Util.debug "@[<v 2>supp:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print m;
*)
let apply = Mapping.apply_term m in
let v' = apply v in
let t' = apply t in
let s' = apply s in
let u' = apply u in
let u_res, u_p_opt = Position.Term.apply p u in
Check that mgu effectively unifies u_p and s
assert (match u_p_opt with
| None -> false
| Some u_p -> Expr.Term.equal s' (apply u_p));
(* Check the guards of the rule *)
if Lpo.compare t' s' = Comparison.Gt ||
Lpo.compare v' u' = Comparison.Gt ||
fst (Position.Term.apply p u) = Position.Var then
acc
else begin
(* Apply substitution *)
match Position.Term.substitute inactive.path ~by:t' u' with
| Some u'' ->
let f = if is_eq inactive.clause then mk_eq else mk_neq in
List.fold_left (fun acc (rho, res) ->
let subst, u''', v'', map = fresh
(Mapping.apply_term rho u'')
(Mapping.apply_term rho v')
(C.singleton res)
in
let subst = Mapping.stretch subst m in
let reason =
if is_eq inactive.clause then
SP(active, inactive, Mapping.apply subst m)
else
SN(active, inactive, Mapping.apply subst m)
in
let c = f u''' v'' map reason in
c :: acc) acc l
| None ->
(* This should not happen *)
assert false
end
(* Perform a rewrite, i.e. either rule RN or RP
[active] is the equality used for the rewrite
[inactive] is the clause being worked on
[rho] is the substitution that matches [active] and [inactive]
*)
let do_rewrite active inactive =
(* currently the substitution must be the identity *)
assert (is_eq active.clause);
assert (Position.equal active.path Position.root);
let sigma = inactive.clause.map in
let s, t = extract active in
let u, v = extract inactive in
Util.debug " @[<v 2 > rwrt:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
pp_map sigma ;
Util.debug "@[<v 2>rwrt:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
pp_map sigma;
*)
let guard =
active.clause.map << sigma &&
Lpo.compare s t = Comparison.Gt &&
(if is_eq inactive.clause then (
not (Lpo.compare u v = Comparison.Gt) ||
not (Position.equal inactive.path Position.root)
) else true)
in
" rwrt failed " ;
else begin
match Position.Term.substitute inactive.path ~by:t u with
| Some u' ->
let f = if is_eq inactive.clause then mk_eq else mk_neq in
let subst, u'', v', map = fresh u' v sigma in
let reason =
if is_eq inactive.clause
then RP(active, inactive, subst)
else RN(active, inactive, subst)
in
Some (f u'' v' map reason)
| None ->
(* shouldn't really happen *)
assert false
end
This functions tries to find an equality [ v = w ] in the index ,
used particualrly for computing the ES rule .
used particualrly for computing the ES rule. *)
let find_eq index v w =
CCList.flat_map (fun (_, rho, l) ->
CCList.flat_map (fun pos ->
let s, t = extract pos in
(* should be enforced by the index. *)
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho v) s);
match Match.term rho w t with
| rho' -> if is_alpha rho' then [pos, rho'] else []
| exception Match.Impossible_ty _ -> []
| exception Match.Impossible_term _ -> []
) l) (I.find_match v index)
This function tries and find if there is an equality in p_set , such
that [ a ] and [ b ] are suceptible to be an equality simplified by the ES rule .
Additionally , for the ES rule , we need to keep track of the position at which
the subtitution takes place . That is the role of the [ curr ] argument .
Returns the list of all potential clauses that could be used to make
[ a ] and [ b ] equal .
that [a] and [b] are suceptible to be an equality simplified by the ES rule.
Additionally, for the ES rule, we need to keep track of the position at which
the subtitution takes place. That is the role of the [curr] argument.
Returns the list of all potential clauses that could be used to make
[a] and [b] equal.
*)
let rec make_eq_aux p_set curr a b =
if Expr.Term.equal a b then `Equal
else
match find_eq p_set.root_pos_index a b with
| [] ->
begin match a, b with
| { Expr.term = Expr.App (f, _, f_args) },
{ Expr.term = Expr.App (g, _, g_args) } when Expr.Id.equal f g ->
make_eq_list p_set curr 0 f_args g_args
| _ -> `Impossible
end
| l -> `Substitutable (curr, l)
and make_eq_list p_set curr idx l l' =
match l, l' with
| [], [] -> `Equal
| a :: r, b :: r' ->
begin match make_eq_aux p_set (Position.follow curr idx) a b with
| `Equal -> make_eq_list p_set curr (idx + 1) r r'
| `Impossible -> `Impossible
| `Substitutable (path, u) as res ->
if List.for_all2 Expr.Term.equal r r' then res else `Impossible
end
| _ ->
Since we only give arguments list of equal functions , the two lists
should always have the same length .
should always have the same length. *)
assert false
let make_eq p_set a b =
make_eq_aux p_set Position.root a b
(* Perform equality subsumption *)
let do_subsumption rho active inactive =
assert (is_alpha rho);
assert (is_eq active.clause);
assert (is_eq inactive.clause);
assert (Position.equal Position.root active.path);
let sigma = active.clause.map in
let s, t = extract active in
let u, v = extract inactive in
let rho = List.fold_left Mapping.expand rho [u; v] in
Util.debug " @[<v > subsumption:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print rho ;
Util.debug "@[<v>subsumption:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print rho;
*)
assert (
match Position.Term.apply inactive.path u with
| _, None -> false
| _, Some (u_p) ->
Expr.Term.equal s (Mapping.apply_term ~fix:false rho u_p)
);
assert (
match Position.Term.substitute inactive.path
~by:t (Mapping.apply_term ~fix:false rho u) with
| None -> false
| Some u' ->
Expr.Term.equal u' (Mapping.apply_term ~fix:false rho v)
);
let redundant, sigma' = C.partition (fun rho ->
C.exists (fun s -> s < rho) sigma) inactive.clause.map in
if C.is_empty redundant then
inactive.clause
else
mk_eq u v sigma' (ES (active, inactive, rho))
(* Perform clause merging *)
let do_merging p active inactive rho =
assert ((is_eq active.clause && is_eq inactive.clause) ||
(not @@ is_eq active.clause && not @@ is_eq inactive.clause));
let sigma = active.clause.map in
let sigma' = inactive.clause.map in
let s, t = extract active in
let u, v = extract inactive in
Util.debug " @[<v > merging:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print rho ;
Util.debug "@[<v>merging:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print rho;
*)
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho u) s);
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho v) t);
if is_alpha rho then begin
let f = if is_eq inactive.clause then mk_eq else mk_neq in
let rho = C.fold (CCFun.flip Mapping.stretch) sigma' rho in
let reason =
if is_eq inactive.clause
then MP (active, inactive, rho)
else MN (active, inactive, rho)
in
let c = C.union sigma (compose_set sigma' rho) in
Util.debug ~section:p.section "@{<Red>Removing@}: %a" pp active.clause;
Some (rm_clause active.clause p, f s t c reason)
end else None
(* Inference rules *)
(* ************************************************************************ *)
(* Equality resolution, alias ER *)
let equality_resolution p_set clause acc =
if not p_set.rules.er then acc
else do_resolution ~section:p_set.section acc clause
Supperposition rules , alias SN & SP
Given a new clause , and the current set of clauses , there are two cases :
- either the new clause might be the active clause in a SN or SP rule
( i.e. the equality used to substitute )
- or it is the inactive clause ( i.e. the clause the substitution is
performed on )
Given a new clause, and the current set of clauses, there are two cases:
- either the new clause might be the active clause in a SN or SP rule
(i.e. the equality used to substitute)
- or it is the inactive clause (i.e. the clause the substitution is
performed on)
*)
let superposition rules acc u active inactive =
if ((is_eq inactive.clause && rules.sp)
|| (* not is_eq && *) rules.sn) then
do_supp acc u active inactive
else
acc
let add_passive_supp p_set clause side acc path = function
| { Expr.term = Expr.Var _ }
| { Expr.term = Expr.Meta _ } -> acc
| p ->
let l = I.find_unify p p_set.root_pos_index in
let inactive = { clause; side; path } in
List.fold_left (fun acc (_, u, l) ->
List.fold_left (fun acc active ->
superposition p_set.rules acc u active inactive
) acc l
) acc l
let add_active_supp p_set clause side s acc =
let l = I.find_unify s p_set.inactive_index in
let active = { clause; side; path = Position.root } in
List.fold_left (fun acc (t, u, l) ->
match t with
| { Expr.term = Expr.Meta _ } -> acc
| _ -> List.fold_left (fun acc inactive ->
superposition p_set.rules acc u active inactive
) acc l
) acc l
Given a new clause , find and apply all instances of SN & SP ,
using the two functions defined above .
using the two functions defined above. *)
let supp_lit c p_set acc =
freshen the clause to ensure it will have distinct variables
from any other clause ( necessary because of how unificaiton is implemented ) ,
inclduing itself ( since inferences between two instance of the same clause
can yield interesting results )
from any other clause (necessary because of how unificaiton is implemented),
inclduing itself (since inferences between two instance of the same clause
can yield interesting results) *)
let c = freshen c in
match c.lit with
| Empty -> acc
| Eq (a, b) ->
begin match Lpo.compare a b with
| Comparison.Gt ->
add_active_supp p_set c Left a
(Position.Term.fold (add_passive_supp p_set c Left) acc a)
| Comparison.Lt ->
add_active_supp p_set c Right b
(Position.Term.fold (add_passive_supp p_set c Right) acc b)
| Comparison.Incomparable ->
add_active_supp p_set c Left a
(add_active_supp p_set c Right b
(Position.Term.fold (add_passive_supp p_set c Left)
(Position.Term.fold (add_passive_supp p_set c Right) acc b) a))
| Comparison.Eq -> assert false (* trivial clauses should have been filtered *)
end
| Neq (a, b) ->
begin match Lpo.compare a b with
| Comparison.Gt ->
Position.Term.fold (add_passive_supp p_set c Left) acc a
| Comparison.Lt ->
Position.Term.fold (add_passive_supp p_set c Right) acc b
| Comparison.Incomparable ->
Position.Term.fold (add_passive_supp p_set c Left)
(Position.Term.fold (add_passive_supp p_set c Right) acc b) a
| Comparison.Eq -> acc
end
Rewriting of litterals , i.e RP & RN
Since RP & RN are simplification rules , using the discount loop ,
we only have to implement that inactive side of the rules .
Indeed the discount loop will only ask us to simplify a given
clause using a set of clauses , so given a clause to simplify ,
we only have to find all active clauses that can be used to
simplify it .
Here , given a term [ u ] ( together with its [ side ] and [ path ]
inside [ clause ] ) , we want to find an instance of a clause
in [ p_set ] that might be used to rewrite [ u ]
Since RP & RN are simplification rules, using the discount loop,
we only have to implement that inactive side of the rules.
Indeed the discount loop will only ask us to simplify a given
clause using a set of clauses, so given a clause to simplify,
we only have to find all active clauses that can be used to
simplify it.
Here, given a term [u] (together with its [side] and [path]
inside [clause]), we want to find an instance of a clause
in [p_set] that might be used to rewrite [u]
*)
let rewrite p active inactive =
if ((is_eq inactive.clause && p.rules.rp) ||
(not @@ is_eq inactive.clause && p.rules.rn)) then
CCOpt.map (fun x -> p, x) @@ do_rewrite active inactive
else
None
let add_inactive_rewrite p_set clause side path u =
(* TODO: use find_match *)
let l = I.find_equal u p_set.root_pos_index in
let inactive = { clause; side; path } in
CCList.find_map (fun (_, l') ->
CCList.find_map (fun active ->
rewrite p_set active inactive) l') l
Simplification function using the rules RN & RP . Returns
[ Some c ' ] if the clause can be simplified into a clause [ c ' ] ,
[ None ] otherwise .
[Some c'] if the clause can be simplified into a clause [c'],
[None] otherwise. *)
let rewrite_lit p_set c =
match c.lit with
| Empty -> None
| Eq (s, t) | Neq (s, t) ->
let res = Position.Term.find_map (add_inactive_rewrite p_set c Left) s in
begin match res with
| Some _ -> res
| None ->
Position.Term.find_map (add_inactive_rewrite p_set c Right) t
end
(* Equality_subsumption, alias ES
Simalarly than above, we only want to check wether a given clause is redundant
with regards to a set of clauses. Returns [true] if the given clause is redundant
(i.e. can be simplified using the ES rule), [false] otherwise.
*)
let equality_subsumption p_set c =
if not p_set.rules.es then None
else match c.lit with
| Empty | Neq _ -> None
| Eq (a, b) ->
begin match make_eq p_set a b with
| `Equal -> assert false (* trivial clause should have been eliminated *)
| `Impossible -> None
| `Substitutable (path, l) ->
let aux clause (pointer, rho) =
do_subsumption rho pointer { clause; path; side = Left;}
in
let c' = List.fold_left aux c l in
if c == c' then None else Some (p_set, c')
end
let merge_aux p active inactive mgm =
let s, t = extract active in
let u, v = extract inactive in
assert (Expr.Term.equal (Mapping.apply_term ~fix:false mgm u) s);
match Match.term mgm v t with
| alpha -> do_merging p active inactive (simpl_mapping alpha)
| exception Match.Impossible_ty _ -> None
| exception Match.Impossible_term _ -> None
let merge_sided p clause side x index =
let inactive = { clause; path = Position.root; side; } in
let l = I.find_match x index in
CCList.find_map (fun (_, mgm, l') ->
CCList.find_map (fun active ->
merge_aux p active inactive mgm
) l') l
let merge p_set clause =
let index = if is_eq clause then p_set.root_pos_index else p_set.root_neg_index in
match clause.lit with
| Empty -> None
| Eq (a, b)
| Neq (a, b) ->
begin match merge_sided p_set clause Left a index with
| (Some _) as res -> res
| None -> merge_sided p_set clause Right b index
end
(* Main functions *)
(* ************************************************************************ *)
(* Applies: TD1, TD2 *)
let trivial c p =
match c.lit with
| Eq (a, b) when Expr.Term.equal a b -> true (* TD1 *)
| _ when C.is_empty c.map -> true (* TD2 *)
| _ ->
(c.depth > p.max_depth && p.max_depth > 0) (* max depth criterion *)
|| S.mem c p.clauses (* Simple redundancy criterion *)
Fixpoint for simplification rules
let rec fix f p clause =
if trivial clause p then p, clause
else match f p clause with
| None -> p, clause
| Some (p', clause') ->
Util.debug ~section:p.section "(simpl) %a" pp clause';
fix f p' clause'
let (|>>) f g = fun p x ->
match f p x with
| None -> g p x
| (Some _) as res -> res
Applies : ES , RP , RN , MP , MN
let simplify c p =
let aux = equality_subsumption |>>
merge |>> rewrite_lit in
fix aux p c
(* Applies: ES, RP, RN *)
let cheap_simplify c p =
let aux = equality_subsumption |>> rewrite_lit in
snd (fix aux p c)
Applies : ER , SP , SN
let generate c p =
supp_lit c p (equality_resolution p c [])
(* Analyze a derivation to record all rewrites *)
(* ************************************************************************ *)
(* Main loop *)
(* ************************************************************************ *)
Enqueue a new clause in p
let enqueue c p =
if S.mem c p.generated then p
else begin
let generated = S.add c p.generated in
let c' = cheap_simplify c p in
if not (c == c') then
(* If clause has changed, print the original *)
Util.debug ~section:p.section " |~ %a" pp c;
Test triviality of the clause . Second test is against
p.generated ( and not generated ) because if c = = c ' , then
we 'd have a problem .
p.generated (and not generated) because if c == c', then
we'd have a problem. *)
if trivial c' p || S.mem c' p.generated then begin
Util.debug ~section:p.section " |- %a" pp c';
{ p with generated }
end else begin
(* The clause is interesting and we add it to generated
as well as the queue. *)
Util.debug ~section:p.section " |+ %a" pp c';
let queue = Q.insert c' p.queue in
let generated = S.add c' generated in
{ p with queue; generated; }
end
end
let rec generate_new ~merge p_set c =
let l = generate c p_set in
if merge && not p_set.rules.mn && not p_set.rules.mp then l
else begin
let rules = mk_rules ~default:false ~mn:p_set.rules.mn ~mp:p_set.rules.mp () in
let tmp = empty
~max_depth:p_set.max_depth ~rules
(Section.make ~parent:p_set.section "tmp")
in
let p = List.fold_right enqueue l tmp in
let p' = discount_loop ~merge:false p in
assert (Q.is_empty p'.queue);
S.elements p'.clauses
end
and discount_loop ~merge p_set =
match Q.take p_set.queue with
| None -> p_set
| Some (u, cl) ->
(* Simplify the clause to add *)
Util.debug ~section:p_set.section "Simplifying: @[<hov>%a@]" pp cl;
let p_set, c = simplify cl p_set in
(* If trivial or redundant, forget it and continue *)
if trivial c p_set then begin
Util.debug ~section:p_set.section "Trivial clause : %a" pp c;
discount_loop ~merge { p_set with queue = u }
end else begin
Util.debug ~section:p_set.section "@{<yellow>Adding clause@} : %a" pp c;
if c.lit = Empty then begin
(* Call the callback *)
CCOpt.iter (fun f ->
Util.debug ~section:p_set.section
"@{<magenta>Found empty clause reached@}, %d clauses in state" (S.cardinal p_set.clauses);
f (Lazy.force c.rewrites) (C.elements c.map)) p_set.callback;
(* Continue solving *)
discount_loop ~merge
{ p_set with clauses = S.add c p_set.clauses; queue = u }
end else begin
(* Add the clause to the set. *)
let p_set = add_clause c p_set in
(* Keep the clauses in the set inter-simplified *)
let p_set, t = S.fold (fun p (p_set, t) ->
let p_aux = rm_clause p p_set in
let p_set', p' = simplify p p_aux in
if p == p' then (* no simplification *)
(p_set, t)
else begin (* clause has been simplified, prepare to queue it back *)
Util.debug ~section:p_set.section "@{<Red>Removing@}: %a" pp p;
(p_set', S.add p' t)
end) p_set.clauses (p_set, S.empty) in
(* Generate new inferences *)
let l = generate_new ~merge p_set c in
Util.debug ~section:p_set.section "@{<green>Generated %d (%d) inferences@}"
(List.length l) (S.cardinal t);
let t = List.fold_left (fun s p -> S.add p s) t l in
(* Do a cheap simplify on the new clauses, and then add them to the queue. *)
let p = S.fold enqueue t { p_set with queue = u } in
discount_loop ~merge p
end
end
(* Wrappers/Helpers for unification *)
(* ************************************************************************ *)
let meta_to_var a b =
let mtys, mterms = Expr.Meta.merge_fm (Expr.Term.fm a) (Expr.Term.fm b) in
let m =
List.fold_left (fun acc m ->
Mapping.Meta.bind_term acc m (
Expr.Term.of_id @@ new_var (Mapping.apply_ty acc Expr.(m.meta_type)))
) (List.fold_left (fun acc m ->
Mapping.Meta.bind_ty acc m (Expr.Ty.of_id @@ new_ty_var ())
) Mapping.empty mtys) mterms in
Mapping.apply_term m a, Mapping.apply_term m b, m
let add_eq t ?f a b =
let a', b', m = meta_to_var a b in
let map = C.singleton m in
let fv = clause_fv a' b' map in
let c = mk_eq a' b' map (Hyp (f, fv)) in
enqueue c t
let add_neq t ?f a b =
let a', b', m = meta_to_var a b in
let map = C.singleton m in
let fv = clause_fv a' b' map in
let c = mk_neq a' b' map (Hyp (f, fv)) in
enqueue c t
let debug t =
Util.debug ~section:t.section "@{<White>Precedence@}: @[<hov>%a@]" pp_precedence t;
let l = List.sort (fun c c' -> Pervasives.compare c.id c'.id) @@ S.elements t.clauses in
List.iter (fun c -> Util.debug ~section:t.section " |%@ %a" pp c) l
let solve t =
debug t;
discount_loop ~merge:true t
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/algos/superposition.ml | ocaml | Types
************************************************************************
Type of reasons for clauses.
Unique id (for printing and tracking through logs)
Contents of the clause
Current mapping for variables & meta-variables
Reason of the clause
Depth of the inference chain that leads to this clause.
List of rewrites used to reach this clause.
Weight computing
************************************************************************
Alpha-renaming
************************************************************************
Substitutions
************************************************************************
can s be composed with another mapping to be equal/included in s'
Mapping composition
Mapping merging
Free variables in clauses
************************************************************************
All meta-variable should be bound to variables, so no meta-variables
should appear in the codomain of the mappings
Clauses
************************************************************************
Misc functions on clauses
Comparison of clauses
Printing of clauses
If the reason is ER, then the resulting clause is the empty clause,
which we always want
Fresh clauses shouldn't increa depths.
Don't increase the depth for simplifications steps.
Clauses
Clause freshening
************************************************************************
Clause pointers
************************************************************************
************************************************************************
Symbol precedence
************************************************************************
Help functions
************************************************************************
Perform an equality resolution, i.e rule ER
Merge the substitutions.
Check the guards of the rule
Apply substitution
This should not happen
Perform a rewrite, i.e. either rule RN or RP
[active] is the equality used for the rewrite
[inactive] is the clause being worked on
[rho] is the substitution that matches [active] and [inactive]
currently the substitution must be the identity
shouldn't really happen
should be enforced by the index.
Perform equality subsumption
Perform clause merging
Inference rules
************************************************************************
Equality resolution, alias ER
not is_eq &&
trivial clauses should have been filtered
TODO: use find_match
Equality_subsumption, alias ES
Simalarly than above, we only want to check wether a given clause is redundant
with regards to a set of clauses. Returns [true] if the given clause is redundant
(i.e. can be simplified using the ES rule), [false] otherwise.
trivial clause should have been eliminated
Main functions
************************************************************************
Applies: TD1, TD2
TD1
TD2
max depth criterion
Simple redundancy criterion
Applies: ES, RP, RN
Analyze a derivation to record all rewrites
************************************************************************
Main loop
************************************************************************
If clause has changed, print the original
The clause is interesting and we add it to generated
as well as the queue.
Simplify the clause to add
If trivial or redundant, forget it and continue
Call the callback
Continue solving
Add the clause to the set.
Keep the clauses in the set inter-simplified
no simplification
clause has been simplified, prepare to queue it back
Generate new inferences
Do a cheap simplify on the new clauses, and then add them to the queue.
Wrappers/Helpers for unification
************************************************************************ | This file is free software , part of Archsat . See file " LICENSE " for more details .
This module uses unitary supperposition to
unify terms modulo equality .
For a reference , see :
' E , a brainiac theorem prover ' by .
This module uses unitary supperposition to
unify terms modulo equality.
For a reference, see :
'E, a brainiac theorem prover' by shulz.
*)
module C = Set.Make(Mapping)
type side = Left | Right
type lit =
| Empty
| Eq of Expr.term * Expr.term
| Neq of Expr.term * Expr.term
type reason =
| Hyp of Expr.formula option * Mapping.t
| Fresh of clause * Mapping.t
| ER of clause * Mapping.t
| ES of pointer * pointer * Mapping.t
| SN of pointer * pointer * Mapping.t
| SP of pointer * pointer * Mapping.t
| RN of pointer * pointer * Mapping.t
| RP of pointer * pointer * Mapping.t
| MN of pointer * pointer * Mapping.t
| MP of pointer * pointer * Mapping.t
Type for unit clauses , i.e clauses with at most one equation
and clause = {
weight of the clause ( clauses with lesser
weight are selected first )
weight are selected first) *)
(Expr.formula * Mapping.t) list Lazy.t;
}
and pointer = {
clause : clause;
side : side;
path : Position.t;
}
let rec term_size acc = function
| { Expr.term = Expr.App (_, _, l) } ->
List.fold_left term_size (acc + 1) l
| _ -> acc + 1
let bind_leaf_ty _ ty acc =
match ty with
| { Expr.ty = Expr.TyApp _ } -> raise Exit
| { Expr.ty = Expr.TyVar v } ->
if Mapping.Var.mem_ty acc v then raise Exit
else Mapping.Var.bind_ty acc v Expr.Ty.base
| { Expr.ty = Expr.TyMeta m } ->
if Mapping.Meta.mem_ty acc m then raise Exit
else Mapping.Meta.bind_ty acc m Expr.Ty.base
let bind_leaf_term _ term acc =
match term with
| { Expr.term = Expr.App _ } -> raise Exit
| { Expr.term = Expr.Var v } ->
if Mapping.Var.mem_term acc v then raise Exit
else Mapping.Var.bind_term acc v (Expr.Term.of_id v)
| { Expr.term = Expr.Meta m } ->
if Mapping.Meta.mem_term acc m then raise Exit
else Mapping.Meta.bind_term acc m (Expr.Term.of_meta m)
let is_alpha m =
try
let _ = Mapping.fold
~ty_var:bind_leaf_ty
~ty_meta:bind_leaf_ty
~term_var:bind_leaf_term
~term_meta:bind_leaf_term
m Mapping.empty
in true
with Exit -> false
let simpl_mapping = Mapping.remove_refl
let match_subst s s' =
let aux get f_match x t acc =
let t' = get s' x in
f_match acc t t'
in
let ty_var = aux Mapping.Var.get_ty Match.ty in
let ty_meta = aux Mapping.Meta.get_ty Match.ty in
let term_var = aux Mapping.Var.get_term Match.term in
let term_meta = aux Mapping.Meta.get_term Match.term in
Mapping.fold ~ty_var ~term_var ~ty_meta ~term_meta s Mapping.empty
let (<) s t =
try
let _ = match_subst s t in
true
with
| Not_found
| Match.Impossible_ty _
| Match.Impossible_term _ -> false
let (<<) t t' =
C.for_all (fun s' -> C.exists (fun s -> s < s') t) t'
let compose_set set rho =
C.map (Mapping.apply rho) set
let merge_aux s s' =
let aux get f_match x t acc =
match get s' x with
| t' -> f_match acc t t'
| exception Not_found -> acc
in
let ty_var = aux Mapping.Var.get_ty Unif.Robinson.ty in
let ty_meta = aux Mapping.Meta.get_ty Unif.Robinson.ty in
let term_var = aux Mapping.Var.get_term Unif.Robinson.term in
let term_meta = aux Mapping.Meta.get_term Unif.Robinson.term in
Mapping.fold ~ty_var ~term_var ~ty_meta ~term_meta s Mapping.empty
let merge s s' =
match merge_aux s s' with
| exception Unif.Robinson.Impossible_ty _ -> None
| exception Unif.Robinson.Impossible_term _ -> None
| rho ->
let aux ~eq ~f = function
| None, None -> assert false
| Some x, None
| None, Some x -> Some (f x)
| Some x, Some y ->
let x' = f x in
let y' = f y in
assert (eq x' y');
Some x'
in
let rho' = Mapping.stretch (Mapping.stretch rho s) s' in
let aux_ty _ opt opt' =
aux ~eq:Expr.Ty.equal ~f:(Mapping.apply_ty rho') (opt, opt') in
let aux_term _ opt opt' =
aux ~eq:Expr.Term.equal ~f:(Mapping.apply_term rho') (opt, opt') in
Some (rho', Mapping.merge
~ty_var:aux_ty ~ty_meta:aux_ty
~term_var:aux_term ~term_meta:aux_term
s s')
let merge_set set set' =
C.fold (fun s acc ->
C.fold (fun s' acc' ->
match merge s s' with
| None -> acc'
| Some s'' -> s'' :: acc'
) set' acc) set []
let clause_mapped_vars map =
C.fold (fun m acc ->
match Mapping.codomain m with
| (fv, ([], [])) -> Expr.Id.merge_fv fv acc
| _ ->
Util.error "Meta-variable in codomain of a map in superposisiton";
assert false
) map ([], [])
let clause_fv a b map =
let mapped_vars = clause_mapped_vars map in
let free_vars = Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b) in
let l, l' = Expr.Id.remove_fv free_vars mapped_vars in
List.fold_left (fun m v ->
Mapping.Var.bind_ty m v (Expr.Ty.of_id v))
(List.fold_left (fun m v ->
Mapping.Var.bind_term m v (Expr.Term.of_id v)) Mapping.empty l') l
let is_eq c =
match c.lit with
| Eq _ -> true
| Neq _ | Empty -> false
let _discr = function
| Empty -> 0
| Eq _ -> 1
| Neq _ -> 2
let compare c c' =
match c.lit, c'.lit with
| Empty, Empty -> C.compare c.map c'.map
| Eq (a, b), Eq (a', b')
| Neq (a, b), Neq (a', b') ->
CCOrd.(Expr.Term.compare a a'
<?> (Expr.Term.compare, b, b')
<?> (C.compare, c.map, c'.map))
| x, y -> Pervasives.compare (_discr x) (_discr y)
let rec pp_id fmt c =
match c.reason with
| Fresh (c', _) -> Format.fprintf fmt "~%a" pp_id c'
| _ -> Format.fprintf fmt "C%d" c.id
let pp_pos fmt pos =
let dir = if pos.side = Left then "→" else "←" in
Format.fprintf fmt "%a%s%a" pp_id pos.clause dir Position.print pos.path
let pp_reason fmt c =
match c.reason with
| Hyp _ -> Format.fprintf fmt "hyp"
| Fresh (c, _) -> Format.fprintf fmt "Fresh(%a)" pp_id c
| ER (d, _) -> Format.fprintf fmt "ER(%a)" pp_id d
| SN (d, e, _) -> Format.fprintf fmt "SN(%a;%a)" pp_pos d pp_pos e
| SP (d, e, _) -> Format.fprintf fmt "SP(%a;%a)" pp_pos d pp_pos e
| ES (d, e, _) -> Format.fprintf fmt "ES(%a;%a)" pp_pos d pp_pos e
| RN (d, e, _) -> Format.fprintf fmt "RN(%a;%a)" pp_pos d pp_pos e
| RP (d, e, _) -> Format.fprintf fmt "RP(%a;%a)" pp_pos d pp_pos e
| MN (d, e, _) -> Format.fprintf fmt "ME(%a;%a)" pp_pos d pp_pos e
| MP (d, e, _) -> Format.fprintf fmt "ME(%a;%a)" pp_pos d pp_pos e
let pp_cmp ~pos fmt (a, b) =
let s = Comparison.to_string (Lpo.compare a b) in
let s' =
if pos then s
else CCString.flat_map (function
| '=' -> "≠" | c -> CCString.of_char c) s
in
Format.fprintf fmt "%s" s'
let pp_lit fmt c =
match c.lit with
| Empty -> Format.fprintf fmt "∅"
| Eq (a, b) ->
Format.fprintf fmt "@[%a@ %a@ %a@]"
Expr.Print.term a (pp_cmp ~pos:true) (a, b) Expr.Print.term b
| Neq (a, b) ->
Format.fprintf fmt "@[%a@ %a@ %a@]"
Expr.Print.term a (pp_cmp ~pos:false) (a, b) Expr.Print.term b
let pp_map fmt map =
C.iter (fun m -> Format.fprintf fmt "@,[%a]" Mapping.print m) map
let debug_map fmt map =
C.iter (fun m -> Format.fprintf fmt "@,[%a]" Mapping.debug m) map
let pp fmt (c:clause) =
Format.fprintf fmt "@[<hov 2>%a[%d]@,@,[%a]@,[%a]%a@]"
pp_id c c.depth pp_reason c pp_lit c pp_map c.map
let pp_hyps fmt c =
match c.reason with
| Hyp _ -> ()
| ER (c, _) | Fresh (c, _) ->
Format.fprintf fmt "%a" pp c
| SN (d, e, _) | SP (d, e, _)
| RN (d, e, _) | RP (d, e, _)
| MN (d, e, _) | MP (d, e, _)
| ES (d, e, _) ->
Format.fprintf fmt "%a@\n%a" pp d.clause pp e.clause
Heuristics for clauses . Currently uses the size of terms .
NOTE : currently , weight does not take the subst into account so that
clauses that might be merged have the same weight and thus are
added together .
TODO : merge clauses in the queue ?
TODO : better heuristic for clause selection .
NOTE: currently, weight does not take the subst into account so that
clauses that might be merged have the same weight and thus are
added together.
TODO: merge clauses in the queue ?
TODO: better heuristic for clause selection.
*)
let compute_weight = function
| Empty -> -1
| Eq (a, b) -> 2 * (term_size (term_size 0 b) a)
| Neq (a, b) -> 1 * (term_size (term_size 0 b) a)
Disequalities have smaller weight because we are more interested
in them ( better chance to apply rule ER , and get a solution )
in them (better chance to apply rule ER, and get a solution) *)
let compute_depth = function
Hypotheses are at depth 0 .
| Hyp _ -> 1
| ER _ -> 0
Superposition steps increase depth
| SN (c, c', _) | SP (c, c', _)
-> max c.clause.depth c'.clause.depth + 1
| Fresh (c, _) -> c.depth
| ES (c, c', _)
| RN (c, c', _) | RP (c, c', _)
| MN (c, c', _) | MP (c, c', _)
-> max c.clause.depth c'.clause.depth
let leq_cl c c' =
c.weight <= c'.weight || (
c.weight = c'.weight &&
C.cardinal c.map >= C.cardinal c'.map
)
TODO : use sets of rewrites to save some space
let map_rewrites m l =
let apply m m' =
let tmp = Mapping.apply m m' in
if Mapping.equal tmp m' then m' else tmp
in
List.map (fun (f, m') -> (f, apply m m')) l
let rec compute_rewrites = function
| Hyp (f, m) ->
if Mapping.is_empty m then [] else
begin match f with
| Some formula -> [formula, m]
| None ->
Util.error "Clause with free_vars but no tagged formula";
[]
end
| Fresh (c', m) | ER (c', m)
-> map_rewrites m (Lazy.force c'.rewrites)
| ES (p, p', m)
| SN (p, p', m) | SP (p, p', m)
| RN (p, p', m) | RP (p, p', m)
| MN (p, p', m) | MP (p, p', m)
-> map_rewrites m (Lazy.force p.clause.rewrites @
Lazy.force p'.clause.rewrites)
let mk_cl =
let i = ref 0 in
(fun lit map reason ->
incr i;
let weight = compute_weight lit in
let depth = compute_depth reason in
let rewrites = lazy (compute_rewrites reason) in
let res = { id = !i; lit; map; reason; weight; depth; rewrites } in
Obsolete , now that there are rewrite rules
assert (
let lty , lt = match lit with
| Empty - > [ ] , [ ]
| Eq ( a , b )
| Neq ( a , b ) - > Expr . Id.merge_fv ( Expr.Term.fv a ) ( Expr.Term.fv b )
in
let b = ( fun m - >
let ( ( vty , vt ) , m ) = Mapping.codomain m in
m = ( [ ] , [ ] ) & &
CCList.subset ~eq : . Id. Ttype.equal lty vty & &
CCList.subset ~eq : . Id. Ty.equal lt vt
) map in
if not b then " % a " pp res ;
b
) ;
assert (
let lty,lt = match lit with
| Empty -> [], []
| Eq (a, b)
| Neq (a, b) -> Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b)
in
let b = C.for_all (fun m ->
let ((vty,vt), m) = Mapping.codomain m in
m = ([], []) &&
CCList.subset ~eq:Expr.Id.Ttype.equal lty vty &&
CCList.subset ~eq:Expr.Id.Ty.equal lt vt
) map in
if not b then Util.debug "%a" pp res;
b
);
*)
res
)
let ord a b = if Expr.Term.compare a b <= 0 then a, b else b, a
let mk_empty map clause mgu =
mk_cl Empty map (ER (clause, mgu))
let mk_eq a b map reason =
let c, d = ord a b in
mk_cl (Eq (c, d)) map reason
let mk_neq a b map reason =
let c, d = ord a b in
mk_cl (Neq (c, d)) map reason
let counter = ref 0
let new_ty_var =
(fun () -> incr counter; Expr.Id.ttype (Format.sprintf "?%d" !counter))
let new_var =
(fun ty -> incr counter; Expr.Id.ty (Format.sprintf "?%d" !counter) ty)
let fresh a b map =
assert (Expr.Term.fm a = ([], []));
assert (Expr.Term.fm b = ([], []));
let tys, terms = Expr.Id.merge_fv (Expr.Term.fv a) (Expr.Term.fv b) in
let m =
List.fold_left (fun acc v ->
Mapping.Var.bind_term acc v (
Expr.Term.of_id @@ new_var (Mapping.apply_ty acc Expr.(v.id_type)))
) (List.fold_left (fun acc v ->
Mapping.Var.bind_ty acc v (Expr.Ty.of_id @@ new_ty_var ())
) Mapping.empty tys) terms
in
let m = C.fold (CCFun.flip Mapping.stretch) map
(Mapping.expand (Mapping.expand m a) b) in
Util.debug " @[<hv 2 > fresh:@ % a@ % a " Mapping.print m pp_map map ;
m, (Mapping.apply_term m a), (Mapping.apply_term m b), (compose_set map m)
let freshen c =
match c.lit with
| Empty -> c
| Eq (a, b)
| Neq (a, b) ->
let f = if is_eq c then mk_eq else mk_neq in
let r, a', b', m' = fresh a b c.map in
f a' b' m' (Fresh (c, r))
let compare_side a b = match a, b with
| Left, Left | Right, Right -> 0
| Left, Right -> -1 | Right, Left -> 1
let compare_pointer pc pc' =
match compare pc.clause pc'.clause with
| 0 -> begin match compare_side pc.side pc'.side with
| 0 -> Position.compare pc.path pc'.path
| x -> x
end
| x -> x
Supperposition state
module M = Map.Make(Expr.Term)
module Q = CCHeap.Make(struct type t = clause let leq = leq_cl end)
module Q = struct
type t = {
top : clause list ;
bot : clause list ;
}
let empty = {
top = [ ] ;
bot = [ ] ;
}
let fold f acc q =
let acc ' = List.fold_left f acc q.top in
List.fold_left f acc ' q.bot
let insert c q =
{ q with bot = c : : }
let rec take q =
match q.top with
| x : : r - > Some ( { q with top = r } , x )
| [ ] - >
begin match with
| [ ] - > None
| l - > take { top = List.rev l ; bot = [ ] }
end
end
module Q = struct
type t = {
top : clause list;
bot : clause list;
}
let empty = {
top = [];
bot = [];
}
let fold f acc q =
let acc' = List.fold_left f acc q.top in
List.fold_left f acc' q.bot
let insert c q =
{ q with bot = c :: q.bot }
let rec take q =
match q.top with
| x :: r -> Some ({q with top = r }, x)
| [] ->
begin match q.bot with
| [] -> None
| l -> take { top = List.rev l; bot = [] }
end
end
*)
module S = Set.Make(struct type t = clause let compare = compare end)
module I = Index.Make(struct type t = pointer let compare = compare_pointer end)
type rules = {
er : bool; es : bool;
sn : bool; sp : bool;
rn : bool; rp : bool;
mn : bool; mp : bool;
}
let mk_rules ~default
?(er=default) ?(es=default)
?(sn=default) ?(sp=default)
?(rn=default) ?(rp=default)
?(mn=default) ?(mp=default)
() =
{
er; es;
sn; sp;
rn; rp;
mn; mp;
}
type t = {
queue : Q.t;
clauses : S.t;
generated : S.t;
rules : rules;
root_pos_index : I.t;
root_neg_index : I.t;
inactive_index : I.t;
max_depth : int;
section : Section.t;
callback :
((Expr.formula * Mapping.t) list -> Mapping.t list -> unit) option;
}
let all_rules = {
er = true;
es = true;
sn = true;
sp = true;
rp = true;
rn = true;
mn = true;
mp = true;
}
let empty ?(max_depth=0) ?(rules=all_rules) ?callback section = {
queue = Q.empty;
clauses = S.empty;
generated = S.empty;
section; callback; rules; max_depth;
root_pos_index = I.empty (Section.make ~parent:section "pos_index");
root_neg_index = I.empty (Section.make ~parent:section "neg_index");
inactive_index = I.empty (Section.make ~parent:section "all_index");
}
let fold_subterms f e side clause i =
Position.Term.fold (fun i path t -> f t { path; side; clause } i) i e
let change_state_aux f_set f_index c t eq a b =
let l = match Lpo.compare a b with
| Comparison.Lt -> [b, Right] | Comparison.Gt -> [a, Left]
| Comparison.Incomparable -> [a, Left; b, Right]
| Comparison.Eq -> []
in
{ t with
clauses = f_set c t.clauses;
root_pos_index =
if eq then
List.fold_left (fun i (t, side) ->
f_index t { path = Position.root; side; clause = c } i)
t.root_pos_index l
else
t.root_pos_index;
root_neg_index =
if not eq then
List.fold_left (fun i (t, side) ->
f_index t { path = Position.root; side; clause = c } i)
t.root_neg_index l
else
t.root_neg_index;
inactive_index =
List.fold_left (fun i (t, side) ->
fold_subterms f_index t side c i) t.inactive_index l;
}
let change_state f_set f_index c t =
match c.lit with
| Eq (a, b) -> change_state_aux f_set f_index c t true a b
| Neq (a, b) -> change_state_aux f_set f_index c t false a b
| Empty -> { t with clauses = f_set c t.clauses }
let add_clause = change_state S.add I.add
let rm_clause = change_state S.remove I.remove
module Symbols = Set.Make(Expr.Id.Const)
let rec term_symbols acc = function
| { Expr.term = Expr.Var _ }
| { Expr.term = Expr.Meta _ } -> acc
| { Expr.term = Expr.App (f, _, l) } ->
List.fold_left term_symbols (Symbols.add f acc) l
let clause_symbols acc c =
match c.lit with
| Empty -> acc
| Eq (a, b) | Neq (a, b) ->
term_symbols (term_symbols acc a) b
let set_symbols t =
let s = Symbols.empty in
let s' = Q.fold clause_symbols s t.queue in
S.fold (CCFun.flip clause_symbols) t.clauses s'
let pp_precedence fmt t =
let s = set_symbols t in
let l = Symbols.elements s in
let sep fmt () = Format.fprintf fmt " <@ " in
CCFormat.list ~sep Expr.Id.Const.print fmt l
let extract pos =
match pos.side, pos.clause.lit with
| Left, (Eq (a, b) | Neq (a, b))
| Right, (Eq (b, a) | Neq (b, a)) -> a, b
| _, Empty -> assert false
let do_resolution ~section acc clause =
match clause.lit with
| Eq _ | Empty -> acc
| Neq (s, t) ->
let sigma = clause.map in
begin match Unif.Robinson.term Mapping.empty s t with
| mgu ->
let mgu = C.fold (CCFun.flip Mapping.stretch) sigma mgu in
mk_empty (compose_set sigma mgu) clause mgu :: acc
| exception Unif.Robinson.Impossible_ty _ -> acc
| exception Unif.Robinson.Impossible_term _ -> acc
end
Perform a superposition , i.e either rule SN or SP
[ active ] is ( the position of ) the equality used to perform the substitution ,
[ inactive ] is ( the position of ) the clause the substitution is being performed on
[ mgu ] is the subtitution that unifies [ active ] and [ inactive ]
TODO : check the LPO constraints iff it really need to be checked
i.e. only when the ordering failed on the non - instanciated clause
[active] is (the position of) the equality used to perform the substitution,
[inactive] is (the position of) the clause the substitution is being performed on
[mgu] is the subtitution that unifies [active] and [inactive]
TODO: check the LPO constraints iff it really need to be checked
i.e. only when the ordering failed on the non-instanciated clause
*)
let do_supp acc sigma'' active inactive =
assert (is_eq active.clause);
assert (Position.equal active.path Position.root);
let p = inactive.path in
let s, t = extract active in
let u, v = extract inactive in
let sigma = active.clause.map in
let sigma' = inactive.clause.map in
let m = List.fold_left Mapping.expand sigma'' [s; t; u; v] in
let m = C.fold (CCFun.flip Mapping.stretch) sigma m in
let m = C.fold (CCFun.flip Mapping.stretch) sigma' m in
let res1 = compose_set sigma m in
let res2 = compose_set sigma' m in
let l = merge_set res1 res2 in
Util.debug " @[<v 2 > supp:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print m ;
Util.debug "@[<v 2>supp:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print m;
*)
let apply = Mapping.apply_term m in
let v' = apply v in
let t' = apply t in
let s' = apply s in
let u' = apply u in
let u_res, u_p_opt = Position.Term.apply p u in
Check that mgu effectively unifies u_p and s
assert (match u_p_opt with
| None -> false
| Some u_p -> Expr.Term.equal s' (apply u_p));
if Lpo.compare t' s' = Comparison.Gt ||
Lpo.compare v' u' = Comparison.Gt ||
fst (Position.Term.apply p u) = Position.Var then
acc
else begin
match Position.Term.substitute inactive.path ~by:t' u' with
| Some u'' ->
let f = if is_eq inactive.clause then mk_eq else mk_neq in
List.fold_left (fun acc (rho, res) ->
let subst, u''', v'', map = fresh
(Mapping.apply_term rho u'')
(Mapping.apply_term rho v')
(C.singleton res)
in
let subst = Mapping.stretch subst m in
let reason =
if is_eq inactive.clause then
SP(active, inactive, Mapping.apply subst m)
else
SN(active, inactive, Mapping.apply subst m)
in
let c = f u''' v'' map reason in
c :: acc) acc l
| None ->
assert false
end
let do_rewrite active inactive =
assert (is_eq active.clause);
assert (Position.equal active.path Position.root);
let sigma = inactive.clause.map in
let s, t = extract active in
let u, v = extract inactive in
Util.debug " @[<v 2 > rwrt:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
pp_map sigma ;
Util.debug "@[<v 2>rwrt:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
pp_map sigma;
*)
let guard =
active.clause.map << sigma &&
Lpo.compare s t = Comparison.Gt &&
(if is_eq inactive.clause then (
not (Lpo.compare u v = Comparison.Gt) ||
not (Position.equal inactive.path Position.root)
) else true)
in
" rwrt failed " ;
else begin
match Position.Term.substitute inactive.path ~by:t u with
| Some u' ->
let f = if is_eq inactive.clause then mk_eq else mk_neq in
let subst, u'', v', map = fresh u' v sigma in
let reason =
if is_eq inactive.clause
then RP(active, inactive, subst)
else RN(active, inactive, subst)
in
Some (f u'' v' map reason)
| None ->
assert false
end
This functions tries to find an equality [ v = w ] in the index ,
used particualrly for computing the ES rule .
used particualrly for computing the ES rule. *)
let find_eq index v w =
CCList.flat_map (fun (_, rho, l) ->
CCList.flat_map (fun pos ->
let s, t = extract pos in
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho v) s);
match Match.term rho w t with
| rho' -> if is_alpha rho' then [pos, rho'] else []
| exception Match.Impossible_ty _ -> []
| exception Match.Impossible_term _ -> []
) l) (I.find_match v index)
This function tries and find if there is an equality in p_set , such
that [ a ] and [ b ] are suceptible to be an equality simplified by the ES rule .
Additionally , for the ES rule , we need to keep track of the position at which
the subtitution takes place . That is the role of the [ curr ] argument .
Returns the list of all potential clauses that could be used to make
[ a ] and [ b ] equal .
that [a] and [b] are suceptible to be an equality simplified by the ES rule.
Additionally, for the ES rule, we need to keep track of the position at which
the subtitution takes place. That is the role of the [curr] argument.
Returns the list of all potential clauses that could be used to make
[a] and [b] equal.
*)
let rec make_eq_aux p_set curr a b =
if Expr.Term.equal a b then `Equal
else
match find_eq p_set.root_pos_index a b with
| [] ->
begin match a, b with
| { Expr.term = Expr.App (f, _, f_args) },
{ Expr.term = Expr.App (g, _, g_args) } when Expr.Id.equal f g ->
make_eq_list p_set curr 0 f_args g_args
| _ -> `Impossible
end
| l -> `Substitutable (curr, l)
and make_eq_list p_set curr idx l l' =
match l, l' with
| [], [] -> `Equal
| a :: r, b :: r' ->
begin match make_eq_aux p_set (Position.follow curr idx) a b with
| `Equal -> make_eq_list p_set curr (idx + 1) r r'
| `Impossible -> `Impossible
| `Substitutable (path, u) as res ->
if List.for_all2 Expr.Term.equal r r' then res else `Impossible
end
| _ ->
Since we only give arguments list of equal functions , the two lists
should always have the same length .
should always have the same length. *)
assert false
let make_eq p_set a b =
make_eq_aux p_set Position.root a b
let do_subsumption rho active inactive =
assert (is_alpha rho);
assert (is_eq active.clause);
assert (is_eq inactive.clause);
assert (Position.equal Position.root active.path);
let sigma = active.clause.map in
let s, t = extract active in
let u, v = extract inactive in
let rho = List.fold_left Mapping.expand rho [u; v] in
Util.debug " @[<v > subsumption:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print rho ;
Util.debug "@[<v>subsumption:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print rho;
*)
assert (
match Position.Term.apply inactive.path u with
| _, None -> false
| _, Some (u_p) ->
Expr.Term.equal s (Mapping.apply_term ~fix:false rho u_p)
);
assert (
match Position.Term.substitute inactive.path
~by:t (Mapping.apply_term ~fix:false rho u) with
| None -> false
| Some u' ->
Expr.Term.equal u' (Mapping.apply_term ~fix:false rho v)
);
let redundant, sigma' = C.partition (fun rho ->
C.exists (fun s -> s < rho) sigma) inactive.clause.map in
if C.is_empty redundant then
inactive.clause
else
mk_eq u v sigma' (ES (active, inactive, rho))
let do_merging p active inactive rho =
assert ((is_eq active.clause && is_eq inactive.clause) ||
(not @@ is_eq active.clause && not @@ is_eq inactive.clause));
let sigma = active.clause.map in
let sigma' = inactive.clause.map in
let s, t = extract active in
let u, v = extract inactive in
Util.debug " @[<v > merging:@ % a@ % a = = % a@ % a@ % a = = % a@ % a@ ] "
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Mapping.print rho ;
Util.debug "@[<v>merging:@ %a@ %a == %a@ %a@ %a == %a@ %a@]"
pp_pos active
Expr.Print.term s Expr.Print.term t
pp_pos inactive
Expr.Print.term u Expr.Print.term v
Mapping.print rho;
*)
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho u) s);
assert (Expr.Term.equal (Mapping.apply_term ~fix:false rho v) t);
if is_alpha rho then begin
let f = if is_eq inactive.clause then mk_eq else mk_neq in
let rho = C.fold (CCFun.flip Mapping.stretch) sigma' rho in
let reason =
if is_eq inactive.clause
then MP (active, inactive, rho)
else MN (active, inactive, rho)
in
let c = C.union sigma (compose_set sigma' rho) in
Util.debug ~section:p.section "@{<Red>Removing@}: %a" pp active.clause;
Some (rm_clause active.clause p, f s t c reason)
end else None
let equality_resolution p_set clause acc =
if not p_set.rules.er then acc
else do_resolution ~section:p_set.section acc clause
Supperposition rules , alias SN & SP
Given a new clause , and the current set of clauses , there are two cases :
- either the new clause might be the active clause in a SN or SP rule
( i.e. the equality used to substitute )
- or it is the inactive clause ( i.e. the clause the substitution is
performed on )
Given a new clause, and the current set of clauses, there are two cases:
- either the new clause might be the active clause in a SN or SP rule
(i.e. the equality used to substitute)
- or it is the inactive clause (i.e. the clause the substitution is
performed on)
*)
let superposition rules acc u active inactive =
if ((is_eq inactive.clause && rules.sp)
do_supp acc u active inactive
else
acc
let add_passive_supp p_set clause side acc path = function
| { Expr.term = Expr.Var _ }
| { Expr.term = Expr.Meta _ } -> acc
| p ->
let l = I.find_unify p p_set.root_pos_index in
let inactive = { clause; side; path } in
List.fold_left (fun acc (_, u, l) ->
List.fold_left (fun acc active ->
superposition p_set.rules acc u active inactive
) acc l
) acc l
let add_active_supp p_set clause side s acc =
let l = I.find_unify s p_set.inactive_index in
let active = { clause; side; path = Position.root } in
List.fold_left (fun acc (t, u, l) ->
match t with
| { Expr.term = Expr.Meta _ } -> acc
| _ -> List.fold_left (fun acc inactive ->
superposition p_set.rules acc u active inactive
) acc l
) acc l
Given a new clause , find and apply all instances of SN & SP ,
using the two functions defined above .
using the two functions defined above. *)
let supp_lit c p_set acc =
freshen the clause to ensure it will have distinct variables
from any other clause ( necessary because of how unificaiton is implemented ) ,
inclduing itself ( since inferences between two instance of the same clause
can yield interesting results )
from any other clause (necessary because of how unificaiton is implemented),
inclduing itself (since inferences between two instance of the same clause
can yield interesting results) *)
let c = freshen c in
match c.lit with
| Empty -> acc
| Eq (a, b) ->
begin match Lpo.compare a b with
| Comparison.Gt ->
add_active_supp p_set c Left a
(Position.Term.fold (add_passive_supp p_set c Left) acc a)
| Comparison.Lt ->
add_active_supp p_set c Right b
(Position.Term.fold (add_passive_supp p_set c Right) acc b)
| Comparison.Incomparable ->
add_active_supp p_set c Left a
(add_active_supp p_set c Right b
(Position.Term.fold (add_passive_supp p_set c Left)
(Position.Term.fold (add_passive_supp p_set c Right) acc b) a))
end
| Neq (a, b) ->
begin match Lpo.compare a b with
| Comparison.Gt ->
Position.Term.fold (add_passive_supp p_set c Left) acc a
| Comparison.Lt ->
Position.Term.fold (add_passive_supp p_set c Right) acc b
| Comparison.Incomparable ->
Position.Term.fold (add_passive_supp p_set c Left)
(Position.Term.fold (add_passive_supp p_set c Right) acc b) a
| Comparison.Eq -> acc
end
Rewriting of litterals , i.e RP & RN
Since RP & RN are simplification rules , using the discount loop ,
we only have to implement that inactive side of the rules .
Indeed the discount loop will only ask us to simplify a given
clause using a set of clauses , so given a clause to simplify ,
we only have to find all active clauses that can be used to
simplify it .
Here , given a term [ u ] ( together with its [ side ] and [ path ]
inside [ clause ] ) , we want to find an instance of a clause
in [ p_set ] that might be used to rewrite [ u ]
Since RP & RN are simplification rules, using the discount loop,
we only have to implement that inactive side of the rules.
Indeed the discount loop will only ask us to simplify a given
clause using a set of clauses, so given a clause to simplify,
we only have to find all active clauses that can be used to
simplify it.
Here, given a term [u] (together with its [side] and [path]
inside [clause]), we want to find an instance of a clause
in [p_set] that might be used to rewrite [u]
*)
let rewrite p active inactive =
if ((is_eq inactive.clause && p.rules.rp) ||
(not @@ is_eq inactive.clause && p.rules.rn)) then
CCOpt.map (fun x -> p, x) @@ do_rewrite active inactive
else
None
let add_inactive_rewrite p_set clause side path u =
let l = I.find_equal u p_set.root_pos_index in
let inactive = { clause; side; path } in
CCList.find_map (fun (_, l') ->
CCList.find_map (fun active ->
rewrite p_set active inactive) l') l
Simplification function using the rules RN & RP . Returns
[ Some c ' ] if the clause can be simplified into a clause [ c ' ] ,
[ None ] otherwise .
[Some c'] if the clause can be simplified into a clause [c'],
[None] otherwise. *)
let rewrite_lit p_set c =
match c.lit with
| Empty -> None
| Eq (s, t) | Neq (s, t) ->
let res = Position.Term.find_map (add_inactive_rewrite p_set c Left) s in
begin match res with
| Some _ -> res
| None ->
Position.Term.find_map (add_inactive_rewrite p_set c Right) t
end
let equality_subsumption p_set c =
if not p_set.rules.es then None
else match c.lit with
| Empty | Neq _ -> None
| Eq (a, b) ->
begin match make_eq p_set a b with
| `Impossible -> None
| `Substitutable (path, l) ->
let aux clause (pointer, rho) =
do_subsumption rho pointer { clause; path; side = Left;}
in
let c' = List.fold_left aux c l in
if c == c' then None else Some (p_set, c')
end
let merge_aux p active inactive mgm =
let s, t = extract active in
let u, v = extract inactive in
assert (Expr.Term.equal (Mapping.apply_term ~fix:false mgm u) s);
match Match.term mgm v t with
| alpha -> do_merging p active inactive (simpl_mapping alpha)
| exception Match.Impossible_ty _ -> None
| exception Match.Impossible_term _ -> None
let merge_sided p clause side x index =
let inactive = { clause; path = Position.root; side; } in
let l = I.find_match x index in
CCList.find_map (fun (_, mgm, l') ->
CCList.find_map (fun active ->
merge_aux p active inactive mgm
) l') l
let merge p_set clause =
let index = if is_eq clause then p_set.root_pos_index else p_set.root_neg_index in
match clause.lit with
| Empty -> None
| Eq (a, b)
| Neq (a, b) ->
begin match merge_sided p_set clause Left a index with
| (Some _) as res -> res
| None -> merge_sided p_set clause Right b index
end
let trivial c p =
match c.lit with
| _ ->
Fixpoint for simplification rules
let rec fix f p clause =
if trivial clause p then p, clause
else match f p clause with
| None -> p, clause
| Some (p', clause') ->
Util.debug ~section:p.section "(simpl) %a" pp clause';
fix f p' clause'
let (|>>) f g = fun p x ->
match f p x with
| None -> g p x
| (Some _) as res -> res
Applies : ES , RP , RN , MP , MN
let simplify c p =
let aux = equality_subsumption |>>
merge |>> rewrite_lit in
fix aux p c
let cheap_simplify c p =
let aux = equality_subsumption |>> rewrite_lit in
snd (fix aux p c)
Applies : ER , SP , SN
let generate c p =
supp_lit c p (equality_resolution p c [])
Enqueue a new clause in p
let enqueue c p =
if S.mem c p.generated then p
else begin
let generated = S.add c p.generated in
let c' = cheap_simplify c p in
if not (c == c') then
Util.debug ~section:p.section " |~ %a" pp c;
Test triviality of the clause . Second test is against
p.generated ( and not generated ) because if c = = c ' , then
we 'd have a problem .
p.generated (and not generated) because if c == c', then
we'd have a problem. *)
if trivial c' p || S.mem c' p.generated then begin
Util.debug ~section:p.section " |- %a" pp c';
{ p with generated }
end else begin
Util.debug ~section:p.section " |+ %a" pp c';
let queue = Q.insert c' p.queue in
let generated = S.add c' generated in
{ p with queue; generated; }
end
end
let rec generate_new ~merge p_set c =
let l = generate c p_set in
if merge && not p_set.rules.mn && not p_set.rules.mp then l
else begin
let rules = mk_rules ~default:false ~mn:p_set.rules.mn ~mp:p_set.rules.mp () in
let tmp = empty
~max_depth:p_set.max_depth ~rules
(Section.make ~parent:p_set.section "tmp")
in
let p = List.fold_right enqueue l tmp in
let p' = discount_loop ~merge:false p in
assert (Q.is_empty p'.queue);
S.elements p'.clauses
end
and discount_loop ~merge p_set =
match Q.take p_set.queue with
| None -> p_set
| Some (u, cl) ->
Util.debug ~section:p_set.section "Simplifying: @[<hov>%a@]" pp cl;
let p_set, c = simplify cl p_set in
if trivial c p_set then begin
Util.debug ~section:p_set.section "Trivial clause : %a" pp c;
discount_loop ~merge { p_set with queue = u }
end else begin
Util.debug ~section:p_set.section "@{<yellow>Adding clause@} : %a" pp c;
if c.lit = Empty then begin
CCOpt.iter (fun f ->
Util.debug ~section:p_set.section
"@{<magenta>Found empty clause reached@}, %d clauses in state" (S.cardinal p_set.clauses);
f (Lazy.force c.rewrites) (C.elements c.map)) p_set.callback;
discount_loop ~merge
{ p_set with clauses = S.add c p_set.clauses; queue = u }
end else begin
let p_set = add_clause c p_set in
let p_set, t = S.fold (fun p (p_set, t) ->
let p_aux = rm_clause p p_set in
let p_set', p' = simplify p p_aux in
(p_set, t)
Util.debug ~section:p_set.section "@{<Red>Removing@}: %a" pp p;
(p_set', S.add p' t)
end) p_set.clauses (p_set, S.empty) in
let l = generate_new ~merge p_set c in
Util.debug ~section:p_set.section "@{<green>Generated %d (%d) inferences@}"
(List.length l) (S.cardinal t);
let t = List.fold_left (fun s p -> S.add p s) t l in
let p = S.fold enqueue t { p_set with queue = u } in
discount_loop ~merge p
end
end
let meta_to_var a b =
let mtys, mterms = Expr.Meta.merge_fm (Expr.Term.fm a) (Expr.Term.fm b) in
let m =
List.fold_left (fun acc m ->
Mapping.Meta.bind_term acc m (
Expr.Term.of_id @@ new_var (Mapping.apply_ty acc Expr.(m.meta_type)))
) (List.fold_left (fun acc m ->
Mapping.Meta.bind_ty acc m (Expr.Ty.of_id @@ new_ty_var ())
) Mapping.empty mtys) mterms in
Mapping.apply_term m a, Mapping.apply_term m b, m
let add_eq t ?f a b =
let a', b', m = meta_to_var a b in
let map = C.singleton m in
let fv = clause_fv a' b' map in
let c = mk_eq a' b' map (Hyp (f, fv)) in
enqueue c t
let add_neq t ?f a b =
let a', b', m = meta_to_var a b in
let map = C.singleton m in
let fv = clause_fv a' b' map in
let c = mk_neq a' b' map (Hyp (f, fv)) in
enqueue c t
let debug t =
Util.debug ~section:t.section "@{<White>Precedence@}: @[<hov>%a@]" pp_precedence t;
let l = List.sort (fun c c' -> Pervasives.compare c.id c'.id) @@ S.elements t.clauses in
List.iter (fun c -> Util.debug ~section:t.section " |%@ %a" pp c) l
let solve t =
debug t;
discount_loop ~merge:true t
|
21ab12cebf07526acad902680a8bcfd23a24779c35becc30f411cdb6c1902a5c | haskell/ThreadScope | BSort.hs | -------------------------------------------------------------------------------
- $ I d : BSort.hs#1 2009/03/06 10:53:15 REDMOND\\satnams $
-------------------------------------------------------------------------------
module Main
where
import System.Mem
import System.Random
import System.Time
-------------------------------------------------------------------------------
infixr 5 >->
-------------------------------------------------------------------------------
(>->) :: (a-> b) -> (b-> c) -> (a-> c)
(>->) circuit1 circuit2 input1
= circuit2 (circuit1 input1)
-------------------------------------------------------------------------------
halve :: [a] -> ([a], [a])
halve l
= (take n l, drop n l)
where
n = length l `div` 2
-------------------------------------------------------------------------------
unhalve :: ([a], [a]) -> [a]
unhalve (a, b) = a ++ b
-------------------------------------------------------------------------------
pair :: [a] -> [[a]]
pair [] = []
pair lst | odd (length lst)
= error ("pair given odd length list of size " ++ show (length lst))
pair (a:b:cs)
= [a,b]:rest
where
rest = pair cs
-------------------------------------------------------------------------------
unpair :: [[a]] -> [a]
unpair list = concat list
-------------------------------------------------------------------------------
par2 :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
par2 circuit1 circuit2 (input1, input2)
= (output1, output2)
where
output1 = circuit1 input1
output2 = circuit2 input2
-------------------------------------------------------------------------------
halveList :: [a] -> [[a]]
halveList l
= [take n l, drop n l]
where
n = length l `div` 2
-------------------------------------------------------------------------------
unhalveList :: [[a]] -> [a]
unhalveList [a, b] = a ++ b
-------------------------------------------------------------------------------
chop :: Int -> [a] -> [[a]]
chop n [] = []
chop n l
= (take n l) : chop n (drop n l)
-------------------------------------------------------------------------------
zipList :: [[a]] -> [[a]]
zipList [[], _] = []
zipList [_, []] = []
zipList [a:as, b:bs]
= [a,b] : zipList [as, bs]
-------------------------------------------------------------------------------
unzipList :: [[a]] -> [[a]]
unzipList list = [map fstListPair list, map sndListPair list]
-------------------------------------------------------------------------------
fsT :: (a -> b) -> (a, c) -> (b, c)
fsT f (a, b)
= (f a, b)
-------------------------------------------------------------------------------
snD :: (b -> c) -> (a, b) -> (a, c)
snD f (a, b)
= (a, f b)
-------------------------------------------------------------------------------
sndList :: ([a] -> [a]) -> [a] -> [a]
sndList f = halve >-> snD f >-> unhalve
-------------------------------------------------------------------------------
fstListPair :: [a] -> a
fstListPair [a, _] = a
-------------------------------------------------------------------------------
sndListPair :: [a] -> a
sndListPair [_, b] = b
-------------------------------------------------------------------------------
two :: ([a] -> [b]) -> [a] -> [b]
two r = halve >-> par2 r r >-> unhalve
-------------------------------------------------------------------------------
-- Many twos.
twoN :: Int -> ([a] -> [b]) -> [a] -> [b]
twoN 0 r = r
twoN n r = two (twoN (n-1) r)
-------------------------------------------------------------------------------
riffle :: [a] -> [a]
riffle = halveList >-> zipList >-> unpair
-------------------------------------------------------------------------------
unriffle :: [a] -> [a]
unriffle = pair >-> unzipList >-> unhalveList
-------------------------------------------------------------------------------
ilv :: ([a] -> [b]) -> [a] -> [b]
ilv r = unriffle >-> two r >-> riffle
-------------------------------------------------------------------------------
ilvN :: Int -> ([a] -> [b]) -> [a] -> [b]
ilvN 0 r = r
ilvN n r = ilv (ilvN (n-1) r)
-------------------------------------------------------------------------------
evens :: ([a] -> [b]) -> [a] -> [b]
evens f = chop 2 >-> map f >-> concat
-------------------------------------------------------------------------------
type ButterflyElement a = [a] -> [a]
type Butterfly a = [a] -> [a]
-------------------------------------------------------------------------------
butterfly :: ButterflyElement a -> Butterfly a
butterfly circuit [x,y] = circuit [x,y]
butterfly circuit input
= (ilv (butterfly circuit) >-> evens circuit) input
-------------------------------------------------------------------------------
sortB cmp [x, y] = cmp [x, y]
sortB cmp input
= (two (sortB cmp) >-> sndList reverse >-> butterfly cmp) input
-------------------------------------------------------------------------------
twoSorter :: [Int] -> [Int]
twoSorter [a, b]
= if a <= b then
[a, b]
else
[b, a]
-------------------------------------------------------------------------------
bsort :: [Int] -> [Int]
bsort = sortB twoSorter
-------------------------------------------------------------------------------
main :: IO ()
main
= do nums <- sequence (replicate (2^14) (getStdRandom (randomR (1,255))))
tStart <- getClockTime
performGC
let r = bsort nums
seq r (return ())
tEnd <- getClockTime
putStrLn (show (sum r))
putStrLn ("Time: " ++ show (secDiff tStart tEnd) ++ " seconds.")
-------------------------------------------------------------------------------
secDiff :: ClockTime -> ClockTime -> Float
secDiff (TOD secs1 psecs1) (TOD secs2 psecs2)
= fromInteger (psecs2 - psecs1) / 1e12 + fromInteger (secs2 - secs1)
-------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/haskell/ThreadScope/7269ccbf7810f268f8cbc3f0e60d49cc6168b882/papers/haskell_symposium_2009/bsort/BSort.hs | haskell | -----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Many twos.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| - $ I d : BSort.hs#1 2009/03/06 10:53:15 REDMOND\\satnams $
module Main
where
import System.Mem
import System.Random
import System.Time
infixr 5 >->
(>->) :: (a-> b) -> (b-> c) -> (a-> c)
(>->) circuit1 circuit2 input1
= circuit2 (circuit1 input1)
halve :: [a] -> ([a], [a])
halve l
= (take n l, drop n l)
where
n = length l `div` 2
unhalve :: ([a], [a]) -> [a]
unhalve (a, b) = a ++ b
pair :: [a] -> [[a]]
pair [] = []
pair lst | odd (length lst)
= error ("pair given odd length list of size " ++ show (length lst))
pair (a:b:cs)
= [a,b]:rest
where
rest = pair cs
unpair :: [[a]] -> [a]
unpair list = concat list
par2 :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
par2 circuit1 circuit2 (input1, input2)
= (output1, output2)
where
output1 = circuit1 input1
output2 = circuit2 input2
halveList :: [a] -> [[a]]
halveList l
= [take n l, drop n l]
where
n = length l `div` 2
unhalveList :: [[a]] -> [a]
unhalveList [a, b] = a ++ b
chop :: Int -> [a] -> [[a]]
chop n [] = []
chop n l
= (take n l) : chop n (drop n l)
zipList :: [[a]] -> [[a]]
zipList [[], _] = []
zipList [_, []] = []
zipList [a:as, b:bs]
= [a,b] : zipList [as, bs]
unzipList :: [[a]] -> [[a]]
unzipList list = [map fstListPair list, map sndListPair list]
fsT :: (a -> b) -> (a, c) -> (b, c)
fsT f (a, b)
= (f a, b)
snD :: (b -> c) -> (a, b) -> (a, c)
snD f (a, b)
= (a, f b)
sndList :: ([a] -> [a]) -> [a] -> [a]
sndList f = halve >-> snD f >-> unhalve
fstListPair :: [a] -> a
fstListPair [a, _] = a
sndListPair :: [a] -> a
sndListPair [_, b] = b
two :: ([a] -> [b]) -> [a] -> [b]
two r = halve >-> par2 r r >-> unhalve
twoN :: Int -> ([a] -> [b]) -> [a] -> [b]
twoN 0 r = r
twoN n r = two (twoN (n-1) r)
riffle :: [a] -> [a]
riffle = halveList >-> zipList >-> unpair
unriffle :: [a] -> [a]
unriffle = pair >-> unzipList >-> unhalveList
ilv :: ([a] -> [b]) -> [a] -> [b]
ilv r = unriffle >-> two r >-> riffle
ilvN :: Int -> ([a] -> [b]) -> [a] -> [b]
ilvN 0 r = r
ilvN n r = ilv (ilvN (n-1) r)
evens :: ([a] -> [b]) -> [a] -> [b]
evens f = chop 2 >-> map f >-> concat
type ButterflyElement a = [a] -> [a]
type Butterfly a = [a] -> [a]
butterfly :: ButterflyElement a -> Butterfly a
butterfly circuit [x,y] = circuit [x,y]
butterfly circuit input
= (ilv (butterfly circuit) >-> evens circuit) input
sortB cmp [x, y] = cmp [x, y]
sortB cmp input
= (two (sortB cmp) >-> sndList reverse >-> butterfly cmp) input
twoSorter :: [Int] -> [Int]
twoSorter [a, b]
= if a <= b then
[a, b]
else
[b, a]
bsort :: [Int] -> [Int]
bsort = sortB twoSorter
main :: IO ()
main
= do nums <- sequence (replicate (2^14) (getStdRandom (randomR (1,255))))
tStart <- getClockTime
performGC
let r = bsort nums
seq r (return ())
tEnd <- getClockTime
putStrLn (show (sum r))
putStrLn ("Time: " ++ show (secDiff tStart tEnd) ++ " seconds.")
secDiff :: ClockTime -> ClockTime -> Float
secDiff (TOD secs1 psecs1) (TOD secs2 psecs2)
= fromInteger (psecs2 - psecs1) / 1e12 + fromInteger (secs2 - secs1)
|
e274ecbe336ec01740a6a353f91ad8202883f5336bb74063d900ae264e7f27b0 | nebogeo/weavingcodes | scene.scm | Planet Fluxus Copyright ( C ) 2013
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU Affero General Public License for more details.
;;
You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see </>.
(define scene-node
(lambda (id prim state children)
(list id prim state children)))
(define scene-node-id (lambda (n) (list-ref n 0)))
(define scene-node-prim (lambda (n) (list-ref n 1)))
(define scene-node-state (lambda (n) (list-ref n 2)))
(define scene-node-children (lambda (n) (list-ref n 3)))
(define scene-node-modify-children (lambda (n v) (list-replace n 3 v)))
(define scene-node-add-child
(lambda (n c)
(scene-node-modify-children
n (cons c (scene-node-children n)))))
(define scene-node-remove-child
(lambda (n id)
(scene-node-modify-children
n (filter
(lambda (c)
(not (eq? (scene-node-id c) id)))
(scene-node-children n)))))
| null | https://raw.githubusercontent.com/nebogeo/weavingcodes/e305a28a38ef745ca31de3074c8aec3953a72aa2/dyadic/scm/scene.scm | scheme |
This program is free software: you can redistribute it and/or modify
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
along with this program. If not, see </>. | Planet Fluxus Copyright ( C ) 2013
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
You should have received a copy of the GNU Affero General Public License
(define scene-node
(lambda (id prim state children)
(list id prim state children)))
(define scene-node-id (lambda (n) (list-ref n 0)))
(define scene-node-prim (lambda (n) (list-ref n 1)))
(define scene-node-state (lambda (n) (list-ref n 2)))
(define scene-node-children (lambda (n) (list-ref n 3)))
(define scene-node-modify-children (lambda (n v) (list-replace n 3 v)))
(define scene-node-add-child
(lambda (n c)
(scene-node-modify-children
n (cons c (scene-node-children n)))))
(define scene-node-remove-child
(lambda (n id)
(scene-node-modify-children
n (filter
(lambda (c)
(not (eq? (scene-node-id c) id)))
(scene-node-children n)))))
|
076363a4e9f6c5d61210b21e87c616e73eda48712814ff8384eb52ddaf2573c7 | haskell-mafia/boris | Log.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
module Boris.Client.Log (
source
, source'
) where
import Boris.Core.Data
import Data.Conduit (Source, (=$=))
import qualified Data.Conduit.List as CL
import qualified Data.Text as T
import Jebediah.Data (Following (..), Query (..), LogGroup (..), LogStream (..), Log (..))
import qualified Jebediah.Conduit as J
import Mismi.Amazonka (Env)
import P
import System.IO (IO)
import Twine.Snooze (seconds)
source :: Env -> Environment -> BuildId -> Source IO Text
source env e i =
let
gname = LogGroup . T.intercalate "." $ ["boris", renderEnvironment e]
sname = LogStream $ renderBuildId i
in
source' env gname sname
source' :: Env -> LogGroup -> LogStream -> Source IO Text
source' env gname sname =
J.source env gname sname Everything (Follow . seconds $ 1)
=$= J.unclean
=$= CL.map logChunk
| null | https://raw.githubusercontent.com/haskell-mafia/boris/fb670071600e8b2d8dbb9191fcf6bf8488f83f5a/boris-client/src/Boris/Client/Log.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
module Boris.Client.Log (
source
, source'
) where
import Boris.Core.Data
import Data.Conduit (Source, (=$=))
import qualified Data.Conduit.List as CL
import qualified Data.Text as T
import Jebediah.Data (Following (..), Query (..), LogGroup (..), LogStream (..), Log (..))
import qualified Jebediah.Conduit as J
import Mismi.Amazonka (Env)
import P
import System.IO (IO)
import Twine.Snooze (seconds)
source :: Env -> Environment -> BuildId -> Source IO Text
source env e i =
let
gname = LogGroup . T.intercalate "." $ ["boris", renderEnvironment e]
sname = LogStream $ renderBuildId i
in
source' env gname sname
source' :: Env -> LogGroup -> LogStream -> Source IO Text
source' env gname sname =
J.source env gname sname Everything (Follow . seconds $ 1)
=$= J.unclean
=$= CL.map logChunk
|
66cead68fc95439f1f8e6d255db5f4c6634b84d2dbac504763d8aa7597eef3e3 | mokus0/junkbox | SimpleActor.hs | {-# LANGUAGE RankNTypes, ExistentialQuantification, RecordWildCards #-}
module TypeExperiments.SimpleActor where
import Control.Concurrent
import Control.Monad.LoopWhile
import Control.Monad.Trans
import Data.IORef
import TypeExperiments.MsgChan
data Actor f m = forall st. Actor
{ name :: !String
, initialize :: m st
, receive :: forall a. f a -> st -> m (a, st)
}
actor :: Monad m => Actor f m
actor = Actor
{ name = error "actor: no name specified"
, initialize = return ()
, receive = error "actor: no receive operation"
}
newtype OrDone f a where
Msg :: f a -> OrDone f a
Done :: OrDone f ()
runActor Actor{..} = do
state <- initialize
state <- newIORef state
msgQueue <- newChan
forkIO $ loop $ do
msg <- lift (readChan msgQueue)
case msg of
Done -> while False
Just (Rq req respVar) -> lift $ do
st <- readIORef state
(resp, st) <- receive req st
writeIORef state st
putMVar respVar resp
return msgQueue
| null | https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/TypeExperiments/SimpleActor.hs | haskell | # LANGUAGE RankNTypes, ExistentialQuantification, RecordWildCards # | module TypeExperiments.SimpleActor where
import Control.Concurrent
import Control.Monad.LoopWhile
import Control.Monad.Trans
import Data.IORef
import TypeExperiments.MsgChan
data Actor f m = forall st. Actor
{ name :: !String
, initialize :: m st
, receive :: forall a. f a -> st -> m (a, st)
}
actor :: Monad m => Actor f m
actor = Actor
{ name = error "actor: no name specified"
, initialize = return ()
, receive = error "actor: no receive operation"
}
newtype OrDone f a where
Msg :: f a -> OrDone f a
Done :: OrDone f ()
runActor Actor{..} = do
state <- initialize
state <- newIORef state
msgQueue <- newChan
forkIO $ loop $ do
msg <- lift (readChan msgQueue)
case msg of
Done -> while False
Just (Rq req respVar) -> lift $ do
st <- readIORef state
(resp, st) <- receive req st
writeIORef state st
putMVar respVar resp
return msgQueue
|
8a691a26bfa6f864feb4a363b93e79e5ed2950aee5aee1b8df329b619e861c61 | returntocorp/semgrep | Hooks.ml |
*
* Copyright ( C ) 2020 r2c
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* LICENSE for more details .
*
* Copyright (C) 2020 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* LICENSE for more details.
*)
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*****************************************************************************)
(* Hooks *)
(*****************************************************************************)
let exit = ref []
let get_type = ref (fun _id -> None)
let get_def = ref (fun _id -> None)
| null | https://raw.githubusercontent.com/returntocorp/semgrep/9a9f7dd6c09327a3e5d8bb9d941abe82a632d63b/src/core/Hooks.ml | ocaml | ***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Hooks
*************************************************************************** |
*
* Copyright ( C ) 2020 r2c
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* LICENSE for more details .
*
* Copyright (C) 2020 r2c
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* LICENSE for more details.
*)
let exit = ref []
let get_type = ref (fun _id -> None)
let get_def = ref (fun _id -> None)
|
6d5d38e1d79c206e35af4c98c79b26b953f40c79f6d309e6fec5926dd2282843 | thma/lambda-ski | GraphReductionSpec.hs | module GraphReductionSpec where
import Parser
import LambdaToSKI
import GraphReduction
import Data.Maybe (fromJust)
import Test.QuickCheck
import Test.Hspec
import Control.Monad.ST (runST, ST)
import Data.STRef
import TestSources
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "Classic GraphReduction with STRef" $ do
it "computes factorial" $
verify factorial
it "computes fibonacci" $
verify fibonacci
it "computes gaussian sum" $
verify gaussian
it "computes ackermann function" $
verify ackermann
it "computes tak " $
verify tak
verify :: SourceCode -> IO ()
verify source = do
let (expected, actual) = runTest source
actual `shouldBe` expected
type SourceCode = String
loadTestCase :: String -> IO SourceCode
loadTestCase name = readFile $ "test/" ++ name ++ ".ths"
getInt :: Expr -> Integer
getInt (Int i) = i
getInt _ = error "not an int"
runTest :: SourceCode -> (String, String)
runTest src =
let pEnv = parseEnvironment src
expr = compile pEnv abstractToSKI
graph = allocate expr
expected = show $ getInt $ fromJust (lookup "expected" pEnv)
result = reduceGraph graph
actual = runST $ printGraph result
in (show expected, show actual)
reduceGraph :: ST s (STRef s (Graph s)) -> ST s (STRef s (Graph s))
reduceGraph graph = do
gP <- graph
normalForm gP
printGraph :: ST s (STRef s (Graph s)) -> ST s String
printGraph graph = do
gP <- graph
toString gP
| null | https://raw.githubusercontent.com/thma/lambda-ski/f5546b865a4fae81dec9d5a250f25d1166ba3546/test/GraphReductionSpec.hs | haskell | module GraphReductionSpec where
import Parser
import LambdaToSKI
import GraphReduction
import Data.Maybe (fromJust)
import Test.QuickCheck
import Test.Hspec
import Control.Monad.ST (runST, ST)
import Data.STRef
import TestSources
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "Classic GraphReduction with STRef" $ do
it "computes factorial" $
verify factorial
it "computes fibonacci" $
verify fibonacci
it "computes gaussian sum" $
verify gaussian
it "computes ackermann function" $
verify ackermann
it "computes tak " $
verify tak
verify :: SourceCode -> IO ()
verify source = do
let (expected, actual) = runTest source
actual `shouldBe` expected
type SourceCode = String
loadTestCase :: String -> IO SourceCode
loadTestCase name = readFile $ "test/" ++ name ++ ".ths"
getInt :: Expr -> Integer
getInt (Int i) = i
getInt _ = error "not an int"
runTest :: SourceCode -> (String, String)
runTest src =
let pEnv = parseEnvironment src
expr = compile pEnv abstractToSKI
graph = allocate expr
expected = show $ getInt $ fromJust (lookup "expected" pEnv)
result = reduceGraph graph
actual = runST $ printGraph result
in (show expected, show actual)
reduceGraph :: ST s (STRef s (Graph s)) -> ST s (STRef s (Graph s))
reduceGraph graph = do
gP <- graph
normalForm gP
printGraph :: ST s (STRef s (Graph s)) -> ST s String
printGraph graph = do
gP <- graph
toString gP
|
|
c6af9ec10728ffb6e4fb1a3324bcd426fdbaeea98117fc37ec3546cac60314ac | FPBench/FPBench | core2fptaylor.rkt | #lang racket
(require "fpcore-reader.rkt" "fpcore-extra.rkt" "imperative.rkt" "range-analysis.rkt")
(provide core->fptaylor fptaylor-supported *fptaylor-inexact-scale*)
(define *fptaylor-inexact-scale* (make-parameter 1))
(define fptaylor-supported
(supported-list
(invert-op-proc
(curry set-member?
'(atan2 cbrt ceil copysign erf erfc exp2 expm1 fdim floor fmod hypot if
lgamma log10 log1p log2 nearbyint pow remainder round tgamma trunc while while*
array dim size ref for for* tensor tensor*)))
(invert-const-proc (curry set-member? '(NAN INFINITY)))
(curry set-member? '(binary16 binary32 binary64 binary128 real))
Note : nearestEven and nearestAway behave identically in
ieee754-rounding-modes
#f))
; Language-specific reserved names (avoid name collisions)
(define fptaylor-reserved
'(Variables variables Definitions definitions Expressions expressions Constraints constraints
IN in int real float16 float32 float64 float128
rnd no_rnd rnd16_ne rnd16 rnd16_0 rnd16_down rnd16_up
rnd32_ne rnd32 rnd32_0 rnd32_down rnd32_up
rnd64_ne rnd64 rnd64_0 rnd64_down rnd64_up
rnd128_ne rnd128 rnd128_0 rnd128_down rnd128_up
inv abs fma sqrt min max exp log cos sin tan cosh sinh tanh
acos asin atan atan2 arccos arcsin arctan acosh asinh atanh
arsinh arcosh artanh arcsinh arccosh arctanh argsinh argcosh argtanh
sub2 floor_power2 interval))
(define (inexact-operator? op)
(set-member? '(exp log sin cos tan asin acos atan
sinh cosh tanh asinh acosh atanh) op))
(define/match (prec->fptaylor prec)
[('undefined) ""]
[('real) "real"]
[('binary16) "float16"]
[('binary32) "float32"]
[('binary64) "float64"]
[('binary128) "float128"]
[(_) (error 'prec->fptaylor "Unsupported precision ~a" prec)])
(define/match (rm->fptaylor rm)
[('nearestEven) "ne"]
; The same as 'nearestEven
[('nearestAway) "ne"]
[('toPositive) "up"]
[('toNegative) "down"]
[('toZero) "zero"]
[(_) (error 'rm->fptaylor "Unsupported rounding mode ~a" rm)])
(define (round->fptaylor expr ctx #:scale [scale 1])
(define prec (ctx-lookup-prop ctx ':precision))
(define rm (rm->fptaylor (ctx-lookup-prop ctx ':round)))
(define bits
(match prec
['undefined "undefined"]
['real ""]
['binary16 "16"]
['binary32 "32"]
['binary64 "64"]
['binary128 "128"]
[_ (error 'round->fptaylor "Unsupported precision ~a" prec)]))
(cond
[(equal? bits "undefined") (format "rnd(~a)" (trim-infix-parens expr))]
[(equal? bits "") expr]
[(and (equal? rm "ne") (= scale 1)) (format "rnd~a(~a)" bits (trim-infix-parens expr))]
[else (format "rnd[~a,~a,~a](~a)" bits rm scale (trim-infix-parens expr))]))
(define (operator->fptaylor op args ctx)
(match (cons op args)
[(list 'fabs a) (round->fptaylor (format "abs(~a)" a) ctx)]
[(list 'fmax a b) (round->fptaylor (format "max(~a, ~a)" a b) ctx)]
[(list 'fmin a b) (round->fptaylor (format "min(~a, ~a)" a b) ctx)]
[(list 'fma a b c) (round->fptaylor (format "((~a * ~a) + ~a)" a b c) ctx)]
[(list (? inexact-operator? f) args ...)
(round->fptaylor (format "~a(~a)" f (string-join args ", ")) ctx #:scale (*fptaylor-inexact-scale*))]
[(list (? operator? f) args ...)
(round->fptaylor (format "~a(~a)" f (string-join args ", ")) ctx)]))
(define constant->expr
(match-lambda
['E "exp(1)"]
['LN2 "log(2)"]
['LN10 "log(10)"]
['PI "4 * atan(1)"]
['PI_2 "2 * atan(1)"]
['PI_4 "atan(1)"]
['M_1_PI "1 / (4 * atan(1))"]
['M_2_PI "1 / (2 * atan(1))"]
['M_2_SQRTPI "1 / sqrt(atan(1))"]
['SQRT2 "sqrt(2)"]
['SQRT1_2 "1 / sqrt(2)"]
[(? hex? expr) (format "~a" expr)]
[(? number? expr) (format-number expr)]
[c (error 'constant->expr "Unsupported constant ~a" c)]))
(define (constant->fptaylor expr ctx)
(define cexpr (constant->expr expr))
(round->fptaylor cexpr ctx))
(define (program->fptaylor name args arg-ctxs body return ctx vars)
(define expr-name
(let ([name* (ctx-lookup-prop ctx ':name #f)])
(if name* (let-values ([(_ name) (ctx-unique-name ctx name*)]) name) name)))
(define pre ((compose canonicalize remove-let)
(ctx-lookup-prop ctx ':pre 'TRUE)))
(define var-ranges
(make-immutable-hash
(dict-map (condition->range-table pre)
(lambda (var range) (cons (ctx-lookup-name ctx var) range)))))
(define arg-strings
(for/list ([arg args] [ctx arg-ctxs])
(define range (dict-ref var-ranges arg (make-interval -inf.0 +inf.0)))
(unless (nonempty-bounded? range)
(error 'fptaylor->function "Bad range for ~a in ~a (~a)" arg name range))
(unless (= (length range) 1)
(print range)
(error 'fptaylor->function "FPTaylor only accepts one sampling range"))
(match-define (interval l u l? u?) (car range))
(define prec (ctx-lookup-prop ctx ':precision))
(format "\t~a ~a in [~a, ~a];" (prec->fptaylor prec) arg
(format-number l) (format-number u))))
(define var-string
(if (null? arg-strings)
""
(format "Variables\n~a\n\n" (string-join arg-strings "\n"))))
(define def-string
(if (non-empty-string? body)
(format "Definitions\n~a\n" body)
""))
; TODO: constraints
(format "{\n~a~aExpressions\n\t~a = ~a;\n}"
var-string def-string expr-name return))
; Override visitor behavior
(define-expr-visitor imperative-visitor fptaylor-visitor
[(visit-! vtor props body #:ctx ctx)
(visit/ctx vtor body (ctx-update-props ctx props))])
; ignore 'declaration' and type' since they are never used
(define core->fptaylor
(make-imperative-compiler "fptaylor"
#:operator operator->fptaylor
#:constant constant->fptaylor
#:round round->fptaylor
#:program program->fptaylor
#:flags '(round-after-operation
never-declare)
#:reserved fptaylor-reserved
#:visitor fptaylor-visitor))
(define-compiler '("fptaylor" "fpt") (const "") core->fptaylor (const "") fptaylor-supported)
;;; Legacy command line
(module+ main
(require racket/cmdline)
(define files (make-parameter #f))
(define files-all (make-parameter #f))
(define auto-file-names (make-parameter #f))
(define out-path (make-parameter "."))
(define precision (make-parameter #f))
(define var-precision (make-parameter #f))
(define split-or (make-parameter #f))
(define subexprs (make-parameter #f))
(define split (make-parameter #f))
(define unroll (make-parameter #f))
(command-line
#:program "core2fptaylor.rkt"
#:once-each
["--files" "Save FPTaylor tasks corresponding to different FPBench expressions in separate files"
(files #t)]
["--files-all" "Save all FPTaylor tasks in separate files"
(files-all #t)]
["--auto-file-names" "Generate special names for all files"
(auto-file-names #t)]
["--out-path" path "All files are saved in the given path"
(out-path path)]
["--precision" prec "The precision of all operations (overrides the :precision property)"
(precision (string->symbol prec))]
["--var-precision" prec "The precision of input variables (overrides the :var-precision property)"
(var-precision (string->symbol prec))]
["--scale" scale "The scale factor for operations which are not correctly rounded"
(*fptaylor-inexact-scale* (string->number scale))]
["--split-or" "Convert preconditions to DNF and create separate FPTaylor tasks for all conjunctions"
(split-or #t)]
["--subexprs" "Create FPTaylor tasks for all subexpressions"
(subexprs #t)]
["--split" n "Split intervals of bounded variables into the given number of parts"
(split (string->number n))]
["--unroll" n "How many iterations to unroll any loops to"
(unroll (string->number n))]
#:args ([input-file #f])
((if input-file
(curry call-with-input-file input-file)
(λ (proc) (proc (current-input-port))))
(λ (port)
(port-count-lines! port)
(for ([prog (in-port (curry read-fpcore "input") port)] [n (in-naturals)])
;;; (with-handlers ([exn:fail? (λ (exn) (eprintf "[ERROR]: ~a\n\n" exn))])
(define def-name (format "ex~a" n))
(define prog-name (if (auto-file-names) def-name (fpcore-name prog def-name)))
(define override-props (if (precision) `(:precision ,(precision)) null))
(define progs (fpcore-transform prog
#:var-precision (var-precision)
#:override-props override-props
#:unroll (unroll)
#:split (split)
#:subexprs (subexprs)
#:split-or (split-or)))
(define results (map (curryr core->fptaylor def-name) progs))
(define multiple-results (> (length results) 1))
(cond
[(files-all)
(for ([r results] [k (in-naturals)])
(define fname (fix-file-name
(string-append prog-name
(if multiple-results (format "_case~a" k) "")
".txt")))
(call-with-output-file (build-path (out-path) fname) #:exists 'replace
(λ (p) (fprintf p "~a" r))))]
[(files)
(define fname (fix-file-name (format "~a.txt" prog-name)))
(call-with-output-file (build-path (out-path) fname) #:exists 'replace
(λ (p) (for ([r results])
(if multiple-results (fprintf p "~a\n" r) (fprintf p "~a" r)))))]
[else (for ([r results]) (printf "~a\n" r))])
)))
))
| null | https://raw.githubusercontent.com/FPBench/FPBench/ecdfbfc484cc7f392c46bfba43813458a6406608/src/core2fptaylor.rkt | racket | Language-specific reserved names (avoid name collisions)
The same as 'nearestEven
TODO: constraints
Override visitor behavior
ignore 'declaration' and type' since they are never used
Legacy command line
(with-handlers ([exn:fail? (λ (exn) (eprintf "[ERROR]: ~a\n\n" exn))]) | #lang racket
(require "fpcore-reader.rkt" "fpcore-extra.rkt" "imperative.rkt" "range-analysis.rkt")
(provide core->fptaylor fptaylor-supported *fptaylor-inexact-scale*)
(define *fptaylor-inexact-scale* (make-parameter 1))
(define fptaylor-supported
(supported-list
(invert-op-proc
(curry set-member?
'(atan2 cbrt ceil copysign erf erfc exp2 expm1 fdim floor fmod hypot if
lgamma log10 log1p log2 nearbyint pow remainder round tgamma trunc while while*
array dim size ref for for* tensor tensor*)))
(invert-const-proc (curry set-member? '(NAN INFINITY)))
(curry set-member? '(binary16 binary32 binary64 binary128 real))
Note : nearestEven and nearestAway behave identically in
ieee754-rounding-modes
#f))
(define fptaylor-reserved
'(Variables variables Definitions definitions Expressions expressions Constraints constraints
IN in int real float16 float32 float64 float128
rnd no_rnd rnd16_ne rnd16 rnd16_0 rnd16_down rnd16_up
rnd32_ne rnd32 rnd32_0 rnd32_down rnd32_up
rnd64_ne rnd64 rnd64_0 rnd64_down rnd64_up
rnd128_ne rnd128 rnd128_0 rnd128_down rnd128_up
inv abs fma sqrt min max exp log cos sin tan cosh sinh tanh
acos asin atan atan2 arccos arcsin arctan acosh asinh atanh
arsinh arcosh artanh arcsinh arccosh arctanh argsinh argcosh argtanh
sub2 floor_power2 interval))
(define (inexact-operator? op)
(set-member? '(exp log sin cos tan asin acos atan
sinh cosh tanh asinh acosh atanh) op))
(define/match (prec->fptaylor prec)
[('undefined) ""]
[('real) "real"]
[('binary16) "float16"]
[('binary32) "float32"]
[('binary64) "float64"]
[('binary128) "float128"]
[(_) (error 'prec->fptaylor "Unsupported precision ~a" prec)])
(define/match (rm->fptaylor rm)
[('nearestEven) "ne"]
[('nearestAway) "ne"]
[('toPositive) "up"]
[('toNegative) "down"]
[('toZero) "zero"]
[(_) (error 'rm->fptaylor "Unsupported rounding mode ~a" rm)])
(define (round->fptaylor expr ctx #:scale [scale 1])
(define prec (ctx-lookup-prop ctx ':precision))
(define rm (rm->fptaylor (ctx-lookup-prop ctx ':round)))
(define bits
(match prec
['undefined "undefined"]
['real ""]
['binary16 "16"]
['binary32 "32"]
['binary64 "64"]
['binary128 "128"]
[_ (error 'round->fptaylor "Unsupported precision ~a" prec)]))
(cond
[(equal? bits "undefined") (format "rnd(~a)" (trim-infix-parens expr))]
[(equal? bits "") expr]
[(and (equal? rm "ne") (= scale 1)) (format "rnd~a(~a)" bits (trim-infix-parens expr))]
[else (format "rnd[~a,~a,~a](~a)" bits rm scale (trim-infix-parens expr))]))
(define (operator->fptaylor op args ctx)
(match (cons op args)
[(list 'fabs a) (round->fptaylor (format "abs(~a)" a) ctx)]
[(list 'fmax a b) (round->fptaylor (format "max(~a, ~a)" a b) ctx)]
[(list 'fmin a b) (round->fptaylor (format "min(~a, ~a)" a b) ctx)]
[(list 'fma a b c) (round->fptaylor (format "((~a * ~a) + ~a)" a b c) ctx)]
[(list (? inexact-operator? f) args ...)
(round->fptaylor (format "~a(~a)" f (string-join args ", ")) ctx #:scale (*fptaylor-inexact-scale*))]
[(list (? operator? f) args ...)
(round->fptaylor (format "~a(~a)" f (string-join args ", ")) ctx)]))
(define constant->expr
(match-lambda
['E "exp(1)"]
['LN2 "log(2)"]
['LN10 "log(10)"]
['PI "4 * atan(1)"]
['PI_2 "2 * atan(1)"]
['PI_4 "atan(1)"]
['M_1_PI "1 / (4 * atan(1))"]
['M_2_PI "1 / (2 * atan(1))"]
['M_2_SQRTPI "1 / sqrt(atan(1))"]
['SQRT2 "sqrt(2)"]
['SQRT1_2 "1 / sqrt(2)"]
[(? hex? expr) (format "~a" expr)]
[(? number? expr) (format-number expr)]
[c (error 'constant->expr "Unsupported constant ~a" c)]))
(define (constant->fptaylor expr ctx)
(define cexpr (constant->expr expr))
(round->fptaylor cexpr ctx))
(define (program->fptaylor name args arg-ctxs body return ctx vars)
(define expr-name
(let ([name* (ctx-lookup-prop ctx ':name #f)])
(if name* (let-values ([(_ name) (ctx-unique-name ctx name*)]) name) name)))
(define pre ((compose canonicalize remove-let)
(ctx-lookup-prop ctx ':pre 'TRUE)))
(define var-ranges
(make-immutable-hash
(dict-map (condition->range-table pre)
(lambda (var range) (cons (ctx-lookup-name ctx var) range)))))
(define arg-strings
(for/list ([arg args] [ctx arg-ctxs])
(define range (dict-ref var-ranges arg (make-interval -inf.0 +inf.0)))
(unless (nonempty-bounded? range)
(error 'fptaylor->function "Bad range for ~a in ~a (~a)" arg name range))
(unless (= (length range) 1)
(print range)
(error 'fptaylor->function "FPTaylor only accepts one sampling range"))
(match-define (interval l u l? u?) (car range))
(define prec (ctx-lookup-prop ctx ':precision))
(format "\t~a ~a in [~a, ~a];" (prec->fptaylor prec) arg
(format-number l) (format-number u))))
(define var-string
(if (null? arg-strings)
""
(format "Variables\n~a\n\n" (string-join arg-strings "\n"))))
(define def-string
(if (non-empty-string? body)
(format "Definitions\n~a\n" body)
""))
(format "{\n~a~aExpressions\n\t~a = ~a;\n}"
var-string def-string expr-name return))
(define-expr-visitor imperative-visitor fptaylor-visitor
[(visit-! vtor props body #:ctx ctx)
(visit/ctx vtor body (ctx-update-props ctx props))])
(define core->fptaylor
(make-imperative-compiler "fptaylor"
#:operator operator->fptaylor
#:constant constant->fptaylor
#:round round->fptaylor
#:program program->fptaylor
#:flags '(round-after-operation
never-declare)
#:reserved fptaylor-reserved
#:visitor fptaylor-visitor))
(define-compiler '("fptaylor" "fpt") (const "") core->fptaylor (const "") fptaylor-supported)
(module+ main
(require racket/cmdline)
(define files (make-parameter #f))
(define files-all (make-parameter #f))
(define auto-file-names (make-parameter #f))
(define out-path (make-parameter "."))
(define precision (make-parameter #f))
(define var-precision (make-parameter #f))
(define split-or (make-parameter #f))
(define subexprs (make-parameter #f))
(define split (make-parameter #f))
(define unroll (make-parameter #f))
(command-line
#:program "core2fptaylor.rkt"
#:once-each
["--files" "Save FPTaylor tasks corresponding to different FPBench expressions in separate files"
(files #t)]
["--files-all" "Save all FPTaylor tasks in separate files"
(files-all #t)]
["--auto-file-names" "Generate special names for all files"
(auto-file-names #t)]
["--out-path" path "All files are saved in the given path"
(out-path path)]
["--precision" prec "The precision of all operations (overrides the :precision property)"
(precision (string->symbol prec))]
["--var-precision" prec "The precision of input variables (overrides the :var-precision property)"
(var-precision (string->symbol prec))]
["--scale" scale "The scale factor for operations which are not correctly rounded"
(*fptaylor-inexact-scale* (string->number scale))]
["--split-or" "Convert preconditions to DNF and create separate FPTaylor tasks for all conjunctions"
(split-or #t)]
["--subexprs" "Create FPTaylor tasks for all subexpressions"
(subexprs #t)]
["--split" n "Split intervals of bounded variables into the given number of parts"
(split (string->number n))]
["--unroll" n "How many iterations to unroll any loops to"
(unroll (string->number n))]
#:args ([input-file #f])
((if input-file
(curry call-with-input-file input-file)
(λ (proc) (proc (current-input-port))))
(λ (port)
(port-count-lines! port)
(for ([prog (in-port (curry read-fpcore "input") port)] [n (in-naturals)])
(define def-name (format "ex~a" n))
(define prog-name (if (auto-file-names) def-name (fpcore-name prog def-name)))
(define override-props (if (precision) `(:precision ,(precision)) null))
(define progs (fpcore-transform prog
#:var-precision (var-precision)
#:override-props override-props
#:unroll (unroll)
#:split (split)
#:subexprs (subexprs)
#:split-or (split-or)))
(define results (map (curryr core->fptaylor def-name) progs))
(define multiple-results (> (length results) 1))
(cond
[(files-all)
(for ([r results] [k (in-naturals)])
(define fname (fix-file-name
(string-append prog-name
(if multiple-results (format "_case~a" k) "")
".txt")))
(call-with-output-file (build-path (out-path) fname) #:exists 'replace
(λ (p) (fprintf p "~a" r))))]
[(files)
(define fname (fix-file-name (format "~a.txt" prog-name)))
(call-with-output-file (build-path (out-path) fname) #:exists 'replace
(λ (p) (for ([r results])
(if multiple-results (fprintf p "~a\n" r) (fprintf p "~a" r)))))]
[else (for ([r results]) (printf "~a\n" r))])
)))
))
|
d258c99029e22a62922d3c93e344f560b2a3f7f6d95510a0709ef3ba8a906d4c | axelarge/advent-of-code | day23_test.clj | (ns advent-of-code.y2022.day23-test
(:require [clojure.test :refer :all]
[advent-of-code.y2022.day23 :refer :all]))
(def test-input "....#..\n..###.#\n#...#.#\n.#...##\n#.###..\n##.#.##\n.#..#..")
(deftest test-solve1
(is (= (solve1 test-input) 110))
(is (= (solve1 input) 3990)))
(deftest test-solve2
(is (= (solve2 test-input) 20))
(is (= (solve2 input) 1057)))
| null | https://raw.githubusercontent.com/axelarge/advent-of-code/077d414b2509891b068f1216c67390ad71312514/test/advent_of_code/y2022/day23_test.clj | clojure | (ns advent-of-code.y2022.day23-test
(:require [clojure.test :refer :all]
[advent-of-code.y2022.day23 :refer :all]))
(def test-input "....#..\n..###.#\n#...#.#\n.#...##\n#.###..\n##.#.##\n.#..#..")
(deftest test-solve1
(is (= (solve1 test-input) 110))
(is (= (solve1 input) 3990)))
(deftest test-solve2
(is (= (solve2 test-input) 20))
(is (= (solve2 input) 1057)))
|
|
0a55acf092fecb2647f1a814932b0c9a211b632cdd64ad1f240197aa5a755ef3 | jrm-code-project/LISP-Machine | qcfasd.lisp | -*- Mode : LISP ; Package : COMPILER ; Base:8 ; : ZL -*-
* * ( c ) Copyright 1980 Massachusetts Institute of Technology * *
(DEFVAR FASD-TABLE-CURRENT-INDEX NIL "Allocating index for runtime fasl table")
(DEFVAR FASD-HASH-TABLE NIL "FASD time hash table")
(DEFVAR FASD-EVAL-HASH-TABLE NIL "FASD time hash table for self ref pointers")
(DEFVAR FASD-TYO-BUFFER-ARRAY nil "FASD output buffer")
(DEFVAR FASD-STREAM)
(DEFVAR FASD-PACKAGE) ;The package in which the fasl file will presumably be loaded
;;; If this is the car of a list, the cdr is a form to be evaluated at load time
;;; The "#," reader macro uses this
(DEFVAR EVAL-AT-LOAD-TIME-MARKER (COPY-SYMBOL 'EVAL-AT-LOAD-TIME-MARKER NIL))
(PUTPROP EVAL-AT-LOAD-TIME-MARKER '(EXECUTION-CONTEXT-EVAL-WARNING) 'OPTIMIZERS)
(DEFUN EXECUTION-CONTEXT-EVAL-WARNING (FORM)
(WARN 'LOAD-TIME-EVAL :IMPOSSIBLE "Load-time eval (#,~S) not inside quoted structure"
(CDR FORM))
(EVAL (CDR FORM)))
If this uninterned symbol is seen as the car of a list , and the cadr of the
;;; list is a named-lambda, it will be compiled.
(DEFVAR FUNCTIONAL-CONSTANT-MARKER (COPY-SYMBOL 'FUNCTIONAL-CONSTANT-MARKER NIL))
;;; Make it the same as FUNCTION for when the interpreter or compiler sees it.
;;; Do NOT make it a displacing macro!
(FSET FUNCTIONAL-CONSTANT-MARKER
'(MACRO LAMBDA (X) (CONS 'FUNCTION (CDR X))))
;;; This is an a-list of special markers that may exist in the car of a cons
;;; and the function to fasdump such conses. A typical thing for such a
;;; a function to do is to call FASD-EVAL1 on some suitable form.
(DEFVAR FASD-MARKERS-ALIST
(LIST (CONS EVAL-AT-LOAD-TIME-MARKER 'FASD-EVAL-AT-LOAD-TIME)
(CONS FUNCTIONAL-CONSTANT-MARKER 'FASD-FUNCTIONAL-CONSTANT)))
;;; This is an a-list of area numbers and functions to fasdump conses in that
;;; area. The function is treated just as for fasd-markers.
(DEFVAR FASD-MAGIC-AREAS-ALIST NIL)
(DEFUN FASD-NIBBLE (NUMBER)
(WHEN (NULL (VECTOR-PUSH NUMBER FASD-TYO-BUFFER-ARRAY))
(FASD-CLEAR-NIBBLE-BUFFER)
(VECTOR-PUSH NUMBER FASD-TYO-BUFFER-ARRAY)))
(DEFUN FASD-CLEAR-NIBBLE-BUFFER ()
(SEND FASD-STREAM ':STRING-OUT FASD-TYO-BUFFER-ARRAY)
(SETF (FILL-POINTER FASD-TYO-BUFFER-ARRAY) 0))
;;;; Output the things that divide a fasl file into its major subparts
;;; Output sixbit /QFASL/ to start a fasl file.
;;; Also clears out the temp area
(DEFUN FASD-START-FILE ()
(FASD-NIBBLE #o143150)
(FASD-NIBBLE #o71660))
(DEFUN FASD-START-GROUP (FLAG LENGTH TYPE)
(LET* ((OUT-LEN (LSH (MIN LENGTH #o377)
(- FASL-GROUP-LENGTH-SHIFT))))
(FASD-NIBBLE (+ %FASL-GROUP-CHECK
(+ (IF FLAG %FASL-GROUP-FLAG 0)
(+ OUT-LEN
TYPE))))
(AND ( LENGTH #o377)
(FASD-NIBBLE LENGTH)))
NIL)
(DEFUN FASD-FUNCTION-HEADER (FCTN-NAME)
(FASD-START-GROUP NIL 0 FASL-OP-FUNCTION-HEADER)
(FASD-CONSTANT FCTN-NAME)
(FASD-CONSTANT 0)
NIL)
(DEFUN FASD-FUNCTION-END ()
(FASD-START-GROUP NIL 0 FASL-OP-FUNCTION-END)
NIL)
(DEFUN FASD-END-WHACK ()
(FASD-START-GROUP NIL 0 FASL-OP-END-OF-WHACK)
;; Reset fasd table, but not temporary areas
(CLRHASH FASD-HASH-TABLE)
(CLRHASH FASD-EVAL-HASH-TABLE)
(SETQ FASD-TABLE-CURRENT-INDEX FASL-TABLE-WORKING-OFFSET))
(DEFUN FASD-END-FILE ()
(FASD-START-GROUP NIL 0 FASL-OP-END-OF-FILE)
(FASD-CLEAR-NIBBLE-BUFFER)
NIL)
;;;; Given a sexp dump a group to cons up that sexp and return it
;;; This is the main function of FASD. It takes a Lisp object and
dumps it . The second ( optional ) arg is a FASL - OP to use
on any lists in the structure . It returns the IDX of the object .
(DEFUN FASD-CONSTANT (S-EXP &OPTIONAL (LIST-OP FASL-OP-LIST))
(BLOCK NIL
(AND FASD-NEW-SYMBOL-FUNCTION ;For FASD-SYMBOLS-PROPERTIES,
(SYMBOLP S-EXP) ;make sure we examine all symbols in
(FUNCALL FASD-NEW-SYMBOL-FUNCTION S-EXP)) ;the data that we dump.
(LET ((TEM (FASD-TABLE-LOOKUP S-EXP))) ;Check if this object already dumped
(WHEN TEM ;Yup.
(COND (( TEM (LSH 1 16.))
(FASD-START-GROUP NIL 2 FASL-OP-LARGE-INDEX)
(FASD-NIBBLE (LDB (byte 8. 16.) TEM))
(FASD-NIBBLE (LDB (byte 16. 0) TEM)))
(T
(FASD-START-GROUP NIL 1 FASL-OP-INDEX) ;Just reference it in the FASL TABLE.
(FASD-NIBBLE TEM)))
(RETURN TEM)))
(TYPECASE S-EXP
(INTEGER (FASD-FIXED S-EXP))
(CHARACTER (FASD-CHARACTER S-EXP))
(SHORT-FLOAT (FASD-SHORT-FLOAT S-EXP))
(SINGLE-FLOAT (FASD-SINGLE-FLOAT S-EXP))
(SYMBOL (FASD-SYMBOL S-EXP))
(STRING (RETURN (FASD-STRING S-EXP)))
(ARRAY (RETURN (FASD-ARRAY S-EXP)))
(COMPILED-FUNCTION (FASD-FEF S-EXP))
(CONS (RETURN (FASD-LIST S-EXP LIST-OP)))
(INSTANCE (FASD-EVAL-CONSTRUCT-CONSTANT
(OR (SEND S-EXP ':SEND-IF-HANDLES ':FASD-FORM)
(and (send s-exp :get-handler-for :reconstruction-init-plist)
`(APPLY 'MAKE-INSTANCE
'(,(TYPE-OF S-EXP)
. ,(SEND S-EXP ':RECONSTRUCTION-INIT-PLIST))))
(ferror "The instance ~S cannot be compiled.~
~&It is an instance of a type which does not provide a way to make a fast-load representation."
s-exp))))
(RATIO (RETURN (FASD-RATIONAL S-EXP)))
(COMPLEX (RETURN (FASD-COMPLEX S-EXP)))
(T (FERROR "The constant ~S cannot be compiled.~
~&The data-type ~S is not suitable for compiling as a fast-load constant (FASD-CONSTANT)."
S-EXP (TYPE-OF S-EXP))))
(FASD-TABLE-ADD S-EXP)))
(DEFUN FASD-LIST (S-EXP LIST-OP)
;; Determine the size of the list, and check for special markers
(DO ((L S-EXP (CDR L))
(N-CONSES 0 (1+ N-CONSES))
(MARK) (DOTTED))
((OR (ATOM L)
(SETQ MARK (ASSQ (CAR L) FASD-MARKERS-ALIST))
(AND FASD-MAGIC-AREAS-ALIST
(SETQ MARK (ASSQ (%AREA-NUMBER L) FASD-MAGIC-AREAS-ALIST))))
;; Now dump that many conses and the tail if non-null
(COND ((ZEROP N-CONSES) (FUNCALL (CDR MARK) S-EXP))
(T (SETQ DOTTED (NOT (NULL L)))
(FASD-START-GROUP DOTTED 1 LIST-OP)
(FASD-NIBBLE (IF DOTTED (1+ N-CONSES) N-CONSES))
(DO ((L1 S-EXP (CDR L1)))
((EQ L1 L))
(FASD-CONSTANT (CAR L1) LIST-OP))
(COND ((NOT DOTTED))
((NOT MARK) (FASD-CONSTANT L))
(T (FUNCALL (CDR MARK) L)))
;; FASL-OP-LIST-COMPONENT speeds things up by not bloating the fasl
;; table with conses out of the middle of lists.
(IF (= LIST-OP FASL-OP-LIST-COMPONENT)
FASL-EVALED-VALUE
(FASD-TABLE-ADD S-EXP)))))))
(DEFUN FASD-EVAL-AT-LOAD-TIME (CONS)
(LET ((FORM (CDR CONS)))
(IF (AND (CONSP FORM)
(EQ (CAR FORM) 'SI::FLAVOR-VAR-SELF-REF-INDEX))
(FASD-EVAL-MEMOIZED FORM T)
(FASD-EVAL1 FORM))))
(DEFUN FASD-FUNCTIONAL-CONSTANT (CONS)
(COND ((AND (CONSP (CADR CONS))
(FUNCTIONP (CADR CONS) T))
(IF (VARIABLE-BOUNDP COMPILER-QUEUE)
(FERROR "Compiler is not recursive -- you will lose somehow"))
(QC-TRANSLATE-FUNCTION (IF (ATOM (CADADR CONS))
(CADADR CONS)
(CAR (CADADR CONS)))
(CADR CONS)
'MACRO-COMPILE
'QFASL-NO-FDEFINE))
(T (FASD-CONSTANT (CONS 'FUNCTION (CDR CONS))))))
(DEFUN FASD-SYMBOL (SYM &AUX (STARTED-FLAG NIL))
(MULTIPLE-VALUE-BIND (PKG-OR-STRING SHARP-FLAG)
(SI:PKG-PRINTING-PREFIX SYM FASD-PACKAGE)
(WHEN PKG-OR-STRING
;; Here if need a prefix of any kind.
(SETQ STARTED-FLAG T)
(FASD-START-GROUP SHARP-FLAG 1 FASL-OP-PACKAGE-SYMBOL)
This nibble is if should ignore local nicknames , else 2 .
(FASD-NIBBLE
(IF (AND (NOT (STRINGP PKG-OR-STRING))
(SI:ASSOC-EQUAL (PACKAGE-PREFIX-PRINT-NAME PKG-OR-STRING)
(DONT-OPTIMIZE (SI:PKG-REFNAME-ALIST PACKAGE))))
#o0402
#o0002))
(FASD-CONSTANT (IF (STRINGP PKG-OR-STRING)
PKG-OR-STRING
(PACKAGE-PREFIX-PRINT-NAME PKG-OR-STRING))))
(IF STARTED-FLAG
(FASD-CONSTANT (SYMBOL-NAME SYM)) ;If there was a prefix
If uninterned or no prefix needed
SYM
FASL-OP-SYMBOL
;;>> this should really be sharp-flag, except that I don't want to (possibly)
> > break things just at this moment
NIL))))
;;; This is expected to do the FASD-TABLE-ADD itself,
;;; since FASD-ARRAY has to do so.
(DEFUN FASD-STRING (STRING)
(IF (OR (ARRAY-HAS-LEADER-P STRING)
(> (ARRAY-LENGTH STRING) (LSH 1 16.)))
(FASD-ARRAY STRING)
(FASD-WRITE-STRING STRING FASL-OP-STRING NIL)
(FASD-TABLE-ADD STRING)))
(DEFUN FASD-WRITE-STRING (OBJECT GROUP-TYPE FLAG)
(LET* ((STRING (STRING OBJECT))
(LENGTH (LENGTH STRING)))
(FASD-START-GROUP FLAG (CEILING LENGTH 2) GROUP-TYPE)
(DO ((I 0 (+ I 2))
C0 C1)
(( I LENGTH))
(SETQ C0 (CHAR-INT (CHAR STRING I))
C1 (IF (= (1+ I) LENGTH)
#o200
(CHAR-INT (CHAR STRING (1+ I)))))
(FASD-NIBBLE (+ (LSH C1 8.) C0)))))
(DEFUN FASD-FIXED (N)
(LET* ((ABS (ABS N))
(LENGTH (CEILING (HAULONG ABS) 16.)))
(FASD-START-GROUP (< N 0) LENGTH FASL-OP-FIXED)
(DO ((POS (* 16. (1- LENGTH)) (- POS 16.))
(C LENGTH (1- C)))
((ZEROP C))
(FASD-NIBBLE (LDB (+ (LSH POS 6) 16.) ABS)))))
(DEFUN FASD-CHARACTER (N)
(LET* ((ABS (ABS N))
(LENGTH (CEILING (HAULONG ABS) 16.)))
(FASD-START-GROUP (< N 0) LENGTH FASL-OP-CHARACTER)
(DO ((POS (* 16. (1- LENGTH)) (- POS 16.))
(C LENGTH (1- C)))
((ZEROP C))
(FASD-NIBBLE (LDB (+ (LSH POS 6) 16.) ABS)))))
(DEFUN FASD-SINGLE-FLOAT (N)
(FASD-START-GROUP NIL 3 FASL-OP-FLOAT)
(FASD-NIBBLE (%P-LDB-OFFSET #o1013 N 0))
(FASD-NIBBLE (DPB (%P-LDB-OFFSET #o0010 N 0) #o1010 (%P-LDB-OFFSET #o2010 N 1)))
(FASD-NIBBLE (%P-LDB-OFFSET #o0020 N 1))
NIL)
Can be replaced with % SHORT - FLOAT - EXPONENT once in system 99 .
;(defsubst %QCFASD-short-float-exponent (short-float)
( ldb ( byte 8 17 . ) ( % pointer short - float ) ) )
(DEFUN FASD-SHORT-FLOAT (N)
(LET ((EXP (- (SI:%SHORT-FLOAT-EXPONENT N) #o200)))
;; If exponent is in range for FASL-OP-FLOAT, use it.
(IF (OR ( #o-100 EXP #o77)
(ZEROP N)) ;exp is #o-200 in this case.
(FASD-OLD-SMALL-FLOAT N)
(FASD-NEW-SMALL-FLOAT N))))
(DEFUN FASD-OLD-SMALL-FLOAT (N)
(SETQ N (%MAKE-POINTER DTP-FIX N)) ;So that LDB's will work.
Convert excess # o200 exponent to excess # o100
(SETQ N (%POINTER-DIFFERENCE N #o40000000)))
(FASD-START-GROUP T 2 FASL-OP-FLOAT)
(FASD-NIBBLE (LDB #o2010 N))
(FASD-NIBBLE (LDB #o0020 N))
NIL)
(DEFUN FASD-NEW-SMALL-FLOAT (N &AUX FRACTION EXPONENT)
(FASD-START-GROUP (MINUSP N) 5 FASL-OP-NEW-FLOAT)
(SETQ FRACTION (SI::%SHORT-FLOAT-MANTISSA N)
EXPONENT (SI::%SHORT-FLOAT-EXPONENT N))
8 bits for exponent , including sign
(FASD-NIBBLE EXPONENT)
17 bits for mantissa , excluding sign
(FASD-NIBBLE (LDB (BYTE 16. 0) FRACTION)) ;exclude sign
(FASD-NIBBLE 1)) ;implied leading digit
(DEFUN FASD-RATIONAL (RAT)
(FASD-START-GROUP NIL 0 FASL-OP-RATIONAL)
(FASD-CONSTANT (NUMERATOR RAT))
(FASD-CONSTANT (DENOMINATOR RAT))
(FASD-TABLE-ADD RAT))
(DEFUN FASD-COMPLEX (COMPLEX)
(FASD-START-GROUP NIL 0 FASL-OP-COMPLEX)
(FASD-CONSTANT (REALPART COMPLEX))
(FASD-CONSTANT (IMAGPART COMPLEX))
(FASD-TABLE-ADD COMPLEX))
(DEFUN FASD-FEF (FEF)
(LET* ((Q-COUNT (%STRUCTURE-BOXED-SIZE FEF))
(NON-Q-COUNT (- (%STRUCTURE-TOTAL-SIZE FEF) Q-COUNT)))
(FASD-START-GROUP NIL 3 FASL-OP-FRAME)
(FASD-NIBBLE Q-COUNT)
(FASD-NIBBLE NON-Q-COUNT)
(FASD-NIBBLE (+ Q-COUNT (LSH NON-Q-COUNT 1)))
(DO ((I 0 (1+ I)))
((= I Q-COUNT))
(FASD-FEF-Q FEF I))
(DO ((I Q-COUNT (1+ I)))
((= I (+ Q-COUNT NON-Q-COUNT)))
(FASD-NIBBLE (%P-LDB-OFFSET %%Q-LOW-HALF FEF I))
(FASD-NIBBLE (%P-LDB-OFFSET %%Q-HIGH-HALF FEF I))))
NIL)
;when we change this, change also
FASD - ATTRIBUTES - LIST and COMPILE - STREAM
(defun map-to-old-cdr-code (new-cdr-code)
(setq new-cdr-code (ldb (byte 2 0) new-cdr-code))
(cond ((= cdr-next 0)
(nth new-cdr-code '(3 1 0 2)))
(t
new-cdr-code)))
(DEFUN FASD-FEF-Q (FEF I &AUX DATTP PTR PTR1 OFFSET (TYPE 0))
(SETQ DATTP (%P-LDB-OFFSET %%Q-DATA-TYPE FEF I))
(SETQ TYPE (LSH (map-to-old-cdr-code (%P-LDB-OFFSET %%Q-CDR-CODE FEF I)) 6))
(COND ((OR (= DATTP DTP-ONE-Q-FORWARD)
(= DATTP DTP-LOCATIVE))
(SETQ PTR1 (%P-CONTENTS-AS-LOCATIVE-OFFSET FEF I))
(SETQ PTR (%FIND-STRUCTURE-HEADER PTR1))
(SETQ OFFSET (%POINTER-DIFFERENCE PTR1 PTR))
(AND (> OFFSET #o17)
(FERROR "~O is too great an offset into atom while fasdumping FEF ~S"
OFFSET (%P-CONTENTS-OFFSET FEF %FEFHI-FCTN-NAME)))
(FASD-CONSTANT PTR)
(AND (= DATTP DTP-ONE-Q-FORWARD)
(SETQ TYPE (+ TYPE 20)))
(AND (= DATTP DTP-LOCATIVE)
(SETQ TYPE (+ TYPE 400)))
LOW 4 BITS OF TYPE ARE OFFSET TO ADD TO POINTER TO MAKE IT POINT AT VALUE CELL , ETC .
(SETQ TYPE (+ TYPE OFFSET)))
((= DATTP DTP-HEADER)
(FASD-CONSTANT (%P-LDB-OFFSET %%Q-POINTER FEF I)))
((= DATTP DTP-SELF-REF-POINTER)
(INCF TYPE 1000)
(MULTIPLE-VALUE-BIND (SYMBOL FLAG)
(SI:FLAVOR-DECODE-SELF-REF-POINTER (SI:FEF-FLAVOR-NAME FEF)
(%P-LDB-OFFSET %%Q-POINTER FEF I))
(FASD-EVAL1 `(SI:FLAVOR-VAR-SELF-REF-INDEX
',(IF FLAG
`(,(SI:FEF-FLAVOR-NAME FEF)
T ,SYMBOL)
`(,(SI:FEF-FLAVOR-NAME FEF) ,SYMBOL))))))
(T (FASD-CONSTANT (%P-CONTENTS-OFFSET FEF I))))
(FASD-NIBBLE TYPE))
;;; Does its own fasd-table adding since it has to be done in the middle
;;; of this function, after the fasl-op-array but before the initialization data.
(DEFUN FASD-ARRAY (ARRAY &AUX SIZE OBJECTIVE-P FAKE-ARRAY RETVAL NSP DIMS)
(SETQ NSP (NAMED-STRUCTURE-P ARRAY)
DIMS (ARRAY-DIMENSIONS ARRAY)
SIZE (APPLY #'* DIMS)
OBJECTIVE-P (NULL (CDR (ASSQ (ARRAY-TYPE ARRAY) ARRAY-BITS-PER-ELEMENT))))
(WHEN (NOT OBJECTIVE-P)
(LET ((EPQ (CDR (ASSQ (ARRAY-TYPE ARRAY) ARRAY-ELEMENTS-PER-Q))))
;; In this case, number of halfwords
(SETQ SIZE (IF (PLUSP EPQ) (CEILING (* SIZE 2) EPQ) (* SIZE 2 (MINUS EPQ))))))
(FASD-START-GROUP NIL 0 (IF OBJECTIVE-P FASL-OP-INITIALIZE-ARRAY
FASL-OP-INITIALIZE-NUMERIC-ARRAY))
(FASD-START-GROUP NSP 0 FASL-OP-ARRAY)
;; Area. Don't lose on arrays in QCOMPILE-TEMPORARY-AREA.
(FASD-CONSTANT NIL)
;; Type symbol
(FASD-CONSTANT (ARRAY-TYPE ARRAY))
;; Dimensions
(FASD-CONSTANT DIMS FASL-OP-TEMP-LIST)
;; Displaced-p. For now
(FASD-CONSTANT NIL)
;; Leader
(FASD-CONSTANT
(IF (ARRAY-HAS-LEADER-P ARRAY)
(DO ((I 0 (1+ I))
(LIST NIL)
(LIM (ARRAY-LEADER-LENGTH ARRAY)))
(( I LIM) LIST)
(PUSH (ARRAY-LEADER ARRAY I) LIST))
NIL)
FASL-OP-TEMP-LIST)
;; Index-offset. For now
(FASD-CONSTANT NIL)
;; Named-structure-p
(AND NSP (FASD-CONSTANT T))
Now that six values have been given , the group is over .
(SETQ RETVAL (FASD-TABLE-ADD ARRAY))
Next , continue to initialize the array .
(FASD-CONSTANT SIZE)
(SETQ FAKE-ARRAY
(MAKE-ARRAY SIZE ':TYPE (IF OBJECTIVE-P 'ART-Q 'ART-16B) ':DISPLACED-TO ARRAY))
(IF OBJECTIVE-P
(DOTIMES (I SIZE)
(IF (LOCATION-BOUNDP (AP-1-FORCE ARRAY I))
(FASD-CONSTANT (AREF FAKE-ARRAY I))
(FASD-NIBBLE (+ %FASL-GROUP-CHECK FASL-OP-NULL-ARRAY-ELEMENT))))
(DOTIMES (I SIZE)
(FASD-NIBBLE (AREF FAKE-ARRAY I))))
;(RETURN-ARRAY (PROG1 FAKE-ARRAY (SETQ FAKE-ARRAY NIL)))
RETVAL)
;;;; Low level routines to dump groups to deposit things in various places
(DEFUN FASD-SET-PARAMETER (PARAM VAL)
(declare (ignore param val))
(ferror "The function FASD-SET-PARAMETER is obsolete; please send a bug report.")
( PROG ( C - VAL )
( COND ( ( NULL ( SETQ C - VAL ( ) ) )
( FERROR " ~S is an unknown FASL parameter " ) ) )
; (COND ((EQUAL VAL (CDR C-VAL))(RETURN NIL)))
; (FASD-START-GROUP NIL 0 FASL-OP-SET-PARAMETER)
; (FASD-CONSTANT PARAM)
; (FASD-CONSTANT VAL)))
)
(DEFUN FASD-STORE-ARRAY-LEADER (VALUE ARRAY SUBSCR)
(FASD-START-GROUP NIL 3 FASL-OP-STOREIN-ARRAY-LEADER)
(FASD-NIBBLE ARRAY)
(FASD-NIBBLE SUBSCR)
(FASD-NIBBLE VALUE) ;NOTE: Nibbles not in same order as
0) ; STORE-ARRAY-LEADER!
(DEFUN FASD-STORE-FUNCTION-CELL (SYM IDX)
IDX an fasd - table index that has stuff desired to store .
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-FUNCTION-CELL)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFUN FASD-STORE-VALUE-CELL (SYM IDX)
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-SYMBOL-VALUE)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFF FASD-STOREIN-FUNCTION-CELL 'FASD-STORE-FUNCTION-CELL)
(DEFUN FASD-STORE-PROPERTY-CELL (SYM IDX)
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-PROPERTY-CELL)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFUN FASD-FILE-PROPERTY-LIST (PLIST)
(FASD-ATTRIBUTES-LIST PLIST NIL))
NOTE : This SETQ 's FASD - PACKAGE if a package is specified in PLIST
(DEFUN FASD-ATTRIBUTES-LIST (PLIST &OPTIONAL (ADD-FASD-DATA T))
(WHEN ADD-FASD-DATA
(MULTIPLE-VALUE-BIND (MAJOR MINOR)
(SI:GET-SYSTEM-VERSION "System")
(SETQ PLIST (LIST* ':FASD-DATA
`(,USER-ID
,SI:LOCAL-PRETTY-HOST-NAME
,(TIME:GET-UNIVERSAL-TIME)
,MAJOR ,MINOR
(NEW-DESTINATIONS T ;; NOT :new-destinations!!
;add this when we change FASD-FEF-Q
new - cdr - codes , ( : cdr - next 0 )
:SITE ,(SHORT-SITE-NAME)))
PLIST))))
(LET ((P (GETL (LOCF PLIST) '(:PACKAGE))))
(WHEN P
(SETQ FASD-PACKAGE (PKG-FIND-PACKAGE (CADR P)))))
(FASD-START-GROUP NIL 0 FASL-OP-FILE-PROPERTY-LIST)
;; Put package prefixes on everything in the plist since it will be loaded in
;; the wrong package. This way the symbols in the plist will always be loaded
;; into exactly the same package they were dumped from, while the rest of the
;; symbols in the file will be free to follow the usual rules for intern.
(LET ((FASD-PACKAGE NIL))
(FASD-CONSTANT PLIST)))
The old way of doing ( FASD - EVAL ) unfortunately does not nest properly ,
ie Can not be used to load into a FEF , because the loader is expecting to see
;;; a single next-value. So this is the way it probably should have been done in
the first place ..
(DEFUN FASD-EVAL1 (SEXP &OPTIONAL TEMPORARY)
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(FASD-CONSTANT SEXP (IF TEMPORARY FASL-OP-TEMP-LIST FASL-OP-LIST))
;(FASD-TABLE-ADD FASD-TABLE-IGNORE)
(FASD-TABLE-NEXT-INDEX))
(DEFUN FASD-EVAL-CONSTRUCT-CONSTANT (SEXP)
"Fasdump a group to eval FORM, but let our caller record it in the fasd table.
He will record the index we use under the object that FORM
is supposed to reconstruct at load time."
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(FASD-CONSTANT SEXP))
(DEFUN FASD-EVAL-MEMOIZED (FORM &OPTIONAL TEMPORARY &AUX TEM)
(COND ((SETQ TEM (FASD-EVAL-TABLE-LOOKUP FORM)) ;If this object already dumped,
(COND (( TEM (LSH 1 16.))
(FASD-START-GROUP NIL 2 FASL-OP-LARGE-INDEX)
(FASD-NIBBLE (LDB (byte 8. 16.) TEM))
(FASD-NIBBLE (LDB (byte 16. 0) TEM)))
(T
(FASD-START-GROUP NIL 1 FASL-OP-INDEX) ;Just reference it in the FASL table.
(FASD-NIBBLE TEM)))
TEM)
(T (LET ((INDEX (FASD-EVAL1 FORM TEMPORARY)))
(FASD-EVAL-TABLE-ADD FORM INDEX)
INDEX))))
;;;; Routines to manipulate the FASD table
FASD simulates keeping a table that looks just like the one FASLOAD will keep .
FASD uses it to refer back to atoms which have been seen before ,
;;; so that no atom need be interned twice.
(defun fasd-table-next-index nil
(prog1 fasd-table-current-index
(setq fasd-table-current-index (1+ fasd-table-current-index))))
(defun fasd-table-add (data)
(let ((index (fasd-table-next-index)))
(puthash data index fasd-hash-table)
index))
(defun fasd-table-lookup (data)
(cond ((numberp data) nil)
(t (gethash data fasd-hash-table))))
The EVAL hash table is used to record data constructed by evaluations at load time ,
;;; in case we want to reuse the data instead of computing them twice.
(DEFUN FASD-EVAL-TABLE-LOOKUP (DATA)
(GETHASH DATA FASD-EVAL-HASH-TABLE))
(DEFUN FASD-EVAL-TABLE-ADD (DATA INDEX)
(PUTHASH DATA INDEX FASD-EVAL-HASH-TABLE))
;;; Set one of the parameters at the front of the FASD-TABLE, as in
;;; (FASD-TABLE-SET FASL-SYMBOL-STRING-AREA PN-STRING)
(DEFUN FASD-TABLE-SET (PARAM DATA)
(declare (ignore param data))
(ferror "The function FASD-TABLE-SET is obsolete; please send a bug report.")
( AS-1 DATA FASD - TABLE PARAM )
)
(DEFUN FASD-TABLE-LENGTH ()
FASD-TABLE-CURRENT-INDEX)
(DEFUN FASD-INITIALIZE (&AUX SI:FASL-TABLE)
(UNLESS FASD-TYO-BUFFER-ARRAY
(FERROR "~S must be called inside ~S"
'FASD-INITIALIZE 'LOCKING-RESOURCES))
(SETQ FASD-NEW-SYMBOL-FUNCTION NIL)
(SETQ FASD-PACKAGE PACKAGE)
(SETQ FASD-TABLE-CURRENT-INDEX FASL-TABLE-WORKING-OFFSET)
(SETF (FILL-POINTER FASD-TYO-BUFFER-ARRAY) 0))
;;;; Dump forms to be evaluated with hair for defun and setq
;;; Dump a group to evaluate a given form and return its value.
If OPTIMIZE is set , SETQ and DEFUN are handled specially ,
in a way appropriate for the top level of fasdump or qc - file .
(DEFUN FASD-FORM (FORM &OPTIONAL OPTIMIZE)
"Put something to execute FORM into the QFASL file being written.
If OPTIMIZE is true, many common types of forms are handled specially,
including SETQ, DEFF, DEFUN, etc. In particular, (DEFUN FOO)
is processed by dumping FOO's current function definition."
(COND ((OR (MEMQ FORM '(T NIL))
(STRINGP FORM)
(NUMBERP FORM))
(FASD-CONSTANT FORM))
((SYMBOLP FORM) (FASD-SYMEVAL FORM))
((ATOM FORM) (FASD-RANDOM-FORM FORM))
((NOT (SYMBOLP (CAR FORM))) (FASD-RANDOM-FORM FORM))
((EQ (CAR FORM) 'QUOTE)
(FASD-CONSTANT (CADR FORM)))
((NOT OPTIMIZE)
(FASD-RANDOM-FORM FORM))
((EQ (CAR FORM) 'SETQ)
(FASD-SETQ FORM))
((EQ (CAR FORM) 'DEFF)
(FASD-STORE-FUNCTION-CELL (CADR FORM) (FASD-FORM (CADDR FORM))))
((AND (EQ (CAR FORM) 'FSET-CAREFULLY)
(CONSP (CADR FORM))
(EQ (CAADR FORM) 'QUOTE))
(FASD-STORE-FUNCTION-CELL (CADADR FORM) (FASD-FORM (CADDR FORM))))
((EQ (CAR FORM) 'DEFUN)
(FASD-FUNCTION (CADR FORM)
(FDEFINITION (SI:UNENCAPSULATE-FUNCTION-SPEC (CADR FORM)))))
(T (FASD-RANDOM-FORM FORM))))
( DEFUN FASD - DECLARATION ( DCL )
( AND ( MEMQ ( CAR DCL ) ' ( SPECIAL UNSPECIAL )
; (FASD-FORM DCL)))
;;; Dump something to eval some random form (which is the argument).
(DEFUN FASD-RANDOM-FORM (FRM)
(FASD-EVAL1 FRM))
Given the body of a DEFUN , dump stuff to perform it .
(DEFUN FASD-FUNCTION (FUNCTION DEFINITION)
(FASD-STORE-FUNCTION-CELL FUNCTION (FASD-CONSTANT DEFINITION)))
Given the body of a SETQ , dump stuff to perform it .
(DEFUN FASD-SETQ (SETQ-FORM)
(DO ((PAIRS (CDR SETQ-FORM) (CDDR PAIRS)))
((NULL PAIRS))
(CHECK-ARG PAIRS (ATOM (CAR PAIRS)) "a SETQ form")
(FASD-STORE-VALUE-CELL (CAR PAIRS) (FASD-FORM (CADR PAIRS)))))
(DEFUN FASD-SYMEVAL (SEXP)
(FASD-START-GROUP NIL 0 FASL-OP-FETCH-SYMBOL-VALUE)
(FASD-CONSTANT SEXP)
;(FASD-TABLE-ADD FASD-TABLE-IGNORE)
(FASD-TABLE-NEXT-INDEX))
(DEFUN FASD-SYMBOL-VALUE (FILENAME SYMBOL &OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME containing SYMBOL's value.
Loading the file will set the symbol back to the same value."
(WITH-OPEN-FILE (FASD-STREAM (FS:MERGE-PATHNAME-DEFAULTS FILENAME
FS:LOAD-PATHNAME-DEFAULTS
':QFASL)
':DIRECTION ':OUTPUT
':CHARACTERS NIL
':BYTE-SIZE 16.)
(LET ((FASD-PACKAGE NIL)) ;in case fasd-attributes-list bashes it
(LOCKING-RESOURCES
(FASD-INITIALIZE)
(FASD-START-FILE)
(FASD-ATTRIBUTES-LIST
(IF (GETL (LOCF ATTRIBUTE-LIST) '(:PACKAGE))
ATTRIBUTE-LIST
(LIST* ':PACKAGE (PACKAGE-NAME (SYMBOL-PACKAGE SYMBOL)) ATTRIBUTE-LIST)))
(FASD-FORM `(SETF (SYMBOL-VALUE ',SYMBOL) ',(SYMBOL-VALUE SYMBOL)))
(FASD-END-WHACK)
(FASD-END-FILE)))))
Copied from LAD : RELEASE-3.SYS ; QCFASD.LISP#258 on 2 - Oct-86 05:07:32
(defun dump-forms-to-fasd-stream (fasd-stream forms-list)
"Dump forms to a fasd-stream only within a with-open-fasd-file form."
(dolist (form forms-list)
(if ( (fasd-table-length) qc-file-whack-threshold)
(fasd-end-whack))
(fasd-form form)))
Copied from LAD : RELEASE-3.SYS ; QCFASD.LISP#258 on 2 - Oct-86 05:07:32
(defun open-fasd-file (filename)
(open (fs:merge-pathname-defaults
filename fs:load-pathname-defaults ':qfasl)
':direction ':output
':characters nil
':byte-size 16.))
Copied from LAD : RELEASE-3.SYS ; QCFASD.LISP#258 on 2 - Oct-86 05:07:33
(defmacro with-open-fasd-file ((stream-variable filename &optional attribute-list) &body body)
"Open filename and bind stream-variable to a fasd-stream.
No output operations should be performed on the fasd-stream except as a side-affect of
invoking dump-forms-to-fasd-stream."
(once-only (attribute-list)
`(with-open-stream (,stream-variable (open-fasd-file ,filename))
(let ((fasd-stream ,stream-variable))
(let ((fasd-package nil)) ;in case fasd-attributes-list bashes it
(locking-resources
(fasd-initialize)
(fasd-start-file)
(fasd-attributes-list
(if (getl (locf ,attribute-list) '(:package))
,attribute-list
(list* ':package ':user ,attribute-list)))
,@body
(fasd-end-whack)
(fasd-end-file)))))))
Copied from LAD : RELEASE-3.SYS ; QCFASD.LISP#258 on 2 - Oct-86 05:07:34
(DEFUN DUMP-FORMS-TO-FILE (FILENAME FORMS-LIST &OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME which, when loaded, will execute the forms in FORMS-LIST.
ATTRIBUTE-LIST is a file attribute list which controls, among other things,
what package the file is dumped and loaded in (default is USER)."
(with-open-fasd-file (stream filename attribute-list)
(dump-forms-to-fasd-stream stream forms-list)))
(DEFUN FASD-FONT (FONT-SYMBOL)
"Write the font FONT into a QFASL file named SYS: FONTS; name-of-font QFASL."
(DUMP-FORMS-TO-FILE (FS:MAKE-PATHNAME ':HOST "SYS"
':DIRECTORY "FONTS"
':NAME (SYMBOL-NAME FONT-SYMBOL))
`((proclaim (special ,font-symbol))
(SETQ ,FONT-SYMBOL ,(TV::FONT-EVALUATE FONT-SYMBOL)))
'(:PACKAGE :FONTS)))
Copied from LAD : RELEASE-3.SYS ; QCFASD.LISP#258 on 2 - Oct-86 05:07:34
(DEFUN FASD-FILE-SYMBOLS-PROPERTIES (FILENAME SYMBOLS PROPERTIES
DUMP-VALUES-P DUMP-FUNCTIONS-P
NEW-SYMBOL-FUNCTION
&OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME containing data on SYMBOLS.
The data can include the symbols' values, function definitions, and properties.
PROPERTIES is a list of which properties should be dumped.
DUMP-VALUES-P says whether to dump their values.
DUMP-FUNCTIONS-P says whether to dump their function definitions.
NEW-SYMBOL-FUNCTION is a function to call whenever a new symbol
not previously seen is found in a value being dumped. The function
can cause the new symbol's data to be dumped like the specified symbols.
When the NEW-SYMBOL-FUNCTION is called, FASD-SYMBOL-LIST will be a list
of symbols waiting to be dumped, and FASD-ALREADY-DUMPED-SYMBOL-LIST a
list of those already dumped. To make a new symbol be dumped, push it
on the former if it is not in either of those two."
(WITH-OPEN-FILE (FASD-STREAM (FS:MERGE-PATHNAME-DEFAULTS FILENAME
FS:LOAD-PATHNAME-DEFAULTS
':QFASL)
':DIRECTION ':OUTPUT
':CHARACTERS NIL
':BYTE-SIZE 16.)
(LET ((FASD-PACKAGE NIL)) ;in case fasd-attributes-list bashes it
(LOCKING-RESOURCES
(FASD-INITIALIZE)
(FASD-START-FILE)
(FASD-ATTRIBUTES-LIST
(IF (GETL (LOCF ATTRIBUTE-LIST) '(:PACKAGE))
ATTRIBUTE-LIST
(LIST* ':PACKAGE ':USER ATTRIBUTE-LIST)))
(FASD-SYMBOLS-PROPERTIES SYMBOLS PROPERTIES DUMP-VALUES-P
DUMP-FUNCTIONS-P NEW-SYMBOL-FUNCTION)
(FASD-END-WHACK)
(FASD-END-FILE)))))
(DEFVAR FASD-SYMBOL-LIST)
(DEFVAR FASD-ALREADY-DUMPED-SYMBOL-LIST)
(DEFVAR FASD-NEW-SYMBOL-FUNCTION)
Take each symbol in SYMBOLS and do a FASD - SYMBOL - PROPERTIES on it .
The symbols already thus dumped are put on FASD - ALREADY - DUMPED - SYMBOL - LIST .
;;; The NEW-SYMBOL-FUNCTION can add more symbols to FASD-SYMBOL-LIST
;;; to cause them to be dumped as well.
(DEFUN FASD-SYMBOLS-PROPERTIES (SYMBOLS PROPERTIES DUMP-VALUES
DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)
(DO ((FASD-SYMBOL-LIST SYMBOLS)
(FASD-ALREADY-DUMPED-SYMBOL-LIST)
(SYMBOL))
((NULL FASD-SYMBOL-LIST))
(SETQ SYMBOL (POP FASD-SYMBOL-LIST))
(PUSH SYMBOL FASD-ALREADY-DUMPED-SYMBOL-LIST)
(FASD-SYMBOL-PROPERTIES SYMBOL PROPERTIES
DUMP-VALUES DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)))
;;; Dump into the FASD file the properties of SYMBOL in PROPERTIES,
;;; and the value if DUMP-VALUES, and the function cell if DUMP-FUNCTIONS.
;;; NEW-SYMBOL-FUNCTION will be called on appropriate symbols in the
;;; structures which are dumped.
(DEFUN FASD-SYMBOL-PROPERTIES (SYMBOL PROPERTIES DUMP-VALUES
DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)
(WHEN (AND DUMP-VALUES (BOUNDP SYMBOL))
(FASD-STORE-VALUE-CELL SYMBOL (FASD-CONSTANT-TRACING-SYMBOLS (SYMBOL-VALUE SYMBOL)
NEW-SYMBOL-FUNCTION)))
(WHEN (AND DUMP-FUNCTIONS (FBOUNDP SYMBOL))
(FASD-STORE-FUNCTION-CELL SYMBOL (FASD-CONSTANT-TRACING-SYMBOLS (SYMBOL-FUNCTION SYMBOL)
NEW-SYMBOL-FUNCTION)))
(MAPC #'(LAMBDA (PROP &AUX (TEM (GET SYMBOL PROP)))
;; If this atom has this property, dump a DEFPROP to be evaled.
(WHEN TEM
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(PROGN
(FASD-START-GROUP NIL 1 FASL-OP-LIST)
4 is length of the DEFPROP form .
(FASD-CONSTANT 'DEFPROP) ;Don't use FASD-FORM, since we want to detect
(FASD-CONSTANT SYMBOL) ; new symbols in the value of the property.
(FASD-CONSTANT-TRACING-SYMBOLS TEM NEW-SYMBOL-FUNCTION)
(FASD-CONSTANT PROP)
(FASD-TABLE-NEXT-INDEX))
(FASD-TABLE-NEXT-INDEX)))
PROPERTIES))
(DEFUN FASD-CONSTANT-TRACING-SYMBOLS (OBJECT FASD-NEW-SYMBOL-FUNCTION)
(FASD-CONSTANT OBJECT))
;;; Use this as the NEW-SYMBOL-FUNCTION, for nice results:
;;; All the substructures of the structures being dumped are also dumped.
(DEFUN FASD-SYMBOL-PUSH (SYMBOL)
(OR (MEMQ SYMBOL FASD-SYMBOL-LIST)
(MEMQ SYMBOL FASD-ALREADY-DUMPED-SYMBOL-LIST)
(PUSH SYMBOL FASD-SYMBOL-LIST)))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/sys/qcfasd.lisp | lisp | Package : COMPILER ; Base:8 ; : ZL -*-
The package in which the fasl file will presumably be loaded
If this is the car of a list, the cdr is a form to be evaluated at load time
The "#," reader macro uses this
list is a named-lambda, it will be compiled.
Make it the same as FUNCTION for when the interpreter or compiler sees it.
Do NOT make it a displacing macro!
This is an a-list of special markers that may exist in the car of a cons
and the function to fasdump such conses. A typical thing for such a
a function to do is to call FASD-EVAL1 on some suitable form.
This is an a-list of area numbers and functions to fasdump conses in that
area. The function is treated just as for fasd-markers.
Output the things that divide a fasl file into its major subparts
Output sixbit /QFASL/ to start a fasl file.
Also clears out the temp area
Reset fasd table, but not temporary areas
Given a sexp dump a group to cons up that sexp and return it
This is the main function of FASD. It takes a Lisp object and
For FASD-SYMBOLS-PROPERTIES,
make sure we examine all symbols in
the data that we dump.
Check if this object already dumped
Yup.
Just reference it in the FASL TABLE.
Determine the size of the list, and check for special markers
Now dump that many conses and the tail if non-null
FASL-OP-LIST-COMPONENT speeds things up by not bloating the fasl
table with conses out of the middle of lists.
Here if need a prefix of any kind.
If there was a prefix
>> this should really be sharp-flag, except that I don't want to (possibly)
This is expected to do the FASD-TABLE-ADD itself,
since FASD-ARRAY has to do so.
(defsubst %QCFASD-short-float-exponent (short-float)
If exponent is in range for FASL-OP-FLOAT, use it.
exp is #o-200 in this case.
So that LDB's will work.
exclude sign
implied leading digit
when we change this, change also
Does its own fasd-table adding since it has to be done in the middle
of this function, after the fasl-op-array but before the initialization data.
In this case, number of halfwords
Area. Don't lose on arrays in QCOMPILE-TEMPORARY-AREA.
Type symbol
Dimensions
Displaced-p. For now
Leader
Index-offset. For now
Named-structure-p
(RETURN-ARRAY (PROG1 FAKE-ARRAY (SETQ FAKE-ARRAY NIL)))
Low level routines to dump groups to deposit things in various places
(COND ((EQUAL VAL (CDR C-VAL))(RETURN NIL)))
(FASD-START-GROUP NIL 0 FASL-OP-SET-PARAMETER)
(FASD-CONSTANT PARAM)
(FASD-CONSTANT VAL)))
NOTE: Nibbles not in same order as
STORE-ARRAY-LEADER!
NOT :new-destinations!!
add this when we change FASD-FEF-Q
Put package prefixes on everything in the plist since it will be loaded in
the wrong package. This way the symbols in the plist will always be loaded
into exactly the same package they were dumped from, while the rest of the
symbols in the file will be free to follow the usual rules for intern.
a single next-value. So this is the way it probably should have been done in
(FASD-TABLE-ADD FASD-TABLE-IGNORE)
If this object already dumped,
Just reference it in the FASL table.
Routines to manipulate the FASD table
so that no atom need be interned twice.
in case we want to reuse the data instead of computing them twice.
Set one of the parameters at the front of the FASD-TABLE, as in
(FASD-TABLE-SET FASL-SYMBOL-STRING-AREA PN-STRING)
Dump forms to be evaluated with hair for defun and setq
Dump a group to evaluate a given form and return its value.
(FASD-FORM DCL)))
Dump something to eval some random form (which is the argument).
(FASD-TABLE-ADD FASD-TABLE-IGNORE)
in case fasd-attributes-list bashes it
QCFASD.LISP#258 on 2 - Oct-86 05:07:32
QCFASD.LISP#258 on 2 - Oct-86 05:07:32
QCFASD.LISP#258 on 2 - Oct-86 05:07:33
in case fasd-attributes-list bashes it
QCFASD.LISP#258 on 2 - Oct-86 05:07:34
QCFASD.LISP#258 on 2 - Oct-86 05:07:34
in case fasd-attributes-list bashes it
The NEW-SYMBOL-FUNCTION can add more symbols to FASD-SYMBOL-LIST
to cause them to be dumped as well.
Dump into the FASD file the properties of SYMBOL in PROPERTIES,
and the value if DUMP-VALUES, and the function cell if DUMP-FUNCTIONS.
NEW-SYMBOL-FUNCTION will be called on appropriate symbols in the
structures which are dumped.
If this atom has this property, dump a DEFPROP to be evaled.
Don't use FASD-FORM, since we want to detect
new symbols in the value of the property.
Use this as the NEW-SYMBOL-FUNCTION, for nice results:
All the substructures of the structures being dumped are also dumped. |
* * ( c ) Copyright 1980 Massachusetts Institute of Technology * *
(DEFVAR FASD-TABLE-CURRENT-INDEX NIL "Allocating index for runtime fasl table")
(DEFVAR FASD-HASH-TABLE NIL "FASD time hash table")
(DEFVAR FASD-EVAL-HASH-TABLE NIL "FASD time hash table for self ref pointers")
(DEFVAR FASD-TYO-BUFFER-ARRAY nil "FASD output buffer")
(DEFVAR FASD-STREAM)
(DEFVAR EVAL-AT-LOAD-TIME-MARKER (COPY-SYMBOL 'EVAL-AT-LOAD-TIME-MARKER NIL))
(PUTPROP EVAL-AT-LOAD-TIME-MARKER '(EXECUTION-CONTEXT-EVAL-WARNING) 'OPTIMIZERS)
(DEFUN EXECUTION-CONTEXT-EVAL-WARNING (FORM)
(WARN 'LOAD-TIME-EVAL :IMPOSSIBLE "Load-time eval (#,~S) not inside quoted structure"
(CDR FORM))
(EVAL (CDR FORM)))
If this uninterned symbol is seen as the car of a list , and the cadr of the
(DEFVAR FUNCTIONAL-CONSTANT-MARKER (COPY-SYMBOL 'FUNCTIONAL-CONSTANT-MARKER NIL))
(FSET FUNCTIONAL-CONSTANT-MARKER
'(MACRO LAMBDA (X) (CONS 'FUNCTION (CDR X))))
(DEFVAR FASD-MARKERS-ALIST
(LIST (CONS EVAL-AT-LOAD-TIME-MARKER 'FASD-EVAL-AT-LOAD-TIME)
(CONS FUNCTIONAL-CONSTANT-MARKER 'FASD-FUNCTIONAL-CONSTANT)))
(DEFVAR FASD-MAGIC-AREAS-ALIST NIL)
(DEFUN FASD-NIBBLE (NUMBER)
(WHEN (NULL (VECTOR-PUSH NUMBER FASD-TYO-BUFFER-ARRAY))
(FASD-CLEAR-NIBBLE-BUFFER)
(VECTOR-PUSH NUMBER FASD-TYO-BUFFER-ARRAY)))
(DEFUN FASD-CLEAR-NIBBLE-BUFFER ()
(SEND FASD-STREAM ':STRING-OUT FASD-TYO-BUFFER-ARRAY)
(SETF (FILL-POINTER FASD-TYO-BUFFER-ARRAY) 0))
(DEFUN FASD-START-FILE ()
(FASD-NIBBLE #o143150)
(FASD-NIBBLE #o71660))
(DEFUN FASD-START-GROUP (FLAG LENGTH TYPE)
(LET* ((OUT-LEN (LSH (MIN LENGTH #o377)
(- FASL-GROUP-LENGTH-SHIFT))))
(FASD-NIBBLE (+ %FASL-GROUP-CHECK
(+ (IF FLAG %FASL-GROUP-FLAG 0)
(+ OUT-LEN
TYPE))))
(AND ( LENGTH #o377)
(FASD-NIBBLE LENGTH)))
NIL)
(DEFUN FASD-FUNCTION-HEADER (FCTN-NAME)
(FASD-START-GROUP NIL 0 FASL-OP-FUNCTION-HEADER)
(FASD-CONSTANT FCTN-NAME)
(FASD-CONSTANT 0)
NIL)
(DEFUN FASD-FUNCTION-END ()
(FASD-START-GROUP NIL 0 FASL-OP-FUNCTION-END)
NIL)
(DEFUN FASD-END-WHACK ()
(FASD-START-GROUP NIL 0 FASL-OP-END-OF-WHACK)
(CLRHASH FASD-HASH-TABLE)
(CLRHASH FASD-EVAL-HASH-TABLE)
(SETQ FASD-TABLE-CURRENT-INDEX FASL-TABLE-WORKING-OFFSET))
(DEFUN FASD-END-FILE ()
(FASD-START-GROUP NIL 0 FASL-OP-END-OF-FILE)
(FASD-CLEAR-NIBBLE-BUFFER)
NIL)
dumps it . The second ( optional ) arg is a FASL - OP to use
on any lists in the structure . It returns the IDX of the object .
(DEFUN FASD-CONSTANT (S-EXP &OPTIONAL (LIST-OP FASL-OP-LIST))
(BLOCK NIL
(COND (( TEM (LSH 1 16.))
(FASD-START-GROUP NIL 2 FASL-OP-LARGE-INDEX)
(FASD-NIBBLE (LDB (byte 8. 16.) TEM))
(FASD-NIBBLE (LDB (byte 16. 0) TEM)))
(T
(FASD-NIBBLE TEM)))
(RETURN TEM)))
(TYPECASE S-EXP
(INTEGER (FASD-FIXED S-EXP))
(CHARACTER (FASD-CHARACTER S-EXP))
(SHORT-FLOAT (FASD-SHORT-FLOAT S-EXP))
(SINGLE-FLOAT (FASD-SINGLE-FLOAT S-EXP))
(SYMBOL (FASD-SYMBOL S-EXP))
(STRING (RETURN (FASD-STRING S-EXP)))
(ARRAY (RETURN (FASD-ARRAY S-EXP)))
(COMPILED-FUNCTION (FASD-FEF S-EXP))
(CONS (RETURN (FASD-LIST S-EXP LIST-OP)))
(INSTANCE (FASD-EVAL-CONSTRUCT-CONSTANT
(OR (SEND S-EXP ':SEND-IF-HANDLES ':FASD-FORM)
(and (send s-exp :get-handler-for :reconstruction-init-plist)
`(APPLY 'MAKE-INSTANCE
'(,(TYPE-OF S-EXP)
. ,(SEND S-EXP ':RECONSTRUCTION-INIT-PLIST))))
(ferror "The instance ~S cannot be compiled.~
~&It is an instance of a type which does not provide a way to make a fast-load representation."
s-exp))))
(RATIO (RETURN (FASD-RATIONAL S-EXP)))
(COMPLEX (RETURN (FASD-COMPLEX S-EXP)))
(T (FERROR "The constant ~S cannot be compiled.~
~&The data-type ~S is not suitable for compiling as a fast-load constant (FASD-CONSTANT)."
S-EXP (TYPE-OF S-EXP))))
(FASD-TABLE-ADD S-EXP)))
(DEFUN FASD-LIST (S-EXP LIST-OP)
(DO ((L S-EXP (CDR L))
(N-CONSES 0 (1+ N-CONSES))
(MARK) (DOTTED))
((OR (ATOM L)
(SETQ MARK (ASSQ (CAR L) FASD-MARKERS-ALIST))
(AND FASD-MAGIC-AREAS-ALIST
(SETQ MARK (ASSQ (%AREA-NUMBER L) FASD-MAGIC-AREAS-ALIST))))
(COND ((ZEROP N-CONSES) (FUNCALL (CDR MARK) S-EXP))
(T (SETQ DOTTED (NOT (NULL L)))
(FASD-START-GROUP DOTTED 1 LIST-OP)
(FASD-NIBBLE (IF DOTTED (1+ N-CONSES) N-CONSES))
(DO ((L1 S-EXP (CDR L1)))
((EQ L1 L))
(FASD-CONSTANT (CAR L1) LIST-OP))
(COND ((NOT DOTTED))
((NOT MARK) (FASD-CONSTANT L))
(T (FUNCALL (CDR MARK) L)))
(IF (= LIST-OP FASL-OP-LIST-COMPONENT)
FASL-EVALED-VALUE
(FASD-TABLE-ADD S-EXP)))))))
(DEFUN FASD-EVAL-AT-LOAD-TIME (CONS)
(LET ((FORM (CDR CONS)))
(IF (AND (CONSP FORM)
(EQ (CAR FORM) 'SI::FLAVOR-VAR-SELF-REF-INDEX))
(FASD-EVAL-MEMOIZED FORM T)
(FASD-EVAL1 FORM))))
(DEFUN FASD-FUNCTIONAL-CONSTANT (CONS)
(COND ((AND (CONSP (CADR CONS))
(FUNCTIONP (CADR CONS) T))
(IF (VARIABLE-BOUNDP COMPILER-QUEUE)
(FERROR "Compiler is not recursive -- you will lose somehow"))
(QC-TRANSLATE-FUNCTION (IF (ATOM (CADADR CONS))
(CADADR CONS)
(CAR (CADADR CONS)))
(CADR CONS)
'MACRO-COMPILE
'QFASL-NO-FDEFINE))
(T (FASD-CONSTANT (CONS 'FUNCTION (CDR CONS))))))
(DEFUN FASD-SYMBOL (SYM &AUX (STARTED-FLAG NIL))
(MULTIPLE-VALUE-BIND (PKG-OR-STRING SHARP-FLAG)
(SI:PKG-PRINTING-PREFIX SYM FASD-PACKAGE)
(WHEN PKG-OR-STRING
(SETQ STARTED-FLAG T)
(FASD-START-GROUP SHARP-FLAG 1 FASL-OP-PACKAGE-SYMBOL)
This nibble is if should ignore local nicknames , else 2 .
(FASD-NIBBLE
(IF (AND (NOT (STRINGP PKG-OR-STRING))
(SI:ASSOC-EQUAL (PACKAGE-PREFIX-PRINT-NAME PKG-OR-STRING)
(DONT-OPTIMIZE (SI:PKG-REFNAME-ALIST PACKAGE))))
#o0402
#o0002))
(FASD-CONSTANT (IF (STRINGP PKG-OR-STRING)
PKG-OR-STRING
(PACKAGE-PREFIX-PRINT-NAME PKG-OR-STRING))))
(IF STARTED-FLAG
If uninterned or no prefix needed
SYM
FASL-OP-SYMBOL
> > break things just at this moment
NIL))))
(DEFUN FASD-STRING (STRING)
(IF (OR (ARRAY-HAS-LEADER-P STRING)
(> (ARRAY-LENGTH STRING) (LSH 1 16.)))
(FASD-ARRAY STRING)
(FASD-WRITE-STRING STRING FASL-OP-STRING NIL)
(FASD-TABLE-ADD STRING)))
(DEFUN FASD-WRITE-STRING (OBJECT GROUP-TYPE FLAG)
(LET* ((STRING (STRING OBJECT))
(LENGTH (LENGTH STRING)))
(FASD-START-GROUP FLAG (CEILING LENGTH 2) GROUP-TYPE)
(DO ((I 0 (+ I 2))
C0 C1)
(( I LENGTH))
(SETQ C0 (CHAR-INT (CHAR STRING I))
C1 (IF (= (1+ I) LENGTH)
#o200
(CHAR-INT (CHAR STRING (1+ I)))))
(FASD-NIBBLE (+ (LSH C1 8.) C0)))))
(DEFUN FASD-FIXED (N)
(LET* ((ABS (ABS N))
(LENGTH (CEILING (HAULONG ABS) 16.)))
(FASD-START-GROUP (< N 0) LENGTH FASL-OP-FIXED)
(DO ((POS (* 16. (1- LENGTH)) (- POS 16.))
(C LENGTH (1- C)))
((ZEROP C))
(FASD-NIBBLE (LDB (+ (LSH POS 6) 16.) ABS)))))
(DEFUN FASD-CHARACTER (N)
(LET* ((ABS (ABS N))
(LENGTH (CEILING (HAULONG ABS) 16.)))
(FASD-START-GROUP (< N 0) LENGTH FASL-OP-CHARACTER)
(DO ((POS (* 16. (1- LENGTH)) (- POS 16.))
(C LENGTH (1- C)))
((ZEROP C))
(FASD-NIBBLE (LDB (+ (LSH POS 6) 16.) ABS)))))
(DEFUN FASD-SINGLE-FLOAT (N)
(FASD-START-GROUP NIL 3 FASL-OP-FLOAT)
(FASD-NIBBLE (%P-LDB-OFFSET #o1013 N 0))
(FASD-NIBBLE (DPB (%P-LDB-OFFSET #o0010 N 0) #o1010 (%P-LDB-OFFSET #o2010 N 1)))
(FASD-NIBBLE (%P-LDB-OFFSET #o0020 N 1))
NIL)
Can be replaced with % SHORT - FLOAT - EXPONENT once in system 99 .
( ldb ( byte 8 17 . ) ( % pointer short - float ) ) )
(DEFUN FASD-SHORT-FLOAT (N)
(LET ((EXP (- (SI:%SHORT-FLOAT-EXPONENT N) #o200)))
(IF (OR ( #o-100 EXP #o77)
(FASD-OLD-SMALL-FLOAT N)
(FASD-NEW-SMALL-FLOAT N))))
(DEFUN FASD-OLD-SMALL-FLOAT (N)
Convert excess # o200 exponent to excess # o100
(SETQ N (%POINTER-DIFFERENCE N #o40000000)))
(FASD-START-GROUP T 2 FASL-OP-FLOAT)
(FASD-NIBBLE (LDB #o2010 N))
(FASD-NIBBLE (LDB #o0020 N))
NIL)
(DEFUN FASD-NEW-SMALL-FLOAT (N &AUX FRACTION EXPONENT)
(FASD-START-GROUP (MINUSP N) 5 FASL-OP-NEW-FLOAT)
(SETQ FRACTION (SI::%SHORT-FLOAT-MANTISSA N)
EXPONENT (SI::%SHORT-FLOAT-EXPONENT N))
8 bits for exponent , including sign
(FASD-NIBBLE EXPONENT)
17 bits for mantissa , excluding sign
(DEFUN FASD-RATIONAL (RAT)
(FASD-START-GROUP NIL 0 FASL-OP-RATIONAL)
(FASD-CONSTANT (NUMERATOR RAT))
(FASD-CONSTANT (DENOMINATOR RAT))
(FASD-TABLE-ADD RAT))
(DEFUN FASD-COMPLEX (COMPLEX)
(FASD-START-GROUP NIL 0 FASL-OP-COMPLEX)
(FASD-CONSTANT (REALPART COMPLEX))
(FASD-CONSTANT (IMAGPART COMPLEX))
(FASD-TABLE-ADD COMPLEX))
(DEFUN FASD-FEF (FEF)
(LET* ((Q-COUNT (%STRUCTURE-BOXED-SIZE FEF))
(NON-Q-COUNT (- (%STRUCTURE-TOTAL-SIZE FEF) Q-COUNT)))
(FASD-START-GROUP NIL 3 FASL-OP-FRAME)
(FASD-NIBBLE Q-COUNT)
(FASD-NIBBLE NON-Q-COUNT)
(FASD-NIBBLE (+ Q-COUNT (LSH NON-Q-COUNT 1)))
(DO ((I 0 (1+ I)))
((= I Q-COUNT))
(FASD-FEF-Q FEF I))
(DO ((I Q-COUNT (1+ I)))
((= I (+ Q-COUNT NON-Q-COUNT)))
(FASD-NIBBLE (%P-LDB-OFFSET %%Q-LOW-HALF FEF I))
(FASD-NIBBLE (%P-LDB-OFFSET %%Q-HIGH-HALF FEF I))))
NIL)
FASD - ATTRIBUTES - LIST and COMPILE - STREAM
(defun map-to-old-cdr-code (new-cdr-code)
(setq new-cdr-code (ldb (byte 2 0) new-cdr-code))
(cond ((= cdr-next 0)
(nth new-cdr-code '(3 1 0 2)))
(t
new-cdr-code)))
(DEFUN FASD-FEF-Q (FEF I &AUX DATTP PTR PTR1 OFFSET (TYPE 0))
(SETQ DATTP (%P-LDB-OFFSET %%Q-DATA-TYPE FEF I))
(SETQ TYPE (LSH (map-to-old-cdr-code (%P-LDB-OFFSET %%Q-CDR-CODE FEF I)) 6))
(COND ((OR (= DATTP DTP-ONE-Q-FORWARD)
(= DATTP DTP-LOCATIVE))
(SETQ PTR1 (%P-CONTENTS-AS-LOCATIVE-OFFSET FEF I))
(SETQ PTR (%FIND-STRUCTURE-HEADER PTR1))
(SETQ OFFSET (%POINTER-DIFFERENCE PTR1 PTR))
(AND (> OFFSET #o17)
(FERROR "~O is too great an offset into atom while fasdumping FEF ~S"
OFFSET (%P-CONTENTS-OFFSET FEF %FEFHI-FCTN-NAME)))
(FASD-CONSTANT PTR)
(AND (= DATTP DTP-ONE-Q-FORWARD)
(SETQ TYPE (+ TYPE 20)))
(AND (= DATTP DTP-LOCATIVE)
(SETQ TYPE (+ TYPE 400)))
LOW 4 BITS OF TYPE ARE OFFSET TO ADD TO POINTER TO MAKE IT POINT AT VALUE CELL , ETC .
(SETQ TYPE (+ TYPE OFFSET)))
((= DATTP DTP-HEADER)
(FASD-CONSTANT (%P-LDB-OFFSET %%Q-POINTER FEF I)))
((= DATTP DTP-SELF-REF-POINTER)
(INCF TYPE 1000)
(MULTIPLE-VALUE-BIND (SYMBOL FLAG)
(SI:FLAVOR-DECODE-SELF-REF-POINTER (SI:FEF-FLAVOR-NAME FEF)
(%P-LDB-OFFSET %%Q-POINTER FEF I))
(FASD-EVAL1 `(SI:FLAVOR-VAR-SELF-REF-INDEX
',(IF FLAG
`(,(SI:FEF-FLAVOR-NAME FEF)
T ,SYMBOL)
`(,(SI:FEF-FLAVOR-NAME FEF) ,SYMBOL))))))
(T (FASD-CONSTANT (%P-CONTENTS-OFFSET FEF I))))
(FASD-NIBBLE TYPE))
(DEFUN FASD-ARRAY (ARRAY &AUX SIZE OBJECTIVE-P FAKE-ARRAY RETVAL NSP DIMS)
(SETQ NSP (NAMED-STRUCTURE-P ARRAY)
DIMS (ARRAY-DIMENSIONS ARRAY)
SIZE (APPLY #'* DIMS)
OBJECTIVE-P (NULL (CDR (ASSQ (ARRAY-TYPE ARRAY) ARRAY-BITS-PER-ELEMENT))))
(WHEN (NOT OBJECTIVE-P)
(LET ((EPQ (CDR (ASSQ (ARRAY-TYPE ARRAY) ARRAY-ELEMENTS-PER-Q))))
(SETQ SIZE (IF (PLUSP EPQ) (CEILING (* SIZE 2) EPQ) (* SIZE 2 (MINUS EPQ))))))
(FASD-START-GROUP NIL 0 (IF OBJECTIVE-P FASL-OP-INITIALIZE-ARRAY
FASL-OP-INITIALIZE-NUMERIC-ARRAY))
(FASD-START-GROUP NSP 0 FASL-OP-ARRAY)
(FASD-CONSTANT NIL)
(FASD-CONSTANT (ARRAY-TYPE ARRAY))
(FASD-CONSTANT DIMS FASL-OP-TEMP-LIST)
(FASD-CONSTANT NIL)
(FASD-CONSTANT
(IF (ARRAY-HAS-LEADER-P ARRAY)
(DO ((I 0 (1+ I))
(LIST NIL)
(LIM (ARRAY-LEADER-LENGTH ARRAY)))
(( I LIM) LIST)
(PUSH (ARRAY-LEADER ARRAY I) LIST))
NIL)
FASL-OP-TEMP-LIST)
(FASD-CONSTANT NIL)
(AND NSP (FASD-CONSTANT T))
Now that six values have been given , the group is over .
(SETQ RETVAL (FASD-TABLE-ADD ARRAY))
Next , continue to initialize the array .
(FASD-CONSTANT SIZE)
(SETQ FAKE-ARRAY
(MAKE-ARRAY SIZE ':TYPE (IF OBJECTIVE-P 'ART-Q 'ART-16B) ':DISPLACED-TO ARRAY))
(IF OBJECTIVE-P
(DOTIMES (I SIZE)
(IF (LOCATION-BOUNDP (AP-1-FORCE ARRAY I))
(FASD-CONSTANT (AREF FAKE-ARRAY I))
(FASD-NIBBLE (+ %FASL-GROUP-CHECK FASL-OP-NULL-ARRAY-ELEMENT))))
(DOTIMES (I SIZE)
(FASD-NIBBLE (AREF FAKE-ARRAY I))))
RETVAL)
(DEFUN FASD-SET-PARAMETER (PARAM VAL)
(declare (ignore param val))
(ferror "The function FASD-SET-PARAMETER is obsolete; please send a bug report.")
( PROG ( C - VAL )
( COND ( ( NULL ( SETQ C - VAL ( ) ) )
( FERROR " ~S is an unknown FASL parameter " ) ) )
)
(DEFUN FASD-STORE-ARRAY-LEADER (VALUE ARRAY SUBSCR)
(FASD-START-GROUP NIL 3 FASL-OP-STOREIN-ARRAY-LEADER)
(FASD-NIBBLE ARRAY)
(FASD-NIBBLE SUBSCR)
(DEFUN FASD-STORE-FUNCTION-CELL (SYM IDX)
IDX an fasd - table index that has stuff desired to store .
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-FUNCTION-CELL)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFUN FASD-STORE-VALUE-CELL (SYM IDX)
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-SYMBOL-VALUE)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFF FASD-STOREIN-FUNCTION-CELL 'FASD-STORE-FUNCTION-CELL)
(DEFUN FASD-STORE-PROPERTY-CELL (SYM IDX)
(FASD-START-GROUP NIL 1 FASL-OP-STOREIN-PROPERTY-CELL)
(FASD-NIBBLE IDX)
(FASD-CONSTANT SYM)
0)
(DEFUN FASD-FILE-PROPERTY-LIST (PLIST)
(FASD-ATTRIBUTES-LIST PLIST NIL))
NOTE : This SETQ 's FASD - PACKAGE if a package is specified in PLIST
(DEFUN FASD-ATTRIBUTES-LIST (PLIST &OPTIONAL (ADD-FASD-DATA T))
(WHEN ADD-FASD-DATA
(MULTIPLE-VALUE-BIND (MAJOR MINOR)
(SI:GET-SYSTEM-VERSION "System")
(SETQ PLIST (LIST* ':FASD-DATA
`(,USER-ID
,SI:LOCAL-PRETTY-HOST-NAME
,(TIME:GET-UNIVERSAL-TIME)
,MAJOR ,MINOR
new - cdr - codes , ( : cdr - next 0 )
:SITE ,(SHORT-SITE-NAME)))
PLIST))))
(LET ((P (GETL (LOCF PLIST) '(:PACKAGE))))
(WHEN P
(SETQ FASD-PACKAGE (PKG-FIND-PACKAGE (CADR P)))))
(FASD-START-GROUP NIL 0 FASL-OP-FILE-PROPERTY-LIST)
(LET ((FASD-PACKAGE NIL))
(FASD-CONSTANT PLIST)))
The old way of doing ( FASD - EVAL ) unfortunately does not nest properly ,
ie Can not be used to load into a FEF , because the loader is expecting to see
the first place ..
(DEFUN FASD-EVAL1 (SEXP &OPTIONAL TEMPORARY)
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(FASD-CONSTANT SEXP (IF TEMPORARY FASL-OP-TEMP-LIST FASL-OP-LIST))
(FASD-TABLE-NEXT-INDEX))
(DEFUN FASD-EVAL-CONSTRUCT-CONSTANT (SEXP)
"Fasdump a group to eval FORM, but let our caller record it in the fasd table.
He will record the index we use under the object that FORM
is supposed to reconstruct at load time."
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(FASD-CONSTANT SEXP))
(DEFUN FASD-EVAL-MEMOIZED (FORM &OPTIONAL TEMPORARY &AUX TEM)
(COND (( TEM (LSH 1 16.))
(FASD-START-GROUP NIL 2 FASL-OP-LARGE-INDEX)
(FASD-NIBBLE (LDB (byte 8. 16.) TEM))
(FASD-NIBBLE (LDB (byte 16. 0) TEM)))
(T
(FASD-NIBBLE TEM)))
TEM)
(T (LET ((INDEX (FASD-EVAL1 FORM TEMPORARY)))
(FASD-EVAL-TABLE-ADD FORM INDEX)
INDEX))))
FASD simulates keeping a table that looks just like the one FASLOAD will keep .
FASD uses it to refer back to atoms which have been seen before ,
(defun fasd-table-next-index nil
(prog1 fasd-table-current-index
(setq fasd-table-current-index (1+ fasd-table-current-index))))
(defun fasd-table-add (data)
(let ((index (fasd-table-next-index)))
(puthash data index fasd-hash-table)
index))
(defun fasd-table-lookup (data)
(cond ((numberp data) nil)
(t (gethash data fasd-hash-table))))
The EVAL hash table is used to record data constructed by evaluations at load time ,
(DEFUN FASD-EVAL-TABLE-LOOKUP (DATA)
(GETHASH DATA FASD-EVAL-HASH-TABLE))
(DEFUN FASD-EVAL-TABLE-ADD (DATA INDEX)
(PUTHASH DATA INDEX FASD-EVAL-HASH-TABLE))
(DEFUN FASD-TABLE-SET (PARAM DATA)
(declare (ignore param data))
(ferror "The function FASD-TABLE-SET is obsolete; please send a bug report.")
( AS-1 DATA FASD - TABLE PARAM )
)
(DEFUN FASD-TABLE-LENGTH ()
FASD-TABLE-CURRENT-INDEX)
(DEFUN FASD-INITIALIZE (&AUX SI:FASL-TABLE)
(UNLESS FASD-TYO-BUFFER-ARRAY
(FERROR "~S must be called inside ~S"
'FASD-INITIALIZE 'LOCKING-RESOURCES))
(SETQ FASD-NEW-SYMBOL-FUNCTION NIL)
(SETQ FASD-PACKAGE PACKAGE)
(SETQ FASD-TABLE-CURRENT-INDEX FASL-TABLE-WORKING-OFFSET)
(SETF (FILL-POINTER FASD-TYO-BUFFER-ARRAY) 0))
If OPTIMIZE is set , SETQ and DEFUN are handled specially ,
in a way appropriate for the top level of fasdump or qc - file .
(DEFUN FASD-FORM (FORM &OPTIONAL OPTIMIZE)
"Put something to execute FORM into the QFASL file being written.
If OPTIMIZE is true, many common types of forms are handled specially,
including SETQ, DEFF, DEFUN, etc. In particular, (DEFUN FOO)
is processed by dumping FOO's current function definition."
(COND ((OR (MEMQ FORM '(T NIL))
(STRINGP FORM)
(NUMBERP FORM))
(FASD-CONSTANT FORM))
((SYMBOLP FORM) (FASD-SYMEVAL FORM))
((ATOM FORM) (FASD-RANDOM-FORM FORM))
((NOT (SYMBOLP (CAR FORM))) (FASD-RANDOM-FORM FORM))
((EQ (CAR FORM) 'QUOTE)
(FASD-CONSTANT (CADR FORM)))
((NOT OPTIMIZE)
(FASD-RANDOM-FORM FORM))
((EQ (CAR FORM) 'SETQ)
(FASD-SETQ FORM))
((EQ (CAR FORM) 'DEFF)
(FASD-STORE-FUNCTION-CELL (CADR FORM) (FASD-FORM (CADDR FORM))))
((AND (EQ (CAR FORM) 'FSET-CAREFULLY)
(CONSP (CADR FORM))
(EQ (CAADR FORM) 'QUOTE))
(FASD-STORE-FUNCTION-CELL (CADADR FORM) (FASD-FORM (CADDR FORM))))
((EQ (CAR FORM) 'DEFUN)
(FASD-FUNCTION (CADR FORM)
(FDEFINITION (SI:UNENCAPSULATE-FUNCTION-SPEC (CADR FORM)))))
(T (FASD-RANDOM-FORM FORM))))
( DEFUN FASD - DECLARATION ( DCL )
( AND ( MEMQ ( CAR DCL ) ' ( SPECIAL UNSPECIAL )
(DEFUN FASD-RANDOM-FORM (FRM)
(FASD-EVAL1 FRM))
Given the body of a DEFUN , dump stuff to perform it .
(DEFUN FASD-FUNCTION (FUNCTION DEFINITION)
(FASD-STORE-FUNCTION-CELL FUNCTION (FASD-CONSTANT DEFINITION)))
Given the body of a SETQ , dump stuff to perform it .
(DEFUN FASD-SETQ (SETQ-FORM)
(DO ((PAIRS (CDR SETQ-FORM) (CDDR PAIRS)))
((NULL PAIRS))
(CHECK-ARG PAIRS (ATOM (CAR PAIRS)) "a SETQ form")
(FASD-STORE-VALUE-CELL (CAR PAIRS) (FASD-FORM (CADR PAIRS)))))
(DEFUN FASD-SYMEVAL (SEXP)
(FASD-START-GROUP NIL 0 FASL-OP-FETCH-SYMBOL-VALUE)
(FASD-CONSTANT SEXP)
(FASD-TABLE-NEXT-INDEX))
(DEFUN FASD-SYMBOL-VALUE (FILENAME SYMBOL &OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME containing SYMBOL's value.
Loading the file will set the symbol back to the same value."
(WITH-OPEN-FILE (FASD-STREAM (FS:MERGE-PATHNAME-DEFAULTS FILENAME
FS:LOAD-PATHNAME-DEFAULTS
':QFASL)
':DIRECTION ':OUTPUT
':CHARACTERS NIL
':BYTE-SIZE 16.)
(LOCKING-RESOURCES
(FASD-INITIALIZE)
(FASD-START-FILE)
(FASD-ATTRIBUTES-LIST
(IF (GETL (LOCF ATTRIBUTE-LIST) '(:PACKAGE))
ATTRIBUTE-LIST
(LIST* ':PACKAGE (PACKAGE-NAME (SYMBOL-PACKAGE SYMBOL)) ATTRIBUTE-LIST)))
(FASD-FORM `(SETF (SYMBOL-VALUE ',SYMBOL) ',(SYMBOL-VALUE SYMBOL)))
(FASD-END-WHACK)
(FASD-END-FILE)))))
(defun dump-forms-to-fasd-stream (fasd-stream forms-list)
"Dump forms to a fasd-stream only within a with-open-fasd-file form."
(dolist (form forms-list)
(if ( (fasd-table-length) qc-file-whack-threshold)
(fasd-end-whack))
(fasd-form form)))
(defun open-fasd-file (filename)
(open (fs:merge-pathname-defaults
filename fs:load-pathname-defaults ':qfasl)
':direction ':output
':characters nil
':byte-size 16.))
(defmacro with-open-fasd-file ((stream-variable filename &optional attribute-list) &body body)
"Open filename and bind stream-variable to a fasd-stream.
No output operations should be performed on the fasd-stream except as a side-affect of
invoking dump-forms-to-fasd-stream."
(once-only (attribute-list)
`(with-open-stream (,stream-variable (open-fasd-file ,filename))
(let ((fasd-stream ,stream-variable))
(locking-resources
(fasd-initialize)
(fasd-start-file)
(fasd-attributes-list
(if (getl (locf ,attribute-list) '(:package))
,attribute-list
(list* ':package ':user ,attribute-list)))
,@body
(fasd-end-whack)
(fasd-end-file)))))))
(DEFUN DUMP-FORMS-TO-FILE (FILENAME FORMS-LIST &OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME which, when loaded, will execute the forms in FORMS-LIST.
ATTRIBUTE-LIST is a file attribute list which controls, among other things,
what package the file is dumped and loaded in (default is USER)."
(with-open-fasd-file (stream filename attribute-list)
(dump-forms-to-fasd-stream stream forms-list)))
(DEFUN FASD-FONT (FONT-SYMBOL)
"Write the font FONT into a QFASL file named SYS: FONTS; name-of-font QFASL."
(DUMP-FORMS-TO-FILE (FS:MAKE-PATHNAME ':HOST "SYS"
':DIRECTORY "FONTS"
':NAME (SYMBOL-NAME FONT-SYMBOL))
`((proclaim (special ,font-symbol))
(SETQ ,FONT-SYMBOL ,(TV::FONT-EVALUATE FONT-SYMBOL)))
'(:PACKAGE :FONTS)))
(DEFUN FASD-FILE-SYMBOLS-PROPERTIES (FILENAME SYMBOLS PROPERTIES
DUMP-VALUES-P DUMP-FUNCTIONS-P
NEW-SYMBOL-FUNCTION
&OPTIONAL ATTRIBUTE-LIST)
"Write a QFASL file named FILENAME containing data on SYMBOLS.
The data can include the symbols' values, function definitions, and properties.
PROPERTIES is a list of which properties should be dumped.
DUMP-VALUES-P says whether to dump their values.
DUMP-FUNCTIONS-P says whether to dump their function definitions.
NEW-SYMBOL-FUNCTION is a function to call whenever a new symbol
not previously seen is found in a value being dumped. The function
can cause the new symbol's data to be dumped like the specified symbols.
When the NEW-SYMBOL-FUNCTION is called, FASD-SYMBOL-LIST will be a list
of symbols waiting to be dumped, and FASD-ALREADY-DUMPED-SYMBOL-LIST a
list of those already dumped. To make a new symbol be dumped, push it
on the former if it is not in either of those two."
(WITH-OPEN-FILE (FASD-STREAM (FS:MERGE-PATHNAME-DEFAULTS FILENAME
FS:LOAD-PATHNAME-DEFAULTS
':QFASL)
':DIRECTION ':OUTPUT
':CHARACTERS NIL
':BYTE-SIZE 16.)
(LOCKING-RESOURCES
(FASD-INITIALIZE)
(FASD-START-FILE)
(FASD-ATTRIBUTES-LIST
(IF (GETL (LOCF ATTRIBUTE-LIST) '(:PACKAGE))
ATTRIBUTE-LIST
(LIST* ':PACKAGE ':USER ATTRIBUTE-LIST)))
(FASD-SYMBOLS-PROPERTIES SYMBOLS PROPERTIES DUMP-VALUES-P
DUMP-FUNCTIONS-P NEW-SYMBOL-FUNCTION)
(FASD-END-WHACK)
(FASD-END-FILE)))))
(DEFVAR FASD-SYMBOL-LIST)
(DEFVAR FASD-ALREADY-DUMPED-SYMBOL-LIST)
(DEFVAR FASD-NEW-SYMBOL-FUNCTION)
Take each symbol in SYMBOLS and do a FASD - SYMBOL - PROPERTIES on it .
The symbols already thus dumped are put on FASD - ALREADY - DUMPED - SYMBOL - LIST .
(DEFUN FASD-SYMBOLS-PROPERTIES (SYMBOLS PROPERTIES DUMP-VALUES
DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)
(DO ((FASD-SYMBOL-LIST SYMBOLS)
(FASD-ALREADY-DUMPED-SYMBOL-LIST)
(SYMBOL))
((NULL FASD-SYMBOL-LIST))
(SETQ SYMBOL (POP FASD-SYMBOL-LIST))
(PUSH SYMBOL FASD-ALREADY-DUMPED-SYMBOL-LIST)
(FASD-SYMBOL-PROPERTIES SYMBOL PROPERTIES
DUMP-VALUES DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)))
(DEFUN FASD-SYMBOL-PROPERTIES (SYMBOL PROPERTIES DUMP-VALUES
DUMP-FUNCTIONS NEW-SYMBOL-FUNCTION)
(WHEN (AND DUMP-VALUES (BOUNDP SYMBOL))
(FASD-STORE-VALUE-CELL SYMBOL (FASD-CONSTANT-TRACING-SYMBOLS (SYMBOL-VALUE SYMBOL)
NEW-SYMBOL-FUNCTION)))
(WHEN (AND DUMP-FUNCTIONS (FBOUNDP SYMBOL))
(FASD-STORE-FUNCTION-CELL SYMBOL (FASD-CONSTANT-TRACING-SYMBOLS (SYMBOL-FUNCTION SYMBOL)
NEW-SYMBOL-FUNCTION)))
(MAPC #'(LAMBDA (PROP &AUX (TEM (GET SYMBOL PROP)))
(WHEN TEM
(FASD-START-GROUP NIL 0 FASL-OP-EVAL1)
(PROGN
(FASD-START-GROUP NIL 1 FASL-OP-LIST)
4 is length of the DEFPROP form .
(FASD-CONSTANT-TRACING-SYMBOLS TEM NEW-SYMBOL-FUNCTION)
(FASD-CONSTANT PROP)
(FASD-TABLE-NEXT-INDEX))
(FASD-TABLE-NEXT-INDEX)))
PROPERTIES))
(DEFUN FASD-CONSTANT-TRACING-SYMBOLS (OBJECT FASD-NEW-SYMBOL-FUNCTION)
(FASD-CONSTANT OBJECT))
(DEFUN FASD-SYMBOL-PUSH (SYMBOL)
(OR (MEMQ SYMBOL FASD-SYMBOL-LIST)
(MEMQ SYMBOL FASD-ALREADY-DUMPED-SYMBOL-LIST)
(PUSH SYMBOL FASD-SYMBOL-LIST)))
|
154967d8449f9b2f76d5e98d433d222606cb52511e0e594d2ce1897b8faf5cc2 | patricoferris/ocaml-multicore-monorepo | target.ml | This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
let decode string =
string
|> Dream.split_target
|> fun (path, query) -> Printf.printf "%S %S\n" path query
let%expect_test _ =
decode "";
decode "?";
decode "/";
decode "/?";
decode "/abc/def";
TODO A very questionable interpretation of // as leading a hostname when we
know this is a target . There seems to be no way to work around this using
the interface of the library .
know this is a target. There seems to be no way to work around this using
the interface of the Uri library. *)
decode "//abc/def";
decode "/abc/def/";
decode "/abc/def?";
decode "/abc/def/?";
decode "/abc?a";
decode "/abc?a=b&c=d";
decode "/abc%2F%26def?a=b&c=d%2B";
decode "/abc/#foo";
decode "/abc/?de=f#foo";
[%expect {|
"" ""
"" ""
"/" ""
"/" ""
"/abc/def" ""
"/def" ""
"/abc/def/" ""
"/abc/def" ""
"/abc/def/" ""
"/abc" "a"
"/abc" "a=b&c=d"
"/abc%2F&def" "a=b&c=d%2B"
"/abc/" ""
"/abc/" "de=f" |}]
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/test/expect/pure/formats/target/target.ml | ocaml | This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
let decode string =
string
|> Dream.split_target
|> fun (path, query) -> Printf.printf "%S %S\n" path query
let%expect_test _ =
decode "";
decode "?";
decode "/";
decode "/?";
decode "/abc/def";
TODO A very questionable interpretation of // as leading a hostname when we
know this is a target . There seems to be no way to work around this using
the interface of the library .
know this is a target. There seems to be no way to work around this using
the interface of the Uri library. *)
decode "//abc/def";
decode "/abc/def/";
decode "/abc/def?";
decode "/abc/def/?";
decode "/abc?a";
decode "/abc?a=b&c=d";
decode "/abc%2F%26def?a=b&c=d%2B";
decode "/abc/#foo";
decode "/abc/?de=f#foo";
[%expect {|
"" ""
"" ""
"/" ""
"/" ""
"/abc/def" ""
"/def" ""
"/abc/def/" ""
"/abc/def" ""
"/abc/def/" ""
"/abc" "a"
"/abc" "a=b&c=d"
"/abc%2F&def" "a=b&c=d%2B"
"/abc/" ""
"/abc/" "de=f" |}]
|
|
1f77b73ff0a28b33f20e0f89b12afcd530ad14138625dda28c71303b05f77b5d | change-metrics/monocle | Syntax.hs | | The Monocle Search Language Syntax
module Monocle.Search.Syntax (
Expr (..),
ParseError (..),
) where
import Relude
type Field = Text
type Value = Text
data Expr
= AndExpr Expr Expr
| OrExpr Expr Expr
| NotExpr Expr
Field operator
EqExpr Field Value
| GtExpr Field Value
| LtExpr Field Value
| GtEqExpr Field Value
| LtEqExpr Field Value
deriving (Show, Eq)
data ParseError = ParseError Text Int
deriving (Show, Eq)
| null | https://raw.githubusercontent.com/change-metrics/monocle/8b239d7ee0e9e30690cd82baf7e46a5fda221583/src/Monocle/Search/Syntax.hs | haskell | | The Monocle Search Language Syntax
module Monocle.Search.Syntax (
Expr (..),
ParseError (..),
) where
import Relude
type Field = Text
type Value = Text
data Expr
= AndExpr Expr Expr
| OrExpr Expr Expr
| NotExpr Expr
Field operator
EqExpr Field Value
| GtExpr Field Value
| LtExpr Field Value
| GtEqExpr Field Value
| LtEqExpr Field Value
deriving (Show, Eq)
data ParseError = ParseError Text Int
deriving (Show, Eq)
|
|
e8e88c65f86f7ccdfc753c12566cc7dc36e02172796e2691663c56de156465f3 | marigold-dev/deku | api_path.ml | open Deku_concepts
open Deku_consensus
open Deku_stdlib
module Level_or_hash = struct
type t = Level of Level.t | Hash of Block_hash.t
let parser path =
let serialize data =
match data with
| Level level -> Level.show level
| Hash hash -> Block_hash.to_b58 hash
in
let parse string =
let parse_level string =
try
string |> Z.of_string |> N.of_z |> Option.map Level.of_n
|> Option.map (fun level -> Level level)
with _ -> None
in
let parse_hash string =
string |> Block_hash.of_b58 |> Option.map (fun hash -> Hash hash)
in
match (parse_level string, parse_hash string) with
| None, None -> None
| Some level, _ -> Some level
| _, Some hash -> Some hash
in
Routes.custom ~serialize ~parse ~label:":level-or-hash" path
end
module Operation_hash = struct
open Deku_protocol
type t = Operation_hash.t
let parser path =
let serialize hash = Operation_hash.to_b58 hash in
let parse string = Operation_hash.of_b58 string in
Routes.custom ~serialize ~parse ~label:":operation-hash" path
end
module Address = struct
type t = Address
let parser path =
let open Deku_ledger in
let serialize address = Address.to_b58 address in
let parse string = Address.of_b58 string in
Routes.custom ~serialize ~parse ~label:":address" path
end
module Contract_address = struct
open Deku_ledger
type t = Contract_address.t
let parser path =
let open Deku_ledger in
let serialize address = Contract_address.to_b58 address in
let parse string = Contract_address.of_b58 string in
Routes.custom ~serialize ~parse ~label:":contract_address" path
end
module Ticketer = struct
type t = Deku_ledger.Ticket_id.ticketer
open Deku_ledger.Ticket_id
let parser path =
let serialize ticket_id =
match ticket_id with
| Tezos contract_hash -> Deku_tezos.Contract_hash.to_b58 contract_hash
| Deku contract_address ->
Deku_ledger.Contract_address.to_b58 contract_address
in
let parse ticketer =
Deku_repr.decode_variant
[
(fun x ->
Deku_tezos.Contract_hash.of_b58 x
|> Option.map (fun x -> Deku_ledger.Ticket_id.Tezos x));
(fun x ->
Deku_ledger.Contract_address.of_b58 x
|> Option.map (fun x -> Deku_ledger.Ticket_id.Deku x));
]
ticketer
in
Routes.custom ~serialize ~parse ~label:":ticketer" path
end
module Data = struct
type t = bytes
let parser path =
let serialize data = data |> Bytes.to_string |> Hex.of_string |> Hex.show in
let parse string =
let string =
match String.starts_with ~prefix:"0x" string with
| false -> string
| true -> String.sub string 2 (String.length string - 2)
in
Hex.to_string (`Hex string) |> Bytes.of_string |> Option.some
in
Routes.custom ~serialize ~parse ~label:":data" path
end
| null | https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-p/src/core/bin/api/api_path.ml | ocaml | open Deku_concepts
open Deku_consensus
open Deku_stdlib
module Level_or_hash = struct
type t = Level of Level.t | Hash of Block_hash.t
let parser path =
let serialize data =
match data with
| Level level -> Level.show level
| Hash hash -> Block_hash.to_b58 hash
in
let parse string =
let parse_level string =
try
string |> Z.of_string |> N.of_z |> Option.map Level.of_n
|> Option.map (fun level -> Level level)
with _ -> None
in
let parse_hash string =
string |> Block_hash.of_b58 |> Option.map (fun hash -> Hash hash)
in
match (parse_level string, parse_hash string) with
| None, None -> None
| Some level, _ -> Some level
| _, Some hash -> Some hash
in
Routes.custom ~serialize ~parse ~label:":level-or-hash" path
end
module Operation_hash = struct
open Deku_protocol
type t = Operation_hash.t
let parser path =
let serialize hash = Operation_hash.to_b58 hash in
let parse string = Operation_hash.of_b58 string in
Routes.custom ~serialize ~parse ~label:":operation-hash" path
end
module Address = struct
type t = Address
let parser path =
let open Deku_ledger in
let serialize address = Address.to_b58 address in
let parse string = Address.of_b58 string in
Routes.custom ~serialize ~parse ~label:":address" path
end
module Contract_address = struct
open Deku_ledger
type t = Contract_address.t
let parser path =
let open Deku_ledger in
let serialize address = Contract_address.to_b58 address in
let parse string = Contract_address.of_b58 string in
Routes.custom ~serialize ~parse ~label:":contract_address" path
end
module Ticketer = struct
type t = Deku_ledger.Ticket_id.ticketer
open Deku_ledger.Ticket_id
let parser path =
let serialize ticket_id =
match ticket_id with
| Tezos contract_hash -> Deku_tezos.Contract_hash.to_b58 contract_hash
| Deku contract_address ->
Deku_ledger.Contract_address.to_b58 contract_address
in
let parse ticketer =
Deku_repr.decode_variant
[
(fun x ->
Deku_tezos.Contract_hash.of_b58 x
|> Option.map (fun x -> Deku_ledger.Ticket_id.Tezos x));
(fun x ->
Deku_ledger.Contract_address.of_b58 x
|> Option.map (fun x -> Deku_ledger.Ticket_id.Deku x));
]
ticketer
in
Routes.custom ~serialize ~parse ~label:":ticketer" path
end
module Data = struct
type t = bytes
let parser path =
let serialize data = data |> Bytes.to_string |> Hex.of_string |> Hex.show in
let parse string =
let string =
match String.starts_with ~prefix:"0x" string with
| false -> string
| true -> String.sub string 2 (String.length string - 2)
in
Hex.to_string (`Hex string) |> Bytes.of_string |> Option.some
in
Routes.custom ~serialize ~parse ~label:":data" path
end
|
|
b04b883f256aa1d723bb405b64f5e82ebf568f1d9db6d48b3721aa9be2d2881b | LdBeth/keim | term-mixin.lisp | -*- syntax : common - lisp ; package : keim ; base : 10 ; mode : lisp -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;; ;;
Copyright ( C ) 1993 by AG Siekmann , , ; ;
Universitaet des Saarlandes , Saarbruecken , Germany . ; ;
;; All rights reserved. ;;
;; For information about this program, write to: ;;
;; KEIM Project ;;
AG Siekmann / FB Informatik ; ;
Universitaet des Saarlandes ; ;
1150 ; ;
; ;
Germany ; ;
;; electronic mail: ;;
;; ;;
;; The author makes no representations about the suitability of this ;;
software for any purpose . It is provided " AS IS " without express or ; ;
;; implied warranty. In particular, it must be understood that this ;;
;; software is an experimental version, and is not suitable for use in ;;
;; any safety-critical application, and the author denies a license for ;;
;; such use. ;;
;; ;;
;; You may use, copy, modify and distribute this software for any ;;
;; noncommercial and non-safety-critical purpose. Use of this software ;;
;; in a commercial product is not included under this license. You must ;;
;; maintain this copyright statement in all copies of this software that ;;
;; you modify or distribute. ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
(in-package :keim)
(mod~defmod termix :uses (env keim mod post term )
:documentation "Using terms in larger structures"
:exports (
termix+mixin
termix~set-term!
termix~term
termix+named-term
termix~named-term-p
termix~read-named-term
termix~named-term-abbrev
)
)
#{
\section{Term mixins}\label{mod:termix}
Often we would like to have objects which behave as terms, but also
have other properties (such as names). Here TERMIX+MIXIN is a new
KEIM+OBJECT
that contains a slot TERM, where a term can be placed.
#}
; rename term+mixin -> termix+mixin
(eval-when (load compile eval)
(defclass termix+mixin (term+top keim+object)
((term :initform nil :initarg :term :reader termix=term
:writer termix=write-term!))
(:documentation "An object which contains a term as a slot.")
)
)
(term~warning-rename-fn term~set-mixin-term! termix~set-term!)
(defgeneric termix~set-term! (term newval)
(declare
(authors nesmith)
(input "A term-mixin object and a new term.")
(effect "Sets the TERM slot of the term-mixin to the new term.")
(value "the new term")
(example "Let mixin1 is an object of class termix+mixin"
"(termix~set-term! mixin1 (QQ Y Y)) --> (QQ Y Y)"
"(termix~term mixin1) --> (QQ Y Y)"))
(:method ((term termix+mixin) (newval term+term))
(termix=write-term! newval term)))
(term~warning-rename-fn term~mixin-term termix~term)
(defun termix~term (term)
(declare
(authors nesmith)
(input "A term-mixin object.")
(effect "none")
(value "the value of the TERM slot."))
(termix=term term))
(defmethod term~reader ((term termix+mixin))
(termix~term term))
(defmethod print-object ((thing termix+mixin) stream)
(print-object (termix~term thing) stream))
#{
\section{Named terms}
Here we define TERMIX+NAMED-TERM. Instances of this class will
contain a name slot as well as a term slot, so we can associate
names with terms.
#}
; rename term+named-term -> termix+named-term
(eval-when (load compile eval)
(defclass termix+named-term (termix+mixin keim+name)
()
(:documentation "This is the superclass to all terms in KEIM that have a name")))
(term~warning-rename-fn term~named-term-p termix~named-term-p)
(defun termix~named-term-p (thing)
(declare
(authors nesmith)
(input "An object")
(effect "none")
(value "T if the object is a named-term, otherwise nil."))
(typep thing 'termix+named-term))
(defmethod print-object :around ((named-term termix+named-term) stream)
(format stream "(~A ~S " (termix~named-term-abbrev named-term)
(keim~name named-term))
(call-next-method)
(format stream ")"))
(term~warning-rename-fn term~read-named-term termix~read-named-term)
(defun termix~read-named-term (symbol env)
(declare
(authors nesmith)
(input "A symbol and a environment")
(effect "none")
(value "If the symbol is associated with a named-term in the environment,
returns the named-term."))
(let ((obj (env~lookup-object symbol env)))
(unless (termix~named-term-p obj)
(post~error "~A is not a named term in environment." symbol))
obj))
(term~warning-rename-fn term~named-term-abbrev termix~named-term-abbrev)
(defgeneric termix~named-term-abbrev (named-term)
(declare
(authors nesmith)
(input "A named-term")
(effect "none")
(value "A short string identifying the specific type of the named-term
(used in printing)."))
(:method ((thing termix+named-term))
"namedterm")
(:documentation "A string abbreviation for this type of named of term. Used in printing."))
(defmethod env~post-print (key (term termix+named-term) stream)
(declare (ignore key))
(post~print term stream)
(values))
| null | https://raw.githubusercontent.com/LdBeth/keim/ed2665d3b0d9a78eaa88b5a2940a4541f0750926/keim/prog/term/term-mixin.lisp | lisp | package : keim ; base : 10 ; mode : lisp -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;;
;
;
All rights reserved. ;;
For information about this program, write to: ;;
KEIM Project ;;
;
;
;
;
;
electronic mail: ;;
;;
The author makes no representations about the suitability of this ;;
;
implied warranty. In particular, it must be understood that this ;;
software is an experimental version, and is not suitable for use in ;;
any safety-critical application, and the author denies a license for ;;
such use. ;;
;;
You may use, copy, modify and distribute this software for any ;;
noncommercial and non-safety-critical purpose. Use of this software ;;
in a commercial product is not included under this license. You must ;;
maintain this copyright statement in all copies of this software that ;;
you modify or distribute. ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
rename term+mixin -> termix+mixin
rename term+named-term -> termix+named-term |
(in-package :keim)
(mod~defmod termix :uses (env keim mod post term )
:documentation "Using terms in larger structures"
:exports (
termix+mixin
termix~set-term!
termix~term
termix+named-term
termix~named-term-p
termix~read-named-term
termix~named-term-abbrev
)
)
#{
\section{Term mixins}\label{mod:termix}
Often we would like to have objects which behave as terms, but also
have other properties (such as names). Here TERMIX+MIXIN is a new
KEIM+OBJECT
that contains a slot TERM, where a term can be placed.
#}
(eval-when (load compile eval)
(defclass termix+mixin (term+top keim+object)
((term :initform nil :initarg :term :reader termix=term
:writer termix=write-term!))
(:documentation "An object which contains a term as a slot.")
)
)
(term~warning-rename-fn term~set-mixin-term! termix~set-term!)
(defgeneric termix~set-term! (term newval)
(declare
(authors nesmith)
(input "A term-mixin object and a new term.")
(effect "Sets the TERM slot of the term-mixin to the new term.")
(value "the new term")
(example "Let mixin1 is an object of class termix+mixin"
"(termix~set-term! mixin1 (QQ Y Y)) --> (QQ Y Y)"
"(termix~term mixin1) --> (QQ Y Y)"))
(:method ((term termix+mixin) (newval term+term))
(termix=write-term! newval term)))
(term~warning-rename-fn term~mixin-term termix~term)
(defun termix~term (term)
(declare
(authors nesmith)
(input "A term-mixin object.")
(effect "none")
(value "the value of the TERM slot."))
(termix=term term))
(defmethod term~reader ((term termix+mixin))
(termix~term term))
(defmethod print-object ((thing termix+mixin) stream)
(print-object (termix~term thing) stream))
#{
\section{Named terms}
Here we define TERMIX+NAMED-TERM. Instances of this class will
contain a name slot as well as a term slot, so we can associate
names with terms.
#}
(eval-when (load compile eval)
(defclass termix+named-term (termix+mixin keim+name)
()
(:documentation "This is the superclass to all terms in KEIM that have a name")))
(term~warning-rename-fn term~named-term-p termix~named-term-p)
(defun termix~named-term-p (thing)
(declare
(authors nesmith)
(input "An object")
(effect "none")
(value "T if the object is a named-term, otherwise nil."))
(typep thing 'termix+named-term))
(defmethod print-object :around ((named-term termix+named-term) stream)
(format stream "(~A ~S " (termix~named-term-abbrev named-term)
(keim~name named-term))
(call-next-method)
(format stream ")"))
(term~warning-rename-fn term~read-named-term termix~read-named-term)
(defun termix~read-named-term (symbol env)
(declare
(authors nesmith)
(input "A symbol and a environment")
(effect "none")
(value "If the symbol is associated with a named-term in the environment,
returns the named-term."))
(let ((obj (env~lookup-object symbol env)))
(unless (termix~named-term-p obj)
(post~error "~A is not a named term in environment." symbol))
obj))
(term~warning-rename-fn term~named-term-abbrev termix~named-term-abbrev)
(defgeneric termix~named-term-abbrev (named-term)
(declare
(authors nesmith)
(input "A named-term")
(effect "none")
(value "A short string identifying the specific type of the named-term
(used in printing)."))
(:method ((thing termix+named-term))
"namedterm")
(:documentation "A string abbreviation for this type of named of term. Used in printing."))
(defmethod env~post-print (key (term termix+named-term) stream)
(declare (ignore key))
(post~print term stream)
(values))
|
23d7fe5a4bc603dc6c958d1c782e7c18fc3a41c865bb58ddaad1a36a49566d19 | GillianPlatform/Gillian | wParserAndCompiler.mli | include
Gillian.CommandLine.ParserAndCompiler.S
with type tl_ast = WProg.t
and type init_data = unit
and module Annot = WAnnot
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/064097945f7d70264be49bb0d54369646269de96/wisl/lib/ParserAndCompiler/wParserAndCompiler.mli | ocaml | include
Gillian.CommandLine.ParserAndCompiler.S
with type tl_ast = WProg.t
and type init_data = unit
and module Annot = WAnnot
|
|
59d95fe22bc5d085c941c8730a562dfd4bc0e6cc9e618fd39ec2214d3ed5cd1b | futurice/haskell-mega-repo | SqlBuilder.hs | {-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE RankNTypes #-}
-- | This small library helps with building complex queries:
--
-- >>> :{
-- demo $ do
< - from _ " table1 "
-- fields_ tbl [ "c1", "c2"]
orderby _ " c2 " ASC
orderby _ " c1 " DESC
where _ [ eparam _ ( -100 : : Int ) , " < " , ecolumn _ " c3 " ]
where _ [ ecolumn _ " c3 " , " < " , eparam _ ( 100 : : Int ) ]
where _ [ ecolumn _ " c4 " , " = " , eparam _ ( " foo " : : String ) ]
limit _ 10
-- :}
-- SELECT t.c1, t.c2
-- FROM sch.table1 t
-- WHERE (? < t.c3) AND (t.c3 < ?) AND (t.c4 = ?)
-- ORDER BY t.c2 ASC, t.c1 DESC
LIMIT 10
-- ---
Plain " -100 "
Plain " 100 "
-- Escape "foo"
--
module Futurice.Postgres.SqlBuilder (
-- * Running queries
poolQueryM,
safePoolQueryM,
-- * DSL
-- ** Methods
from_,
fromSubselect_,
fields_,
orderby_,
where_,
limit_,
-- ** Expressions
Expr,
ecolumn_,
eparam_,
-- ** Types
QueryM,
TableName,
TableAbbr,
ColumnName,
SortDirection (..),
-- * Debug
renderQuery,
) where
import Control.Monad (ap)
import Data.Char (isAlphaNum)
import Data.Semigroup.Generic (gmappend, gmempty)
import Data.Monoid (Last (..))
import Futurice.Postgres
import Futurice.Prelude
import Prelude ()
import qualified Data.Set as Set
import qualified Database.PostgreSQL.Simple as PQ
import qualified Database.PostgreSQL.Simple.ToField as PQ
import qualified Text.PrettyPrint.Compact as PP
-------------------------------------------------------------------------------
-- Running
-------------------------------------------------------------------------------
poolQueryM
:: (PQ.FromRow r, HasPostgresPool ctx, MonadBaseControl IO m)
=> ctx -> String -> QueryM () -> m [r]
poolQueryM ctx schema q = poolQuery ctx (fromString query) row
where
(query, row) = renderQuery schema q
safePoolQueryM
:: (PQ.FromRow r, HasPostgresPool ctx, MonadBaseControl IO m, MonadLog m, MonadCatch m)
=> ctx -> String -> QueryM () -> m [r]
safePoolQueryM ctx schema q = safePoolQuery ctx (fromString query) row
where
(query, row) = renderQuery schema q
-------------------------------------------------------------------------------
-- Newtypes
-------------------------------------------------------------------------------
newtype TableName = TN String deriving (Show, IsString)
newtype ColumnName = CN String deriving (Show, IsString)
-- | Table abbreviation.
--
-- Returned by 'from_'
newtype TableAbbr = TableAbbr String
deriving (Eq, Ord, Show)
-------------------------------------------------------------------------------
-- Query
-------------------------------------------------------------------------------
data SortDirection = ASC | DESC
deriving (Show)
data SelectQuery = SelectQuery
{ sqTables :: [(Either SelectQuery TableName, TableAbbr)]
, sqFields :: [(TableAbbr, ColumnName)]
, sqOrderBy :: [(TableAbbr, ColumnName, SortDirection)]
, sqWhere :: [Expr]
, sqLimit :: Last Int
}
deriving (Show, Generic)
instance Semigroup SelectQuery where
(<>) = gmappend
instance Monoid SelectQuery where
mempty = gmempty
mappend = (<>)
-------------------------------------------------------------------------------
-- Query Monad
-------------------------------------------------------------------------------
-- | Query building monad.
newtype QueryM a = QueryM { unQueryM :: St -> (SelectQuery, St, a) }
deriving (Functor)
instance Applicative QueryM where
pure = return
(<*>) = ap
instance Monad QueryM where
return x = QueryM $ \s -> (mempty, s, x)
m >>= k = QueryM $ \st0 ->
let (sq1, st1, x) = unQueryM m st0
(sq2, st2, y) = unQueryM (k x) st1
in (sq1 <> sq2, st2, y)
-- | State of 'QueryM'.
newtype St = St
{ stAbbrs :: Set TableAbbr
}
emptyS :: St
emptyS = St
{ stAbbrs = mempty
}
-------------------------------------------------------------------------------
-- DSL
-------------------------------------------------------------------------------
-- | @FROM table1@
--
-- >>> demo $ from_ "table1"
-- SELECT 1 FROM sch.table1 t
--
-- >>> demo $ from_ "table-with-dash" >>= \tbl -> fields_ tbl [ "c1", "c2" ]
SELECT t.c1 , t.c2 FROM sch . "table - with - dash " t
--
from_ :: TableName -> QueryM TableAbbr
from_ (TN tbl) = QueryM $ \(St tbls) ->
let abbr = takeAbbr $ filter (\a -> Set.notMember a tbls) abbrs
in (mempty { sqTables = [ (Right (TN tbl), abbr) ] } , St $ Set.insert abbr tbls, abbr)
where
abbrs = case tbl of
[] -> [ TableAbbr $ "tmp" ++ show i | i <- [ 0 :: Int .. ] ]
(c:_) -> TableAbbr [c] : [ TableAbbr $ c : show i | i <- [ 1 :: Int .. ] ]
takeAbbr [] = TableAbbr "panic" -- should not happen
takeAbbr (abbr : _) = abbr
-- | @FROM (SELECT ...)@
--
-- >>> let q = from_ "table1" >>= \tbl -> fields_ tbl [ "col1", "col2" ]
-- >>> demo $ fromSubselect_ q >>= \tbl -> fields_ tbl [ "col1" ]
-- SELECT sub0.col1 FROM (SELECT t.col1, t.col2 FROM sch.table1 t) sub0
--
fromSubselect_ :: QueryM () -> QueryM TableAbbr
fromSubselect_ subQ = QueryM $ \st0 ->
let (q, St tbls, ()) = unQueryM subQ st0
abbr = takeAbbr $ filter (\a -> Set.notMember a tbls) abbrs
in (mempty { sqTables = [(Left q, abbr)] }, St $ Set.insert abbr tbls, abbr)
where
abbrs = [ TableAbbr $ "sub" ++ show i | i <- [ 0 :: Int .. ] ]
takeAbbr [] = TableAbbr "panic" -- should not happen
takeAbbr (abbr : _) = abbr
| @SELECT col1 , col2@
--
-- >>> demo $ from_ "table1" >>= \tbl -> fields_ tbl [ "col1", "col2" ]
-- SELECT t.col1, t.col2 FROM sch.table1 t
--
fields_ :: TableAbbr -> [ColumnName] -> QueryM ()
fields_ tbl cls = QueryM $ \st ->
(mempty { sqFields = [ (tbl, cl) | cl <- cls ] }, st, ())
-- | @ORDER BY tbl.clmn ASC@
--
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " col1 " , " col2 " ] > > orderby _ " col1 " ASC
-- SELECT t.col1, t.col2 FROM sch.table1 t ORDER BY t.col1 ASC
--
orderby_ :: TableAbbr -> ColumnName -> SortDirection -> QueryM ()
orderby_ tbl cl sd = QueryM $ \st ->
(mempty { sqOrderBy = [ (tbl, cl, sd) ] }, st, ())
-- | @WHERE tbl.clmn = ?@
--
-- Where clauses referencing single column.
--
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " c1 " , " c2 " ] > > where _ [ ecolumn _ " c3 " , " < 42 " ]
SELECT t.c1 , t.c2 FROM sch.table1 t WHERE ( t.c3 < 42 )
--
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " c1 " , " c2 " ] > > let c3 = ecolumn _ " c3 " in where _ [ eparam _ ( -100 : : Int ) , " < " , , " AND " , , " < " , eparam _ ( 100 : : Int ) ]
SELECT t.c1 , t.c2 FROM sch.table1 t WHERE ( ? < t.c3 AND t.c3 < ? )
-- ---
Plain " -100 "
Plain " 100 "
--
where_
:: [Expr]
-> QueryM ()
where_ expr = QueryM $ \st ->
(mempty { sqWhere = [ mconcat expr ] }, st, ())
limit_ :: Int -> QueryM ()
limit_ l = QueryM $ \st ->
(mempty { sqLimit = Last (Just l) }, st, ())
-------------------------------------------------------------------------------
Expression
-------------------------------------------------------------------------------
-- | SQL "Expressions".
--
-- Possible future developments: make a GADT?
newtype Expr = Expr [ExprPiece]
deriving (Show, Semigroup, Monoid)
ecolumn_ :: TableAbbr -> ColumnName -> Expr
ecolumn_ tbl cl = Expr $ pure $ EPColumn tbl cl
eparam_ :: PQ.ToField f => f -> Expr
eparam_ = Expr . pure . EPAction . PQ.toField
inquery : : TableAbbr - > ColumnName -
-- inquery tbl cl q
instance IsString Expr where
fromString = Expr . pure . EPString
data ExprPiece
= EPColumn TableAbbr ColumnName
| EPAction PQ.Action
| EPString String
deriving Show
-------------------------------------------------------------------------------
-- Escaping table column names
-------------------------------------------------------------------------------
escapeTableColumn :: TableAbbr -> ColumnName -> String
escapeTableColumn (TableAbbr tn) (CN cn) =
escapeSymbol tn ++ "." ++ escapeSymbol cn
ppTableColumn :: TableAbbr -> ColumnName -> PP.Doc ()
ppTableColumn tbl cl = PP.text (escapeTableColumn tbl cl)
escapeSymbol :: String -> String
escapeSymbol str
| all isAlphaNum str = str
| otherwise = "\"" ++ str ++ "\""
-------------------------------------------------------------------------------
-- Rendering
-------------------------------------------------------------------------------
-- | Render query into template and pieces.
renderQuery
:: String -- ^ schema
-> QueryM () -- ^ query builder
-> (String, [PQ.Action]) -- ^ query template and actions (from @postgresql-simple@)
renderQuery sch (QueryM f) = case f emptyS of
(sq, _st, ()) -> (PP.render $ ppQuery sch sq, queryActions sq)
ppQuery :: String -> SelectQuery -> PP.Doc ()
ppQuery schema sq = PP.sep $
[ PP.hang 4 (PP.text "SELECT") $ ppFields $ sqFields sq
] ++ catMaybes
[ if null (sqTables sq)
then Nothing
else Just $ PP.hang 4 (PP.text "FROM") $ ppTables $ sqTables sq
, if null (sqWhere sq)
then Nothing
else Just $ PP.hang 4 (PP.text "WHERE") $ ppWhere $ sqWhere sq
, if null (sqOrderBy sq)
then Nothing
else Just $ PP.hang 4 (PP.text "ORDER BY") $ ppOrderBy $ sqOrderBy sq
, getLast (sqLimit sq) <&> \limit ->
PP.text "LIMIT" PP.<+> PP.int limit
]
where
ppFields :: [(TableAbbr, ColumnName)] -> PP.Doc ()
ppFields [] = PP.text "1"
ppFields xs = PP.sep $ PP.punctuate PP.comma
[ ppTableColumn tbl cl
| (tbl, cl) <- xs
]
ppTables :: [(Either SelectQuery TableName, TableAbbr)] -> PP.Doc ()
ppTables xs = PP.sep $ PP.punctuate PP.comma
[ ppTable tblOrQuery PP.<+> PP.text abbr
| (tblOrQuery, TableAbbr abbr) <- xs
]
where
ppTable :: Either SelectQuery TableName -> PP.Doc ()
ppTable (Right (TN tbl)) = PP.text (escapeSymbol schema ++ "." ++ escapeSymbol tbl)
ppTable (Left sq') = PP.parens (ppQuery schema sq')
ppOrderBy :: [(TableAbbr, ColumnName, SortDirection)] -> PP.Doc ()
ppOrderBy xs = PP.sep $ PP.punctuate PP.comma
[ ppTableColumn tbl cl PP.<+> PP.text (show sd)
| (tbl, cl, sd) <- xs
]
ppWhere :: [Expr] -> PP.Doc ()
ppWhere xs = PP.sep $ PP.punctuate (PP.text " AND")
[ PP.parens $ PP.hcat $ map ppExprPiece pieces
| Expr pieces <- xs
]
ppExprPiece :: ExprPiece -> PP.Doc ()
ppExprPiece (EPAction _) = PP.char '?'
ppExprPiece (EPString str) = PP.text str
ppExprPiece (EPColumn tbl cl) = ppTableColumn tbl cl
-- | Note: be careful to produce actions in the same order as in 'ppQuery'.
queryActions :: SelectQuery -> [PQ.Action]
queryActions sq = mconcat
[ concatMap whereAction (sqWhere sq)
]
where
whereAction (Expr pieces) = mapMaybe pieceAction pieces
pieceAction (EPAction act) = Just act
pieceAction _ = Nothing
-------------------------------------------------------------------------------
-- ...
-------------------------------------------------------------------------------
-- $setup
--
-- >>> :set -XOverloadedStrings -Wno-type-defaults
> > > let demo q = let ( str , acts ) = renderQuery " sch " ( void q ) in putStrLn str > > unless ( null acts ) ( putStrLn " --- " ) > > traverse _ print acts
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/futurice-postgres/src/Futurice/Postgres/SqlBuilder.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE RankNTypes #
| This small library helps with building complex queries:
>>> :{
demo $ do
fields_ tbl [ "c1", "c2"]
:}
SELECT t.c1, t.c2
FROM sch.table1 t
WHERE (? < t.c3) AND (t.c3 < ?) AND (t.c4 = ?)
ORDER BY t.c2 ASC, t.c1 DESC
---
Escape "foo"
* Running queries
* DSL
** Methods
** Expressions
** Types
* Debug
-----------------------------------------------------------------------------
Running
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Newtypes
-----------------------------------------------------------------------------
| Table abbreviation.
Returned by 'from_'
-----------------------------------------------------------------------------
Query
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Query Monad
-----------------------------------------------------------------------------
| Query building monad.
| State of 'QueryM'.
-----------------------------------------------------------------------------
DSL
-----------------------------------------------------------------------------
| @FROM table1@
>>> demo $ from_ "table1"
SELECT 1 FROM sch.table1 t
>>> demo $ from_ "table-with-dash" >>= \tbl -> fields_ tbl [ "c1", "c2" ]
should not happen
| @FROM (SELECT ...)@
>>> let q = from_ "table1" >>= \tbl -> fields_ tbl [ "col1", "col2" ]
>>> demo $ fromSubselect_ q >>= \tbl -> fields_ tbl [ "col1" ]
SELECT sub0.col1 FROM (SELECT t.col1, t.col2 FROM sch.table1 t) sub0
should not happen
>>> demo $ from_ "table1" >>= \tbl -> fields_ tbl [ "col1", "col2" ]
SELECT t.col1, t.col2 FROM sch.table1 t
| @ORDER BY tbl.clmn ASC@
SELECT t.col1, t.col2 FROM sch.table1 t ORDER BY t.col1 ASC
| @WHERE tbl.clmn = ?@
Where clauses referencing single column.
---
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| SQL "Expressions".
Possible future developments: make a GADT?
inquery tbl cl q
-----------------------------------------------------------------------------
Escaping table column names
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Rendering
-----------------------------------------------------------------------------
| Render query into template and pieces.
^ schema
^ query builder
^ query template and actions (from @postgresql-simple@)
| Note: be careful to produce actions in the same order as in 'ppQuery'.
-----------------------------------------------------------------------------
...
-----------------------------------------------------------------------------
$setup
>>> :set -XOverloadedStrings -Wno-type-defaults | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
< - from _ " table1 "
orderby _ " c2 " ASC
orderby _ " c1 " DESC
where _ [ eparam _ ( -100 : : Int ) , " < " , ecolumn _ " c3 " ]
where _ [ ecolumn _ " c3 " , " < " , eparam _ ( 100 : : Int ) ]
where _ [ ecolumn _ " c4 " , " = " , eparam _ ( " foo " : : String ) ]
limit _ 10
LIMIT 10
Plain " -100 "
Plain " 100 "
module Futurice.Postgres.SqlBuilder (
poolQueryM,
safePoolQueryM,
from_,
fromSubselect_,
fields_,
orderby_,
where_,
limit_,
Expr,
ecolumn_,
eparam_,
QueryM,
TableName,
TableAbbr,
ColumnName,
SortDirection (..),
renderQuery,
) where
import Control.Monad (ap)
import Data.Char (isAlphaNum)
import Data.Semigroup.Generic (gmappend, gmempty)
import Data.Monoid (Last (..))
import Futurice.Postgres
import Futurice.Prelude
import Prelude ()
import qualified Data.Set as Set
import qualified Database.PostgreSQL.Simple as PQ
import qualified Database.PostgreSQL.Simple.ToField as PQ
import qualified Text.PrettyPrint.Compact as PP
poolQueryM
:: (PQ.FromRow r, HasPostgresPool ctx, MonadBaseControl IO m)
=> ctx -> String -> QueryM () -> m [r]
poolQueryM ctx schema q = poolQuery ctx (fromString query) row
where
(query, row) = renderQuery schema q
safePoolQueryM
:: (PQ.FromRow r, HasPostgresPool ctx, MonadBaseControl IO m, MonadLog m, MonadCatch m)
=> ctx -> String -> QueryM () -> m [r]
safePoolQueryM ctx schema q = safePoolQuery ctx (fromString query) row
where
(query, row) = renderQuery schema q
newtype TableName = TN String deriving (Show, IsString)
newtype ColumnName = CN String deriving (Show, IsString)
newtype TableAbbr = TableAbbr String
deriving (Eq, Ord, Show)
data SortDirection = ASC | DESC
deriving (Show)
data SelectQuery = SelectQuery
{ sqTables :: [(Either SelectQuery TableName, TableAbbr)]
, sqFields :: [(TableAbbr, ColumnName)]
, sqOrderBy :: [(TableAbbr, ColumnName, SortDirection)]
, sqWhere :: [Expr]
, sqLimit :: Last Int
}
deriving (Show, Generic)
instance Semigroup SelectQuery where
(<>) = gmappend
instance Monoid SelectQuery where
mempty = gmempty
mappend = (<>)
newtype QueryM a = QueryM { unQueryM :: St -> (SelectQuery, St, a) }
deriving (Functor)
instance Applicative QueryM where
pure = return
(<*>) = ap
instance Monad QueryM where
return x = QueryM $ \s -> (mempty, s, x)
m >>= k = QueryM $ \st0 ->
let (sq1, st1, x) = unQueryM m st0
(sq2, st2, y) = unQueryM (k x) st1
in (sq1 <> sq2, st2, y)
newtype St = St
{ stAbbrs :: Set TableAbbr
}
emptyS :: St
emptyS = St
{ stAbbrs = mempty
}
SELECT t.c1 , t.c2 FROM sch . "table - with - dash " t
from_ :: TableName -> QueryM TableAbbr
from_ (TN tbl) = QueryM $ \(St tbls) ->
let abbr = takeAbbr $ filter (\a -> Set.notMember a tbls) abbrs
in (mempty { sqTables = [ (Right (TN tbl), abbr) ] } , St $ Set.insert abbr tbls, abbr)
where
abbrs = case tbl of
[] -> [ TableAbbr $ "tmp" ++ show i | i <- [ 0 :: Int .. ] ]
(c:_) -> TableAbbr [c] : [ TableAbbr $ c : show i | i <- [ 1 :: Int .. ] ]
takeAbbr (abbr : _) = abbr
fromSubselect_ :: QueryM () -> QueryM TableAbbr
fromSubselect_ subQ = QueryM $ \st0 ->
let (q, St tbls, ()) = unQueryM subQ st0
abbr = takeAbbr $ filter (\a -> Set.notMember a tbls) abbrs
in (mempty { sqTables = [(Left q, abbr)] }, St $ Set.insert abbr tbls, abbr)
where
abbrs = [ TableAbbr $ "sub" ++ show i | i <- [ 0 :: Int .. ] ]
takeAbbr (abbr : _) = abbr
| @SELECT col1 , col2@
fields_ :: TableAbbr -> [ColumnName] -> QueryM ()
fields_ tbl cls = QueryM $ \st ->
(mempty { sqFields = [ (tbl, cl) | cl <- cls ] }, st, ())
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " col1 " , " col2 " ] > > orderby _ " col1 " ASC
orderby_ :: TableAbbr -> ColumnName -> SortDirection -> QueryM ()
orderby_ tbl cl sd = QueryM $ \st ->
(mempty { sqOrderBy = [ (tbl, cl, sd) ] }, st, ())
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " c1 " , " c2 " ] > > where _ [ ecolumn _ " c3 " , " < 42 " ]
SELECT t.c1 , t.c2 FROM sch.table1 t WHERE ( t.c3 < 42 )
> > > demo $ from _ " table1 " > > = \tbl - > fields _ tbl [ " c1 " , " c2 " ] > > let c3 = ecolumn _ " c3 " in where _ [ eparam _ ( -100 : : Int ) , " < " , , " AND " , , " < " , eparam _ ( 100 : : Int ) ]
SELECT t.c1 , t.c2 FROM sch.table1 t WHERE ( ? < t.c3 AND t.c3 < ? )
Plain " -100 "
Plain " 100 "
where_
:: [Expr]
-> QueryM ()
where_ expr = QueryM $ \st ->
(mempty { sqWhere = [ mconcat expr ] }, st, ())
limit_ :: Int -> QueryM ()
limit_ l = QueryM $ \st ->
(mempty { sqLimit = Last (Just l) }, st, ())
Expression
newtype Expr = Expr [ExprPiece]
deriving (Show, Semigroup, Monoid)
ecolumn_ :: TableAbbr -> ColumnName -> Expr
ecolumn_ tbl cl = Expr $ pure $ EPColumn tbl cl
eparam_ :: PQ.ToField f => f -> Expr
eparam_ = Expr . pure . EPAction . PQ.toField
inquery : : TableAbbr - > ColumnName -
instance IsString Expr where
fromString = Expr . pure . EPString
data ExprPiece
= EPColumn TableAbbr ColumnName
| EPAction PQ.Action
| EPString String
deriving Show
escapeTableColumn :: TableAbbr -> ColumnName -> String
escapeTableColumn (TableAbbr tn) (CN cn) =
escapeSymbol tn ++ "." ++ escapeSymbol cn
ppTableColumn :: TableAbbr -> ColumnName -> PP.Doc ()
ppTableColumn tbl cl = PP.text (escapeTableColumn tbl cl)
escapeSymbol :: String -> String
escapeSymbol str
| all isAlphaNum str = str
| otherwise = "\"" ++ str ++ "\""
renderQuery
renderQuery sch (QueryM f) = case f emptyS of
(sq, _st, ()) -> (PP.render $ ppQuery sch sq, queryActions sq)
ppQuery :: String -> SelectQuery -> PP.Doc ()
ppQuery schema sq = PP.sep $
[ PP.hang 4 (PP.text "SELECT") $ ppFields $ sqFields sq
] ++ catMaybes
[ if null (sqTables sq)
then Nothing
else Just $ PP.hang 4 (PP.text "FROM") $ ppTables $ sqTables sq
, if null (sqWhere sq)
then Nothing
else Just $ PP.hang 4 (PP.text "WHERE") $ ppWhere $ sqWhere sq
, if null (sqOrderBy sq)
then Nothing
else Just $ PP.hang 4 (PP.text "ORDER BY") $ ppOrderBy $ sqOrderBy sq
, getLast (sqLimit sq) <&> \limit ->
PP.text "LIMIT" PP.<+> PP.int limit
]
where
ppFields :: [(TableAbbr, ColumnName)] -> PP.Doc ()
ppFields [] = PP.text "1"
ppFields xs = PP.sep $ PP.punctuate PP.comma
[ ppTableColumn tbl cl
| (tbl, cl) <- xs
]
ppTables :: [(Either SelectQuery TableName, TableAbbr)] -> PP.Doc ()
ppTables xs = PP.sep $ PP.punctuate PP.comma
[ ppTable tblOrQuery PP.<+> PP.text abbr
| (tblOrQuery, TableAbbr abbr) <- xs
]
where
ppTable :: Either SelectQuery TableName -> PP.Doc ()
ppTable (Right (TN tbl)) = PP.text (escapeSymbol schema ++ "." ++ escapeSymbol tbl)
ppTable (Left sq') = PP.parens (ppQuery schema sq')
ppOrderBy :: [(TableAbbr, ColumnName, SortDirection)] -> PP.Doc ()
ppOrderBy xs = PP.sep $ PP.punctuate PP.comma
[ ppTableColumn tbl cl PP.<+> PP.text (show sd)
| (tbl, cl, sd) <- xs
]
ppWhere :: [Expr] -> PP.Doc ()
ppWhere xs = PP.sep $ PP.punctuate (PP.text " AND")
[ PP.parens $ PP.hcat $ map ppExprPiece pieces
| Expr pieces <- xs
]
ppExprPiece :: ExprPiece -> PP.Doc ()
ppExprPiece (EPAction _) = PP.char '?'
ppExprPiece (EPString str) = PP.text str
ppExprPiece (EPColumn tbl cl) = ppTableColumn tbl cl
queryActions :: SelectQuery -> [PQ.Action]
queryActions sq = mconcat
[ concatMap whereAction (sqWhere sq)
]
where
whereAction (Expr pieces) = mapMaybe pieceAction pieces
pieceAction (EPAction act) = Just act
pieceAction _ = Nothing
> > > let demo q = let ( str , acts ) = renderQuery " sch " ( void q ) in putStrLn str > > unless ( null acts ) ( putStrLn " --- " ) > > traverse _ print acts
|
98203e4555d8e74d8f69759c988a0761be5e2dc9aa57b526a7d20ce5ee9509a9 | lumberdev/auth0-clojure | requests.clj | (ns auth0-clojure.utils.requests
(:require [auth0-clojure.utils.common :as common]
[auth0-clojure.utils.json :as json]
[auth0-clojure.utils.edn :as edn]
[auth0-clojure.utils.urls :as urls]
[clj-http.client :as client]
[org.bovinegenius.exploding-fish :as uri]))
(def authorization-header "Authorization")
(def bearer "Bearer ")
(defn bearer-header [access-token]
{authorization-header (str bearer access-token)})
(def oauth-ks
#{:auth0/grant-type})
(defn oauth-vals-edn->json [body]
(let [edn-vals (select-keys body oauth-ks)
json-vals (into {} (for [[k v] edn-vals] [k (edn/kw->str-val v)]))
body (merge body json-vals)]
body))
(defmethod client/coerce-response-body :auth0-edn [_ resp]
(json/coerce-response-body-to-auth0-edn resp))
(defn auth0-request [config path options]
(let [base-url (urls/base-url
(select-keys
config
[:auth0/default-domain
:auth0/custom-domain]))
request-url (uri/path base-url path)
string-url (-> request-url uri/uri->map uri/map->string)]
(merge
TODO - getting EDN is cool , but in some cases JSON might be preferable - make this configurable
{:url string-url
:method :get
:content-type :json
:accept :json
:as :auth0-edn
:throw-exceptions false}
(common/edit-if
options
:body
(fn [body]
(-> body
oauth-vals-edn->json
json/edn->json))))))
(defn auth0-mgmt-request [{:keys [:auth0/mgmt-access-token] :as config} path options]
(auth0-request
config
path
(merge
options
{:headers (bearer-header mgmt-access-token)})))
| null | https://raw.githubusercontent.com/lumberdev/auth0-clojure/ed01e95d7a11e6948d286a35aead100ab5a39a00/src/auth0_clojure/utils/requests.clj | clojure | (ns auth0-clojure.utils.requests
(:require [auth0-clojure.utils.common :as common]
[auth0-clojure.utils.json :as json]
[auth0-clojure.utils.edn :as edn]
[auth0-clojure.utils.urls :as urls]
[clj-http.client :as client]
[org.bovinegenius.exploding-fish :as uri]))
(def authorization-header "Authorization")
(def bearer "Bearer ")
(defn bearer-header [access-token]
{authorization-header (str bearer access-token)})
(def oauth-ks
#{:auth0/grant-type})
(defn oauth-vals-edn->json [body]
(let [edn-vals (select-keys body oauth-ks)
json-vals (into {} (for [[k v] edn-vals] [k (edn/kw->str-val v)]))
body (merge body json-vals)]
body))
(defmethod client/coerce-response-body :auth0-edn [_ resp]
(json/coerce-response-body-to-auth0-edn resp))
(defn auth0-request [config path options]
(let [base-url (urls/base-url
(select-keys
config
[:auth0/default-domain
:auth0/custom-domain]))
request-url (uri/path base-url path)
string-url (-> request-url uri/uri->map uri/map->string)]
(merge
TODO - getting EDN is cool , but in some cases JSON might be preferable - make this configurable
{:url string-url
:method :get
:content-type :json
:accept :json
:as :auth0-edn
:throw-exceptions false}
(common/edit-if
options
:body
(fn [body]
(-> body
oauth-vals-edn->json
json/edn->json))))))
(defn auth0-mgmt-request [{:keys [:auth0/mgmt-access-token] :as config} path options]
(auth0-request
config
path
(merge
options
{:headers (bearer-header mgmt-access-token)})))
|
|
5bbc34bf5957ca5e0eb4b0a1fb9ca05e4fca1610fefe4432674b9830899ee65c | owainlewis/falkor | server.clj | (ns falkor.server
(:require [falkor.parser :as falkor]
[falkor.util :refer [enforce-params json-handler wrap-as-result]]
[falkor.middleware :as logging]
[compojure.core :refer :all]
[compojure.handler :as handler]
[ring.middleware.json :as middleware]
[ring.util.response :refer [resource-response response]]
[ring.middleware.defaults :refer [wrap-defaults api-defaults]]
[compojure.route :as route]))
(defn query-handler
"The query handler is used to render any xpath query"
[params]
(let [{:strs [url query] :as q} params]
(enforce-params {:url url :query query}
(try
(let [result (falkor/run-query url query)]
(json-handler 200
(wrap-as-result result url query)))
(catch Exception e
(json-handler 500
{:body "Request failed"}))))))
(defn root-handler []
(json-handler 200 {:body "OK"}))
(defroutes api-routes
(GET "/api/query" {params :query-params}
(query-handler params)))
(defroutes base-routes
(GET "/" []
(response "OK"))
(route/resources "/")
(route/not-found "<h1>Page not found</h1>"))
(def all-routes (routes api-routes base-routes))
(def app
(-> all-routes
handler/api
logging/wrap-logging
(wrap-defaults api-defaults)))
(def handler app)
| null | https://raw.githubusercontent.com/owainlewis/falkor/7d4fb04b11d4c7c820c9814d78a6d9ebff3ff01b/src/falkor/server.clj | clojure | (ns falkor.server
(:require [falkor.parser :as falkor]
[falkor.util :refer [enforce-params json-handler wrap-as-result]]
[falkor.middleware :as logging]
[compojure.core :refer :all]
[compojure.handler :as handler]
[ring.middleware.json :as middleware]
[ring.util.response :refer [resource-response response]]
[ring.middleware.defaults :refer [wrap-defaults api-defaults]]
[compojure.route :as route]))
(defn query-handler
"The query handler is used to render any xpath query"
[params]
(let [{:strs [url query] :as q} params]
(enforce-params {:url url :query query}
(try
(let [result (falkor/run-query url query)]
(json-handler 200
(wrap-as-result result url query)))
(catch Exception e
(json-handler 500
{:body "Request failed"}))))))
(defn root-handler []
(json-handler 200 {:body "OK"}))
(defroutes api-routes
(GET "/api/query" {params :query-params}
(query-handler params)))
(defroutes base-routes
(GET "/" []
(response "OK"))
(route/resources "/")
(route/not-found "<h1>Page not found</h1>"))
(def all-routes (routes api-routes base-routes))
(def app
(-> all-routes
handler/api
logging/wrap-logging
(wrap-defaults api-defaults)))
(def handler app)
|
|
4d4817ee8b1e3f0a00a6f60d9612364494c35fcf9607bc960ca4ea75ca9b075e | rabbitmq/rabbitmq-auth-backend-oauth2 | uaa_jwt_jwt.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(uaa_jwt_jwt).
Transitional step until we can require Erlang / OTP 21 and
%% use the now recommended try/catch syntax for obtaining the stack trace.
-compile(nowarn_deprecated_function).
-export([decode/1, decode_and_verify/2, get_key_id/1]).
-include_lib("jose/include/jose_jwt.hrl").
-include_lib("jose/include/jose_jws.hrl").
decode(Token) ->
try
#jose_jwt{fields = Fields} = jose_jwt:peek_payload(Token),
Fields
catch Type:Err:Stacktrace ->
{error, {invalid_token, Type, Err, Stacktrace}}
end.
decode_and_verify(Jwk, Token) ->
case jose_jwt:verify(Jwk, Token) of
{true, #jose_jwt{fields = Fields}, _} -> {true, Fields};
{false, #jose_jwt{fields = Fields}, _} -> {false, Fields}
end.
get_key_id(Token) ->
try
case jose_jwt:peek_protected(Token) of
#jose_jws{fields = #{<<"kid">> := Kid}} -> {ok, Kid};
#jose_jws{} -> get_default_key()
end
catch Type:Err:Stacktrace ->
{error, {invalid_token, Type, Err, Stacktrace}}
end.
get_default_key() ->
UaaEnv = application:get_env(rabbitmq_auth_backend_oauth2, key_config, []),
case proplists:get_value(default_key, UaaEnv, undefined) of
undefined -> {error, no_key};
Val -> {ok, Val}
end.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-auth-backend-oauth2/444174bba60eba307c0ee5ede51cb4a2fb99034f/src/uaa_jwt_jwt.erl | erlang |
use the now recommended try/catch syntax for obtaining the stack trace. | 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(uaa_jwt_jwt).
Transitional step until we can require Erlang / OTP 21 and
-compile(nowarn_deprecated_function).
-export([decode/1, decode_and_verify/2, get_key_id/1]).
-include_lib("jose/include/jose_jwt.hrl").
-include_lib("jose/include/jose_jws.hrl").
decode(Token) ->
try
#jose_jwt{fields = Fields} = jose_jwt:peek_payload(Token),
Fields
catch Type:Err:Stacktrace ->
{error, {invalid_token, Type, Err, Stacktrace}}
end.
decode_and_verify(Jwk, Token) ->
case jose_jwt:verify(Jwk, Token) of
{true, #jose_jwt{fields = Fields}, _} -> {true, Fields};
{false, #jose_jwt{fields = Fields}, _} -> {false, Fields}
end.
get_key_id(Token) ->
try
case jose_jwt:peek_protected(Token) of
#jose_jws{fields = #{<<"kid">> := Kid}} -> {ok, Kid};
#jose_jws{} -> get_default_key()
end
catch Type:Err:Stacktrace ->
{error, {invalid_token, Type, Err, Stacktrace}}
end.
get_default_key() ->
UaaEnv = application:get_env(rabbitmq_auth_backend_oauth2, key_config, []),
case proplists:get_value(default_key, UaaEnv, undefined) of
undefined -> {error, no_key};
Val -> {ok, Val}
end.
|
c7f2b51706359dcb586df3e23283c03a7436cfff907fe1191fff8b5fa7b4adf3 | exercism/clojure | two_fer.clj | (ns two-fer)
(defn two-fer [name] ;; <- arglist goes here
;; your code goes here
)
| null | https://raw.githubusercontent.com/exercism/clojure/7ed96a5ae3c471c37db2602baf3db2be3b5a2d1a/exercises/practice/two-fer/src/two_fer.clj | clojure | <- arglist goes here
your code goes here | (ns two-fer)
)
|
9cd120eb34c85ce584322258c551745c567e518a3c16964b77f06a00592cec8e | ocaml/odoc | m.mli | type t
module M : sig
type nonrec t = Foo of t
end
type x = Foo of y
and y = Bar of x
| null | https://raw.githubusercontent.com/ocaml/odoc/51220dfad29dbc48154230032291b9c2696e6b28/test/xref2/recursive_types.t/m.mli | ocaml | type t
module M : sig
type nonrec t = Foo of t
end
type x = Foo of y
and y = Bar of x
|
|
ddae3fcb595f63d876efb4b3f2ee31c52fdfb9a9f882cadf61776c078d99523c | camlp5/camlp5 | parsetree.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
*)
open Asttypes
type constant =
Pconst_integer of string * char option
3 3l 3L 3n
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes except 'l', 'L' and 'n' are rejected by the typechecker
*)
| Pconst_char of char
(* 'c' *)
| Pconst_string of string * Location.t * string option
(* "constant"
{delim|other constant|delim}
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
(* 3.4 2e5 1.4e-4
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
(* [@id ARG]
[@@id ARG]
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
*)
and extension = string loc * payload
(* [%id ARG]
[%%id ARG]
Sub-language placeholder -- rejected by the typechecker.
*)
and attributes = attribute list
and payload =
| PStr of structure
: SIG
| PTyp of core_type (* : T *)
| PPat of pattern * expression option (* ? P or ? P when E *)
* { 1 Core language }
(* Type expressions *)
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
ptyp_attributes: attributes; (* ... [@id1] [@id2] *)
}
and core_type_desc =
| Ptyp_any
(* _ *)
| Ptyp_var of string
(* 'a *)
| Ptyp_arrow of arg_label * core_type * core_type
(* T1 -> T2 Simple
~l:T1 -> T2 Labelled
?l:T1 -> T2 Optional
*)
| Ptyp_tuple of core_type list
T1 * ... * Tn
Invariant : n > = 2
Invariant: n >= 2
*)
| Ptyp_constr of Longident.t loc * core_type list
(* tconstr
T tconstr
(T1, ..., Tn) tconstr
*)
| Ptyp_object of object_field list * closed_flag
(* < l1:T1; ...; ln:Tn > (flag = Closed)
< l1:T1; ...; ln:Tn; .. > (flag = Open)
*)
| Ptyp_class of Longident.t loc * core_type list
# tconstr
T # tconstr
( T1 , ... , Tn ) # tconstr
T #tconstr
(T1, ..., Tn) #tconstr
*)
| Ptyp_alias of core_type * string
(* T as 'a *)
| Ptyp_variant of row_field list * closed_flag * label list option
(* [ `A|`B ] (flag = Closed; labels = None)
[> `A|`B ] (flag = Open; labels = None)
[< `A|`B ] (flag = Closed; labels = Some [])
[< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"])
*)
| Ptyp_poly of string loc list * core_type
' a1 ... ' an . T
Can only appear in the following context :
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let - binding : let x : ' a1 ... ' an . T
= e ...
- Under Cfk_virtual for methods ( not values ) .
- As the core_type of a Pctf_method node .
- As the core_type of a Pexp_poly node .
- As the pld_type field of a label_declaration .
- As a core_type of a Ptyp_object node .
Can only appear in the following context:
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let-binding: let x : 'a1 ... 'an. T
= e ...
- Under Cfk_virtual for methods (not values).
- As the core_type of a Pctf_method node.
- As the core_type of a Pexp_poly node.
- As the pld_type field of a label_declaration.
- As a core_type of a Ptyp_object node.
*)
| Ptyp_package of package_type
(* (module S) *)
| Ptyp_extension of extension
(* [%id] *)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
(*
(module S)
(module S with type t1 = T1 and ... and tn = Tn)
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
[ ` A ] ( true , [ ] )
[ ` A of T ] ( false , [ T ] )
[ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] )
[ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] )
- The ' bool ' field is true if the tag contains a
constant ( empty ) constructor .
- ' & ' occurs when several types are used for the same constructor
( see 4.2 in the manual )
[`A of T] ( false, [T] )
[`A of T1 & .. & Tn] ( false, [T1;...Tn] )
[`A of & T1 & .. & Tn] ( true, [T1;...Tn] )
- The 'bool' field is true if the tag contains a
constant (empty) constructor.
- '&' occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type
(* [ | t ] *)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
(* Patterns *)
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
ppat_attributes: attributes; (* ... [@id1] [@id2] *)
}
and pattern_desc =
| Ppat_any
(* _ *)
| Ppat_var of string loc
(* x *)
| Ppat_alias of pattern * string loc
(* P as 'a *)
| Ppat_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Ppat_interval of constant * constant
(* 'a'..'z'
Other forms of interval are recognized by the parser
but rejected by the type-checker. *)
| Ppat_tuple of pattern list
( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Ppat_construct of Longident.t loc * pattern option
C None
C P Some P
C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] )
C P Some P
C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn])
*)
| Ppat_variant of label * pattern option
(* `A (None)
`A P (Some P)
*)
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
{ l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Ppat_array of pattern list
(* [| P1; ...; Pn |] *)
| Ppat_or of pattern * pattern
P1 | P2
| Ppat_constraint of pattern * core_type
(* (P : T) *)
| Ppat_type of Longident.t loc
(* #tconst *)
| Ppat_lazy of pattern
(* lazy P *)
| Ppat_unpack of string option loc
(* (module P) Some "P"
(module _) None
Note: (module P : S) is represented as
Ppat_constraint(Ppat_unpack, Ptyp_package)
*)
| Ppat_exception of pattern
(* exception P *)
| Ppat_extension of extension
(* [%id] *)
| Ppat_open of Longident.t loc * pattern
(* M.(P) *)
(* Value expressions *)
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
pexp_attributes: attributes; (* ... [@id1] [@id2] *)
}
and expression_desc =
| Pexp_ident of Longident.t loc
(* x
M.x
*)
| Pexp_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Pexp_let of rec_flag * value_binding list * expression
let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Pexp_function of case list
(* function P1 -> E1 | ... | Pn -> En *)
| Pexp_fun of arg_label * expression option * pattern * expression
fun P - > E1 ( Simple , None )
fun ~l :P - > E1 ( Labelled l , None )
fun ? l :P - > E1 ( Optional l , None )
fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 )
Notes :
- If E0 is provided , only Optional is allowed .
- " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun .
- " let f P = E " is represented using Pexp_fun .
fun ~l:P -> E1 (Labelled l, None)
fun ?l:P -> E1 (Optional l, None)
fun ?l:(P = E0) -> E1 (Optional l, Some E0)
Notes:
- If E0 is provided, only Optional is allowed.
- "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun.
- "let f P = E" is represented using Pexp_fun.
*)
| Pexp_apply of expression * (arg_label * expression) list
E0 ~l1 : E1 ... ~ln : En
li can be empty ( non labeled argument ) or start with ' ? '
( optional argument ) .
Invariant : n > 0
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pexp_match of expression * case list
match E0 with P1 - > E1 | ... | Pn - > En
| Pexp_try of expression * case list
try E0 with P1 - > E1 | ... | Pn - > En
| Pexp_tuple of expression list
( E1 , ... , En )
Invariant : n > = 2
Invariant: n >= 2
*)
| Pexp_construct of Longident.t loc * expression option
(* C None
C E Some E
C (E1, ..., En) Some (Pexp_tuple[E1;...;En])
*)
| Pexp_variant of label * expression option
(* `A (None)
`A E (Some E)
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
{ l1 = P1 ; ... ; ln = Pn } ( None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 )
Invariant : n > 0
{ E0 with l1=P1; ...; ln=Pn } (Some E0)
Invariant: n > 0
*)
| Pexp_field of expression * Longident.t loc
(* E.l *)
| Pexp_setfield of expression * Longident.t loc * expression
E1.l < - E2
| Pexp_array of expression list
(* [| E1; ...; En |] *)
| Pexp_ifthenelse of expression * expression * expression option
if E1 then E2 else E3
| Pexp_sequence of expression * expression
(* E1; E2 *)
| Pexp_while of expression * expression
(* while E1 do E2 done *)
| Pexp_for of
pattern * expression * expression * direction_flag * expression
for i = E1 to E2 do E3 done ( flag = Upto )
for i = E1 downto E2 do E3 done ( flag = )
for i = E1 downto E2 do E3 done (flag = Downto)
*)
| Pexp_constraint of expression * core_type
(* (E : T) *)
| Pexp_coerce of expression * core_type option * core_type
(* (E :> T) (None, T)
(E : T0 :> T) (Some T0, T)
*)
| Pexp_send of expression * label loc
(* E # m *)
| Pexp_new of Longident.t loc
(* new M.c *)
| Pexp_setinstvar of label loc * expression
(* x <- 2 *)
| Pexp_override of (label loc * expression) list
{ < x1 = E1 ; ... ; > }
| Pexp_letmodule of string option loc * module_expr * expression
(* let module M = ME in E *)
| Pexp_letexception of extension_constructor * expression
(* let exception C in E *)
| Pexp_assert of expression
(* assert E
Note: "assert false" is treated in a special way by the
type-checker. *)
| Pexp_lazy of expression
(* lazy E *)
| Pexp_poly of expression * core_type option
Used for method bodies .
Can only be used as the expression under
for methods ( not values ) .
Can only be used as the expression under Cfk_concrete
for methods (not values). *)
| Pexp_object of class_structure
(* object ... end *)
| Pexp_newtype of string loc * expression
(* fun (type t) -> E *)
| Pexp_pack of module_expr
(* (module ME)
(module ME : S) is represented as
Pexp_constraint(Pexp_pack, Ptyp_package S) *)
| Pexp_open of open_declaration * expression
(* M.(E)
let open M in E
let! open M in E *)
| Pexp_letop of letop
(* let* P = E in E
let* P = E and* P = E in E *)
| Pexp_extension of extension
(* [%id] *)
| Pexp_unreachable
(* . *)
and case = (* (P -> E) or (P when E0 -> E) *)
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
(* Value descriptions *)
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
pval_attributes: attributes; (* ... [@@id1] [@@id2] *)
pval_loc: Location.t;
}
(*
val x: T (prim = [])
external x: T = "s1" ... "sn" (prim = ["s1";..."sn"])
*)
(* Type declarations *)
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
(* ('a1,...'an) t; None represents _*)
ptype_cstrs: (core_type * core_type * Location.t) list;
... constraint T1 = T1 ' ... constraint
ptype_kind: type_kind;
ptype_private: private_flag; (* = private ... *)
ptype_manifest: core_type option; (* = T *)
ptype_attributes: attributes; (* ... [@@id1] [@@id2] *)
ptype_loc: Location.t;
}
(*
type t (abstract, no manifest)
type t = T0 (abstract, manifest=T0)
type t = C of T | ... (variant, no manifest)
type t = T0 = C of T | ... (variant, manifest=T0)
type t = {l: T; ...} (record, no manifest)
type t = T0 = {l : T; ...} (record, manifest=T0)
type t = .. (open, no manifest)
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list
(* Invariant: non-empty list *)
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
pld_attributes: attributes; (* l : T [@id1] [@id2] *)
}
(* { ...; l: T; ... } (mutable=Immutable)
{ ...; mutable l: T; ... } (mutable=Mutable)
Note: T can be a Ptyp_poly.
*)
and constructor_declaration =
{
pcd_name: string loc;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
pcd_attributes: attributes; (* C of ... [@id1] [@id2] *)
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
(*
| C of T1 * ... * Tn (res = None, args = Pcstr_tuple [])
| C: T0 (res = Some T0, args = [])
| C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple)
| C of {...} (res = None, args = Pcstr_record)
| C: {...} -> T0 (res = Some T0, args = Pcstr_record)
| C of {...} as t (res = None, args = Pcstr_record)
*)
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
ptyext_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
(*
type t += ...
*)
and extension_constructor =
{
pext_name: string loc;
pext_kind : extension_constructor_kind;
pext_loc : Location.t;
pext_attributes: attributes; (* C of ... [@id1] [@id2] *)
}
(* exception E *)
and type_exception =
{
ptyexn_constructor: extension_constructor;
ptyexn_loc: Location.t;
ptyexn_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and extension_constructor_kind =
Pext_decl of constructor_arguments * core_type option
(*
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
*)
| Pext_rebind of Longident.t loc
(*
| C = D
*)
(** {1 Class language} *)
(* Type expressions for the class language *)
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
pcty_attributes: attributes; (* ... [@id1] [@id2] *)
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
(* c
['a1, ..., 'an] c *)
| Pcty_signature of class_signature
(* object ... end *)
| Pcty_arrow of arg_label * core_type * class_type
(* T -> CT Simple
~l:T -> CT Labelled l
?l:T -> CT Optional l
*)
| Pcty_extension of extension
(* [%id] *)
| Pcty_open of open_description * class_type
(* let open M in CT *)
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
(* object('selfpat) ... end
object ... end (self = Ptyp_any)
*)
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
pctf_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and class_type_field_desc =
| Pctf_inherit of class_type
(* inherit CT *)
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
(* val x: T *)
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
(* method x: T
Note: T can be a Ptyp_poly.
*)
| Pctf_constraint of (core_type * core_type)
(* constraint T1 = T2 *)
| Pctf_attribute of attribute
(* [@@@id] *)
| Pctf_extension of extension
(* [%%id] *)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
pci_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
(* class c = ...
class ['a1,...,'an] c = ...
class virtual c = ...
Also used for "class type" declaration.
*)
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
(* Value expressions for the class language *)
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
pcl_attributes: attributes; (* ... [@id1] [@id2] *)
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
(* c
['a1, ..., 'an] c *)
| Pcl_structure of class_structure
(* object ... end *)
| Pcl_fun of arg_label * expression option * pattern * class_expr
(* fun P -> CE (Simple, None)
fun ~l:P -> CE (Labelled l, None)
fun ?l:P -> CE (Optional l, None)
fun ?l:(P = E0) -> CE (Optional l, Some E0)
*)
| Pcl_apply of class_expr * (arg_label * expression) list
(* CE ~l1:E1 ... ~ln:En
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pcl_let of rec_flag * value_binding list * class_expr
let P1 = E1 and ... and Pn = EN in CE ( flag = )
let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive)
*)
| Pcl_constraint of class_expr * class_type
(* (CE : CT) *)
| Pcl_extension of extension
(* [%id] *)
| Pcl_open of open_description * class_expr
(* let open M in CE *)
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
(* object(selfpat) ... end
object ... end (self = Ppat_any)
*)
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
pcf_attributes: attributes; (* ... [@@id1] [@@id2] *)
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
(* inherit CE
inherit CE as x
inherit! CE
inherit! CE as x
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
(* val x = E
val virtual x: T
*)
| Pcf_method of (label loc * private_flag * class_field_kind)
method x = E ( E can be a Pexp_poly )
method virtual x : T ( T can be a Ptyp_poly )
method virtual x: T (T can be a Ptyp_poly)
*)
| Pcf_constraint of (core_type * core_type)
(* constraint T1 = T2 *)
| Pcf_initializer of expression
(* initializer E *)
| Pcf_attribute of attribute
(* [@@@id] *)
| Pcf_extension of extension
(* [%%id] *)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
(** {1 Module language} *)
(* Type expressions for the module language *)
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
pmty_attributes: attributes; (* ... [@id1] [@id2] *)
}
and module_type_desc =
| Pmty_ident of Longident.t loc
(* S *)
| Pmty_signature of signature
(* sig ... end *)
| Pmty_functor of functor_parameter * module_type
functor(X : ) - > MT2
| Pmty_with of module_type * with_constraint list
(* MT with ... *)
| Pmty_typeof of module_expr
(* module type of ME *)
| Pmty_extension of extension
(* [%id] *)
| Pmty_alias of Longident.t loc
(* (module M) *)
and functor_parameter =
| Unit
(* () *)
| Named of string option loc * module_type
( X : MT ) Some X , MT
( _ : MT ) None , MT
(_ : MT) None, MT *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
x : T
external x : T = " s1 " ... " sn "
val x: T
external x: T = "s1" ... "sn"
*)
| Psig_type of rec_flag * type_declaration list
type t1 = ... and ... and = ...
| Psig_typesubst of type_declaration list
(* type t1 := ... and ... and tn := ... *)
| Psig_typext of type_extension
(* type t1 += ... *)
| Psig_exception of type_exception
(* exception C of T *)
| Psig_module of module_declaration
(* module X = M
module X : MT *)
| Psig_modsubst of module_substitution
(* module X := M *)
| Psig_recmodule of module_declaration list
module rec X1 : and ... and Xn : MTn
| Psig_modtype of module_type_declaration
(* module type S = MT
module type S *)
| Psig_open of open_description
(* open X *)
| Psig_include of include_description
include MT
| Psig_class of class_description list
(* class c1 : ... and ... and cn : ... *)
| Psig_class_type of class_type_declaration list
(* class type ct1 = ... and ... and ctn = ... *)
| Psig_attribute of attribute
(* [@@@id] *)
| Psig_extension of extension * attributes
(* [%%id] *)
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
pmd_attributes: attributes; (* ... [@@id1] [@@id2] *)
pmd_loc: Location.t;
}
(* S : MT *)
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
pms_attributes: attributes; (* ... [@@id1] [@@id2] *)
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
pmtd_attributes: attributes; (* ... [@@id1] [@@id2] *)
pmtd_loc: Location.t;
}
S = MT
S ( abstract module type declaration , pmtd_type = None )
S (abstract module type declaration, pmtd_type = None)
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
(* open! X - popen_override = Override (silences the 'used identifier
shadowing' warning)
open X - popen_override = Fresh
*)
and open_description = Longident.t loc open_infos
open M.N
open M(N).O
open M(N).O *)
and open_declaration = module_expr open_infos
open M.N
open M(N).O
open struct ... end
open M(N).O
open struct ... end *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
include MT
and include_declaration = module_expr include_infos
(* include ME *)
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
(* with type X.t = ...
Note: the last component of the longident must match
the name of the type_declaration. *)
| Pwith_module of Longident.t loc * Longident.t loc
(* with module X.Y = Z *)
| Pwith_typesubst of Longident.t loc * type_declaration
(* with type X.t := ..., same format as [Pwith_type] *)
| Pwith_modsubst of Longident.t loc * Longident.t loc
(* with module X.Y := Z *)
(* Value expressions for the module language *)
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
pmod_attributes: attributes; (* ... [@id1] [@id2] *)
}
and module_expr_desc =
| Pmod_ident of Longident.t loc
(* X *)
| Pmod_structure of structure
(* struct ... end *)
| Pmod_functor of functor_parameter * module_expr
functor(X : ) - > ME
| Pmod_apply of module_expr * module_expr
(* ME1(ME2) *)
| Pmod_constraint of module_expr * module_type
(* (ME : MT) *)
| Pmod_unpack of expression
( E )
| Pmod_extension of extension
(* [%id] *)
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes
(* E *)
| Pstr_value of rec_flag * value_binding list
let P1 = E1 and ... and Pn = EN ( flag = )
let rec P1 = E1 and ... and Pn = EN ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN (flag = Recursive)
*)
| Pstr_primitive of value_description
x : T
external x : T = " s1 " ... " sn "
external x: T = "s1" ... "sn" *)
| Pstr_type of rec_flag * type_declaration list
(* type t1 = ... and ... and tn = ... *)
| Pstr_typext of type_extension
(* type t1 += ... *)
| Pstr_exception of type_exception
exception C of T
exception C =
exception C = M.X *)
| Pstr_module of module_binding
(* module X = ME *)
| Pstr_recmodule of module_binding list
(* module rec X1 = ME1 and ... and Xn = MEn *)
| Pstr_modtype of module_type_declaration
(* module type S = MT *)
| Pstr_open of open_declaration
(* open X *)
| Pstr_class of class_declaration list
(* class c1 = ... and ... and cn = ... *)
| Pstr_class_type of class_type_declaration list
(* class type ct1 = ... and ... and ctn = ... *)
| Pstr_include of include_declaration
(* include ME *)
| Pstr_attribute of attribute
(* [@@@id] *)
| Pstr_extension of extension * attributes
(* [%%id] *)
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
(* X = ME *)
* { 1 Toplevel }
Toplevel phrases
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive
(* #use, #load ... *)
and toplevel_directive =
{
pdir_name : string loc;
pdir_arg : directive_argument option;
pdir_loc : Location.t;
}
and directive_argument =
{
pdira_desc : directive_argument_desc;
pdira_loc : Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/ocaml_stuff/4.12.0/parsing/parsetree.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
'c'
"constant"
{delim|other constant|delim}
The location span the content of the string, without the delimiters.
3.4 2e5 1.4e-4
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
[@id ARG]
[@@id ARG]
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
[%id ARG]
[%%id ARG]
Sub-language placeholder -- rejected by the typechecker.
: T
? P or ? P when E
Type expressions
... [@id1] [@id2]
_
'a
T1 -> T2 Simple
~l:T1 -> T2 Labelled
?l:T1 -> T2 Optional
tconstr
T tconstr
(T1, ..., Tn) tconstr
< l1:T1; ...; ln:Tn > (flag = Closed)
< l1:T1; ...; ln:Tn; .. > (flag = Open)
T as 'a
[ `A|`B ] (flag = Closed; labels = None)
[> `A|`B ] (flag = Open; labels = None)
[< `A|`B ] (flag = Closed; labels = Some [])
[< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"])
(module S)
[%id]
(module S)
(module S with type t1 = T1 and ... and tn = Tn)
[ | t ]
Patterns
... [@id1] [@id2]
_
x
P as 'a
'a'..'z'
Other forms of interval are recognized by the parser
but rejected by the type-checker.
`A (None)
`A P (Some P)
[| P1; ...; Pn |]
(P : T)
#tconst
lazy P
(module P) Some "P"
(module _) None
Note: (module P : S) is represented as
Ppat_constraint(Ppat_unpack, Ptyp_package)
exception P
[%id]
M.(P)
Value expressions
... [@id1] [@id2]
x
M.x
function P1 -> E1 | ... | Pn -> En
C None
C E Some E
C (E1, ..., En) Some (Pexp_tuple[E1;...;En])
`A (None)
`A E (Some E)
E.l
[| E1; ...; En |]
E1; E2
while E1 do E2 done
(E : T)
(E :> T) (None, T)
(E : T0 :> T) (Some T0, T)
E # m
new M.c
x <- 2
let module M = ME in E
let exception C in E
assert E
Note: "assert false" is treated in a special way by the
type-checker.
lazy E
object ... end
fun (type t) -> E
(module ME)
(module ME : S) is represented as
Pexp_constraint(Pexp_pack, Ptyp_package S)
M.(E)
let open M in E
let! open M in E
let* P = E in E
let* P = E and* P = E in E
[%id]
.
(P -> E) or (P when E0 -> E)
Value descriptions
... [@@id1] [@@id2]
val x: T (prim = [])
external x: T = "s1" ... "sn" (prim = ["s1";..."sn"])
Type declarations
('a1,...'an) t; None represents _
= private ...
= T
... [@@id1] [@@id2]
type t (abstract, no manifest)
type t = T0 (abstract, manifest=T0)
type t = C of T | ... (variant, no manifest)
type t = T0 = C of T | ... (variant, manifest=T0)
type t = {l: T; ...} (record, no manifest)
type t = T0 = {l : T; ...} (record, manifest=T0)
type t = .. (open, no manifest)
Invariant: non-empty list
l : T [@id1] [@id2]
{ ...; l: T; ... } (mutable=Immutable)
{ ...; mutable l: T; ... } (mutable=Mutable)
Note: T can be a Ptyp_poly.
C of ... [@id1] [@id2]
| C of T1 * ... * Tn (res = None, args = Pcstr_tuple [])
| C: T0 (res = Some T0, args = [])
| C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple)
| C of {...} (res = None, args = Pcstr_record)
| C: {...} -> T0 (res = Some T0, args = Pcstr_record)
| C of {...} as t (res = None, args = Pcstr_record)
... [@@id1] [@@id2]
type t += ...
C of ... [@id1] [@id2]
exception E
... [@@id1] [@@id2]
| C of T1 * ... * Tn ([T1; ...; Tn], None)
| C: T0 ([], Some T0)
| C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
| C = D
* {1 Class language}
Type expressions for the class language
... [@id1] [@id2]
c
['a1, ..., 'an] c
object ... end
T -> CT Simple
~l:T -> CT Labelled l
?l:T -> CT Optional l
[%id]
let open M in CT
object('selfpat) ... end
object ... end (self = Ptyp_any)
... [@@id1] [@@id2]
inherit CT
val x: T
method x: T
Note: T can be a Ptyp_poly.
constraint T1 = T2
[@@@id]
[%%id]
... [@@id1] [@@id2]
class c = ...
class ['a1,...,'an] c = ...
class virtual c = ...
Also used for "class type" declaration.
Value expressions for the class language
... [@id1] [@id2]
c
['a1, ..., 'an] c
object ... end
fun P -> CE (Simple, None)
fun ~l:P -> CE (Labelled l, None)
fun ?l:P -> CE (Optional l, None)
fun ?l:(P = E0) -> CE (Optional l, Some E0)
CE ~l1:E1 ... ~ln:En
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
(CE : CT)
[%id]
let open M in CE
object(selfpat) ... end
object ... end (self = Ppat_any)
... [@@id1] [@@id2]
inherit CE
inherit CE as x
inherit! CE
inherit! CE as x
val x = E
val virtual x: T
constraint T1 = T2
initializer E
[@@@id]
[%%id]
* {1 Module language}
Type expressions for the module language
... [@id1] [@id2]
S
sig ... end
MT with ...
module type of ME
[%id]
(module M)
()
type t1 := ... and ... and tn := ...
type t1 += ...
exception C of T
module X = M
module X : MT
module X := M
module type S = MT
module type S
open X
class c1 : ... and ... and cn : ...
class type ct1 = ... and ... and ctn = ...
[@@@id]
[%%id]
... [@@id1] [@@id2]
S : MT
... [@@id1] [@@id2]
... [@@id1] [@@id2]
open! X - popen_override = Override (silences the 'used identifier
shadowing' warning)
open X - popen_override = Fresh
include ME
with type X.t = ...
Note: the last component of the longident must match
the name of the type_declaration.
with module X.Y = Z
with type X.t := ..., same format as [Pwith_type]
with module X.Y := Z
Value expressions for the module language
... [@id1] [@id2]
X
struct ... end
ME1(ME2)
(ME : MT)
[%id]
E
type t1 = ... and ... and tn = ...
type t1 += ...
module X = ME
module rec X1 = ME1 and ... and Xn = MEn
module type S = MT
open X
class c1 = ... and ... and cn = ...
class type ct1 = ... and ... and ctn = ...
include ME
[@@@id]
[%%id]
X = ME
#use, #load ... | , 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 Asttypes
type constant =
Pconst_integer of string * char option
3 3l 3L 3n
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes except 'l', 'L' and 'n' are rejected by the typechecker
*)
| Pconst_char of char
| Pconst_string of string * Location.t * string option
| Pconst_float of string * char option
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
and extension = string loc * payload
and attributes = attribute list
and payload =
| PStr of structure
: SIG
* { 1 Core language }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
}
and core_type_desc =
| Ptyp_any
| Ptyp_var of string
| Ptyp_arrow of arg_label * core_type * core_type
| Ptyp_tuple of core_type list
T1 * ... * Tn
Invariant : n > = 2
Invariant: n >= 2
*)
| Ptyp_constr of Longident.t loc * core_type list
| Ptyp_object of object_field list * closed_flag
| Ptyp_class of Longident.t loc * core_type list
# tconstr
T # tconstr
( T1 , ... , Tn ) # tconstr
T #tconstr
(T1, ..., Tn) #tconstr
*)
| Ptyp_alias of core_type * string
| Ptyp_variant of row_field list * closed_flag * label list option
| Ptyp_poly of string loc list * core_type
' a1 ... ' an . T
Can only appear in the following context :
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let - binding : let x : ' a1 ... ' an . T
= e ...
- Under Cfk_virtual for methods ( not values ) .
- As the core_type of a Pctf_method node .
- As the core_type of a Pexp_poly node .
- As the pld_type field of a label_declaration .
- As a core_type of a Ptyp_object node .
Can only appear in the following context:
- As the core_type of a Ppat_constraint node corresponding
to a constraint on a let-binding: let x : 'a1 ... 'an. T
= e ...
- Under Cfk_virtual for methods (not values).
- As the core_type of a Pctf_method node.
- As the core_type of a Pexp_poly node.
- As the pld_type field of a label_declaration.
- As a core_type of a Ptyp_object node.
*)
| Ptyp_package of package_type
| Ptyp_extension of extension
and package_type = Longident.t loc * (Longident.t loc * core_type) list
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
[ ` A ] ( true , [ ] )
[ ` A of T ] ( false , [ T ] )
[ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] )
[ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] )
- The ' bool ' field is true if the tag contains a
constant ( empty ) constructor .
- ' & ' occurs when several types are used for the same constructor
( see 4.2 in the manual )
[`A of T] ( false, [T] )
[`A of T1 & .. & Tn] ( false, [T1;...Tn] )
[`A of & T1 & .. & Tn] ( true, [T1;...Tn] )
- The 'bool' field is true if the tag contains a
constant (empty) constructor.
- '&' occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
}
and pattern_desc =
| Ppat_any
| Ppat_var of string loc
| Ppat_alias of pattern * string loc
| Ppat_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Ppat_interval of constant * constant
| Ppat_tuple of pattern list
( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Ppat_construct of Longident.t loc * pattern option
C None
C P Some P
C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] )
C P Some P
C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn])
*)
| Ppat_variant of label * pattern option
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
{ l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Ppat_array of pattern list
| Ppat_or of pattern * pattern
P1 | P2
| Ppat_constraint of pattern * core_type
| Ppat_type of Longident.t loc
| Ppat_lazy of pattern
| Ppat_unpack of string option loc
| Ppat_exception of pattern
| Ppat_extension of extension
| Ppat_open of Longident.t loc * pattern
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
}
and expression_desc =
| Pexp_ident of Longident.t loc
| Pexp_constant of constant
1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Pexp_let of rec_flag * value_binding list * expression
let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Pexp_function of case list
| Pexp_fun of arg_label * expression option * pattern * expression
fun P - > E1 ( Simple , None )
fun ~l :P - > E1 ( Labelled l , None )
fun ? l :P - > E1 ( Optional l , None )
fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 )
Notes :
- If E0 is provided , only Optional is allowed .
- " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun .
- " let f P = E " is represented using Pexp_fun .
fun ~l:P -> E1 (Labelled l, None)
fun ?l:P -> E1 (Optional l, None)
fun ?l:(P = E0) -> E1 (Optional l, Some E0)
Notes:
- If E0 is provided, only Optional is allowed.
- "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun.
- "let f P = E" is represented using Pexp_fun.
*)
| Pexp_apply of expression * (arg_label * expression) list
E0 ~l1 : E1 ... ~ln : En
li can be empty ( non labeled argument ) or start with ' ? '
( optional argument ) .
Invariant : n > 0
li can be empty (non labeled argument) or start with '?'
(optional argument).
Invariant: n > 0
*)
| Pexp_match of expression * case list
match E0 with P1 - > E1 | ... | Pn - > En
| Pexp_try of expression * case list
try E0 with P1 - > E1 | ... | Pn - > En
| Pexp_tuple of expression list
( E1 , ... , En )
Invariant : n > = 2
Invariant: n >= 2
*)
| Pexp_construct of Longident.t loc * expression option
| Pexp_variant of label * expression option
| Pexp_record of (Longident.t loc * expression) list * expression option
{ l1 = P1 ; ... ; ln = Pn } ( None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 )
Invariant : n > 0
{ E0 with l1=P1; ...; ln=Pn } (Some E0)
Invariant: n > 0
*)
| Pexp_field of expression * Longident.t loc
| Pexp_setfield of expression * Longident.t loc * expression
E1.l < - E2
| Pexp_array of expression list
| Pexp_ifthenelse of expression * expression * expression option
if E1 then E2 else E3
| Pexp_sequence of expression * expression
| Pexp_while of expression * expression
| Pexp_for of
pattern * expression * expression * direction_flag * expression
for i = E1 to E2 do E3 done ( flag = Upto )
for i = E1 downto E2 do E3 done ( flag = )
for i = E1 downto E2 do E3 done (flag = Downto)
*)
| Pexp_constraint of expression * core_type
| Pexp_coerce of expression * core_type option * core_type
| Pexp_send of expression * label loc
| Pexp_new of Longident.t loc
| Pexp_setinstvar of label loc * expression
| Pexp_override of (label loc * expression) list
{ < x1 = E1 ; ... ; > }
| Pexp_letmodule of string option loc * module_expr * expression
| Pexp_letexception of extension_constructor * expression
| Pexp_assert of expression
| Pexp_lazy of expression
| Pexp_poly of expression * core_type option
Used for method bodies .
Can only be used as the expression under
for methods ( not values ) .
Can only be used as the expression under Cfk_concrete
for methods (not values). *)
| Pexp_object of class_structure
| Pexp_newtype of string loc * expression
| Pexp_pack of module_expr
| Pexp_open of open_declaration * expression
| Pexp_letop of letop
| Pexp_extension of extension
| Pexp_unreachable
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
pval_loc: Location.t;
}
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
ptype_cstrs: (core_type * core_type * Location.t) list;
... constraint T1 = T1 ' ... constraint
ptype_kind: type_kind;
ptype_loc: Location.t;
}
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
}
and constructor_declaration =
{
pcd_name: string loc;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
}
and extension_constructor =
{
pext_name: string loc;
pext_kind : extension_constructor_kind;
pext_loc : Location.t;
}
and type_exception =
{
ptyexn_constructor: extension_constructor;
ptyexn_loc: Location.t;
}
and extension_constructor_kind =
Pext_decl of constructor_arguments * core_type option
| Pext_rebind of Longident.t loc
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
| Pcty_signature of class_signature
| Pcty_arrow of arg_label * core_type * class_type
| Pcty_extension of extension
| Pcty_open of open_description * class_type
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
}
and class_type_field_desc =
| Pctf_inherit of class_type
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
| Pctf_constraint of (core_type * core_type)
| Pctf_attribute of attribute
| Pctf_extension of extension
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
}
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
| Pcl_structure of class_structure
| Pcl_fun of arg_label * expression option * pattern * class_expr
| Pcl_apply of class_expr * (arg_label * expression) list
| Pcl_let of rec_flag * value_binding list * class_expr
let P1 = E1 and ... and Pn = EN in CE ( flag = )
let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive)
*)
| Pcl_constraint of class_expr * class_type
| Pcl_extension of extension
| Pcl_open of open_description * class_expr
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
| Pcf_val of (label loc * mutable_flag * class_field_kind)
| Pcf_method of (label loc * private_flag * class_field_kind)
method x = E ( E can be a Pexp_poly )
method virtual x : T ( T can be a Ptyp_poly )
method virtual x: T (T can be a Ptyp_poly)
*)
| Pcf_constraint of (core_type * core_type)
| Pcf_initializer of expression
| Pcf_attribute of attribute
| Pcf_extension of extension
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
}
and module_type_desc =
| Pmty_ident of Longident.t loc
| Pmty_signature of signature
| Pmty_functor of functor_parameter * module_type
functor(X : ) - > MT2
| Pmty_with of module_type * with_constraint list
| Pmty_typeof of module_expr
| Pmty_extension of extension
| Pmty_alias of Longident.t loc
and functor_parameter =
| Unit
| Named of string option loc * module_type
( X : MT ) Some X , MT
( _ : MT ) None , MT
(_ : MT) None, MT *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
x : T
external x : T = " s1 " ... " sn "
val x: T
external x: T = "s1" ... "sn"
*)
| Psig_type of rec_flag * type_declaration list
type t1 = ... and ... and = ...
| Psig_typesubst of type_declaration list
| Psig_typext of type_extension
| Psig_exception of type_exception
| Psig_module of module_declaration
| Psig_modsubst of module_substitution
| Psig_recmodule of module_declaration list
module rec X1 : and ... and Xn : MTn
| Psig_modtype of module_type_declaration
| Psig_open of open_description
| Psig_include of include_description
include MT
| Psig_class of class_description list
| Psig_class_type of class_type_declaration list
| Psig_attribute of attribute
| Psig_extension of extension * attributes
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
pmd_loc: Location.t;
}
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
pmtd_loc: Location.t;
}
S = MT
S ( abstract module type declaration , pmtd_type = None )
S (abstract module type declaration, pmtd_type = None)
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
and open_description = Longident.t loc open_infos
open M.N
open M(N).O
open M(N).O *)
and open_declaration = module_expr open_infos
open M.N
open M(N).O
open struct ... end
open M(N).O
open struct ... end *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
include MT
and include_declaration = module_expr include_infos
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
| Pwith_module of Longident.t loc * Longident.t loc
| Pwith_typesubst of Longident.t loc * type_declaration
| Pwith_modsubst of Longident.t loc * Longident.t loc
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
}
and module_expr_desc =
| Pmod_ident of Longident.t loc
| Pmod_structure of structure
| Pmod_functor of functor_parameter * module_expr
functor(X : ) - > ME
| Pmod_apply of module_expr * module_expr
| Pmod_constraint of module_expr * module_type
| Pmod_unpack of expression
( E )
| Pmod_extension of extension
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes
| Pstr_value of rec_flag * value_binding list
let P1 = E1 and ... and Pn = EN ( flag = )
let rec P1 = E1 and ... and Pn = EN ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN (flag = Recursive)
*)
| Pstr_primitive of value_description
x : T
external x : T = " s1 " ... " sn "
external x: T = "s1" ... "sn" *)
| Pstr_type of rec_flag * type_declaration list
| Pstr_typext of type_extension
| Pstr_exception of type_exception
exception C of T
exception C =
exception C = M.X *)
| Pstr_module of module_binding
| Pstr_recmodule of module_binding list
| Pstr_modtype of module_type_declaration
| Pstr_open of open_declaration
| Pstr_class of class_declaration list
| Pstr_class_type of class_type_declaration list
| Pstr_include of include_declaration
| Pstr_attribute of attribute
| Pstr_extension of extension * attributes
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
* { 1 Toplevel }
Toplevel phrases
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive
and toplevel_directive =
{
pdir_name : string loc;
pdir_arg : directive_argument option;
pdir_loc : Location.t;
}
and directive_argument =
{
pdira_desc : directive_argument_desc;
pdira_loc : Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
|
2931ba514b54959bff2b49909f913feeaa47831c7cb7bf1715ba92625d26f1fd | FlowerWrong/mblog | user_default.erl | %% ---
Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
%% Copyrights apply to this code. It may not be used to create training material,
%% courses, books, articles, and the like. Contact us if you are in doubt.
%% We make no guarantees that this code is fit for any purpose.
%% Visit for more book information.
%%---
-module(user_default).
-compile(export_all).
hello() ->
"Hello Joe how are you?".
away(Time) ->
io:format("Joe is away and will be back in ~w minutes~n",
[Time]).
| null | https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/user_default.erl | erlang | ---
Copyrights apply to this code. It may not be used to create training material,
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
--- | Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
-module(user_default).
-compile(export_all).
hello() ->
"Hello Joe how are you?".
away(Time) ->
io:format("Joe is away and will be back in ~w minutes~n",
[Time]).
|
8916b58512c7264e1026b5ea8b1359ba9be44d0e1ace8e5baff578fcfe89a150 | haroldcarr/learn-haskell-coq-ml-etc | WriteRunDot.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
Created : 2014 Feb 26 ( We d ) 18:54:30 by .
Last Modified : 2014 Mar 02 ( Sun ) 15:49:45 by .
Created : 2014 Feb 26 (Wed) 18:54:30 by Harold Carr.
Last Modified : 2014 Mar 02 (Sun) 15:49:45 by Harold Carr.
-}
module WriteRunDot where
import Control.Monad (forM_)
import Data.GraphViz
import System.FilePath
doDots :: PrintDotRepr dg n => [(FilePath, dg n)] -> IO ()
doDots cases = forM_ cases createImage
createImage :: PrintDotRepr dg n => (FilePath, dg n) -> IO FilePath
createImage (n, g) = createImageInDir "/tmp" n Png g
createImageInDir :: PrintDotRepr dg n => FilePath -> FilePath -> GraphvizOutput -> dg n -> IO FilePath
createImageInDir d n o g = Data.GraphViz.addExtension (runGraphvizCommand Dot g) o (combine d n)
-- End of file.
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/paper/haroldcarr/2014-02-28-using-graphviz-via-haskell/2014-02-28-using-graphviz-via-haskell/WriteRunDot.hs | haskell | End of file. | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
Created : 2014 Feb 26 ( We d ) 18:54:30 by .
Last Modified : 2014 Mar 02 ( Sun ) 15:49:45 by .
Created : 2014 Feb 26 (Wed) 18:54:30 by Harold Carr.
Last Modified : 2014 Mar 02 (Sun) 15:49:45 by Harold Carr.
-}
module WriteRunDot where
import Control.Monad (forM_)
import Data.GraphViz
import System.FilePath
doDots :: PrintDotRepr dg n => [(FilePath, dg n)] -> IO ()
doDots cases = forM_ cases createImage
createImage :: PrintDotRepr dg n => (FilePath, dg n) -> IO FilePath
createImage (n, g) = createImageInDir "/tmp" n Png g
createImageInDir :: PrintDotRepr dg n => FilePath -> FilePath -> GraphvizOutput -> dg n -> IO FilePath
createImageInDir d n o g = Data.GraphViz.addExtension (runGraphvizCommand Dot g) o (combine d n)
|
627dfa87fa0b9bf541afdd975005a40d5c0674e9498dd4b06a86312c06afc3af | andrejv/cl-simple-tk | ex1.lisp | (defpackage :tk-user
(:use :cl :tk)
(:export :main))
(in-package :tk-user)
(defun main ()
(with-tk-root (root)
(setf (window-title root) "Example 1")
(setf (window-geometry root) "300x100+100+200")
(let ((f (frame :parent root)))
(pack f :expand t :fill "both")
(pack (button :parent f
:text "Quit"
:command (lambda ()
(window-destroy root)))
:padx 5 :pady 5 :expand t))))
| null | https://raw.githubusercontent.com/andrejv/cl-simple-tk/0ef565fedde588caa62148c2551be1520a955567/examples/ex1.lisp | lisp | (defpackage :tk-user
(:use :cl :tk)
(:export :main))
(in-package :tk-user)
(defun main ()
(with-tk-root (root)
(setf (window-title root) "Example 1")
(setf (window-geometry root) "300x100+100+200")
(let ((f (frame :parent root)))
(pack f :expand t :fill "both")
(pack (button :parent f
:text "Quit"
:command (lambda ()
(window-destroy root)))
:padx 5 :pady 5 :expand t))))
|
|
8a2471b409dbd23ddbe503f7792ece24c32cc4d57f49bf256180bfc7b03ba15f | spurious/sagittarius-scheme-mirror | types.scm | -*- mode : scheme ; coding : utf-8 ; -*-
;;;
;;; encode.scm - ASN.1 BER types
;;;
Copyright ( c ) 2009 - 2012 < >
;;;
;;; 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.
;;;
;;; 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.
;;;
(library (asn.1 ber types)
(export <ber-constructed-octet-string>
<ber-application-specific>
<ber-tagged-object>
<ber-sequence>
<ber-set>
<ber-null>
make-ber-constructed-octet-string
make-ber-application-specific
make-ber-tagged-object
make-ber-sequence
make-ber-set
make-ber-null)
(import (rnrs)
(clos user)
(clos core)
(sagittarius)
(asn.1 types)
(asn.1 der tags)
(asn.1 der encode)
(srfi :1 lists))
(define *max-length* 1000)
(define-generic make-ber-constructed-octet-string)
(define-generic make-ber-application-specific)
(define-generic make-ber-tagged-object)
(define-generic make-ber-sequence)
(define-generic make-ber-set)
(define-generic make-ber-null)
(define-class <ber-constructed-octet-string> (<der-octet-string>)
((octs :init-keyword :octs)))
(define-method make-ber-constructed-octet-string ((b <bytevector>))
(let* ((len (bytevector-length b))
(l (do ((i 0 (+ i *max-length*)) (r '()))
((>= i len) (reverse r))
(let* ((end (if (> (+ i *max-length*) len)
len
(+ i *max-length*)))
(nstr (make-bytevector (- end i))))
(bytevector-copy! b i nstr 0 (bytevector-length nstr))
(set! r (cons (make-der-octet-string nstr) r))))))
(make <ber-constructed-octet-string> :string b :octs l)))
(define-method make-ber-constructed-octet-string l
(let ((b (call-with-bytevector-output-port
(lambda (p)
(for-each (lambda (o)
(put-bytevector p (slot-ref o 'string))) l)))))
(make <ber-constructed-octet-string> :string b :octs l)))
(define-method der-encode ((o <ber-constructed-octet-string>) (p <port>))
TODO this must be separated path for DER and BER
(put-u8 p (bitwise-ior CONSTRUCTED OCTET-STRING))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'octs))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-constructed-octet-string>) (p <port>))
(der-generic-write "ber-constructed-octet-string" (slot-ref o 'string) p))
(define-class <ber-application-specific> (<der-application-specific>) ())
(define-method make-ber-application-specific ((tag <integer>) . l)
(make <ber-application-specific> :tag tag
(call-with-bytevector-output-port
(lambda (p)
(for-each (lambda (o) (der-encode o p)) l)))))
(define-class <ber-tagged-object> (<der-tagged-object>) ())
(define-method make-ber-tagged-object
((explicit? <boolean>) (tag-no <integer>) (obj <der-encodable>))
(make <ber-tagged-object>
:tag-no tag-no
:explicit? (if (is-a? obj <asn.1-choice>) #t explicit?)
:obj obj))
(define-method der-encode ((o <ber-tagged-object>) (p <port>))
TODO this must be separated path for DER and BER
(der-write-tag (bitwise-ior CONSTRUCTED TAGGED) (slot-ref o 'tag-no) p)
(put-u8 p #x80)
(unless (slot-ref o 'empty?)
(cond ((slot-ref o 'explicit?)
(der-write-object (slot-ref o 'obj) p))
(else
(let* ((obj (slot-ref o 'obj))
(e (cond
((is-a? obj <asn.1-octet-string>)
(cond ((is-a? obj <ber-constructed-octet-string>)
(slot-ref obj 'octs))
(else
(let ((bco (make-ber-constructed-octet-string
(slot-ref obj 'string))))
(slot-ref bco 'octs)))))
((is-a? obj <asn.1-sequence>) (slot-ref obj 'sequence))
((is-a? obj <asn.1-set>) (slot-ref obj 'set))
(else
(assertion-violation 'der-encode
"not implemented" obj)))))
(for-each (lambda (o) (der-write-object o p)) e)))))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-tagged-object>) (p <port>))
(der-generic-write "ber-tagged-object"
(format "[~a] ~a~a" (slot-ref o 'tag-no)
(slot-ref o 'explicit?)
(der-list->string
(list (slot-ref o 'obj))))
p))
(define-class <ber-sequence> (<der-sequence>) ())
(define-method make-ber-sequence l
(or (for-all (lambda (o) (is-a? o <der-encodable>)) l)
(assertion-violation 'make-ber-sequcne
"list of <der-encodable> required" l))
(make <ber-sequence> :sequence l))
(define-method der-encode ((o <ber-sequence>) (p <port>))
(put-u8 p (bitwise-ior SEQUENCE CONSTRUCTED))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'sequence))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-sequence>) (p <port>))
(der-generic-write "ber-sequence" (der-list->string (slot-ref o 'sequence)) p))
(define-class <ber-set> (<der-set>) ())
(define-method make-ber-set l
(or (for-all (lambda (o) (is-a? o <der-encodable>)) l)
(assertion-violation 'make-ber-sequcne
"list of <der-encodable> required" l))
(make <ber-set> :sequence l :need-sort? #f))
(define-method der-encode ((o <ber-set>) (p <port>))
(put-u8 p (bitwise-ior SET CONSTRUCTED))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'sequence))
(put-u8 p #x00)
(put-u8 p #x00)
)
(define-method write-object ((o <ber-set>) (p <port>))
(der-generic-write "ber-set" (der-list->string (slot-ref o 'set)) p))
(define-class <ber-null> (<der-null>) ())
(define *ber-null* (make <ber-null>))
(define-method make-ber-null () *ber-null*)
(define-method der-encode ((o <ber-null>) (p <port>))
(put-u8 p NULL))
(define-method write-object ((o <ber-null>) (p <port>))
(der-generic-write "ber-null" "" p))
)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/asn.1/ber/types.scm | scheme | coding : utf-8 ; -*-
encode.scm - ASN.1 BER types
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
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 ) 2009 - 2012 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(library (asn.1 ber types)
(export <ber-constructed-octet-string>
<ber-application-specific>
<ber-tagged-object>
<ber-sequence>
<ber-set>
<ber-null>
make-ber-constructed-octet-string
make-ber-application-specific
make-ber-tagged-object
make-ber-sequence
make-ber-set
make-ber-null)
(import (rnrs)
(clos user)
(clos core)
(sagittarius)
(asn.1 types)
(asn.1 der tags)
(asn.1 der encode)
(srfi :1 lists))
(define *max-length* 1000)
(define-generic make-ber-constructed-octet-string)
(define-generic make-ber-application-specific)
(define-generic make-ber-tagged-object)
(define-generic make-ber-sequence)
(define-generic make-ber-set)
(define-generic make-ber-null)
(define-class <ber-constructed-octet-string> (<der-octet-string>)
((octs :init-keyword :octs)))
(define-method make-ber-constructed-octet-string ((b <bytevector>))
(let* ((len (bytevector-length b))
(l (do ((i 0 (+ i *max-length*)) (r '()))
((>= i len) (reverse r))
(let* ((end (if (> (+ i *max-length*) len)
len
(+ i *max-length*)))
(nstr (make-bytevector (- end i))))
(bytevector-copy! b i nstr 0 (bytevector-length nstr))
(set! r (cons (make-der-octet-string nstr) r))))))
(make <ber-constructed-octet-string> :string b :octs l)))
(define-method make-ber-constructed-octet-string l
(let ((b (call-with-bytevector-output-port
(lambda (p)
(for-each (lambda (o)
(put-bytevector p (slot-ref o 'string))) l)))))
(make <ber-constructed-octet-string> :string b :octs l)))
(define-method der-encode ((o <ber-constructed-octet-string>) (p <port>))
TODO this must be separated path for DER and BER
(put-u8 p (bitwise-ior CONSTRUCTED OCTET-STRING))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'octs))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-constructed-octet-string>) (p <port>))
(der-generic-write "ber-constructed-octet-string" (slot-ref o 'string) p))
(define-class <ber-application-specific> (<der-application-specific>) ())
(define-method make-ber-application-specific ((tag <integer>) . l)
(make <ber-application-specific> :tag tag
(call-with-bytevector-output-port
(lambda (p)
(for-each (lambda (o) (der-encode o p)) l)))))
(define-class <ber-tagged-object> (<der-tagged-object>) ())
(define-method make-ber-tagged-object
((explicit? <boolean>) (tag-no <integer>) (obj <der-encodable>))
(make <ber-tagged-object>
:tag-no tag-no
:explicit? (if (is-a? obj <asn.1-choice>) #t explicit?)
:obj obj))
(define-method der-encode ((o <ber-tagged-object>) (p <port>))
TODO this must be separated path for DER and BER
(der-write-tag (bitwise-ior CONSTRUCTED TAGGED) (slot-ref o 'tag-no) p)
(put-u8 p #x80)
(unless (slot-ref o 'empty?)
(cond ((slot-ref o 'explicit?)
(der-write-object (slot-ref o 'obj) p))
(else
(let* ((obj (slot-ref o 'obj))
(e (cond
((is-a? obj <asn.1-octet-string>)
(cond ((is-a? obj <ber-constructed-octet-string>)
(slot-ref obj 'octs))
(else
(let ((bco (make-ber-constructed-octet-string
(slot-ref obj 'string))))
(slot-ref bco 'octs)))))
((is-a? obj <asn.1-sequence>) (slot-ref obj 'sequence))
((is-a? obj <asn.1-set>) (slot-ref obj 'set))
(else
(assertion-violation 'der-encode
"not implemented" obj)))))
(for-each (lambda (o) (der-write-object o p)) e)))))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-tagged-object>) (p <port>))
(der-generic-write "ber-tagged-object"
(format "[~a] ~a~a" (slot-ref o 'tag-no)
(slot-ref o 'explicit?)
(der-list->string
(list (slot-ref o 'obj))))
p))
(define-class <ber-sequence> (<der-sequence>) ())
(define-method make-ber-sequence l
(or (for-all (lambda (o) (is-a? o <der-encodable>)) l)
(assertion-violation 'make-ber-sequcne
"list of <der-encodable> required" l))
(make <ber-sequence> :sequence l))
(define-method der-encode ((o <ber-sequence>) (p <port>))
(put-u8 p (bitwise-ior SEQUENCE CONSTRUCTED))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'sequence))
(put-u8 p #x00)
(put-u8 p #x00))
(define-method write-object ((o <ber-sequence>) (p <port>))
(der-generic-write "ber-sequence" (der-list->string (slot-ref o 'sequence)) p))
(define-class <ber-set> (<der-set>) ())
(define-method make-ber-set l
(or (for-all (lambda (o) (is-a? o <der-encodable>)) l)
(assertion-violation 'make-ber-sequcne
"list of <der-encodable> required" l))
(make <ber-set> :sequence l :need-sort? #f))
(define-method der-encode ((o <ber-set>) (p <port>))
(put-u8 p (bitwise-ior SET CONSTRUCTED))
(put-u8 p #x80)
(for-each (lambda (o) (der-write-object o p)) (slot-ref o 'sequence))
(put-u8 p #x00)
(put-u8 p #x00)
)
(define-method write-object ((o <ber-set>) (p <port>))
(der-generic-write "ber-set" (der-list->string (slot-ref o 'set)) p))
(define-class <ber-null> (<der-null>) ())
(define *ber-null* (make <ber-null>))
(define-method make-ber-null () *ber-null*)
(define-method der-encode ((o <ber-null>) (p <port>))
(put-u8 p NULL))
(define-method write-object ((o <ber-null>) (p <port>))
(der-generic-write "ber-null" "" p))
)
|
978cd33f94983314ef60e2988f5df3aea1242a7b9b8c97399783aec63704c51d | ocaml-community/obus | oBus_resolver.mli |
* oBus_resolver.mli
* -----------------
* Copyright : ( c ) 2008 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* oBus_resolver.mli
* -----------------
* Copyright : (c) 2008, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
(** Bus name resolving *)
* This module implements bus name resolving and monitoring .
- for a unique connection name , it means being notified when the
peer owning this name exits
- for a well - known name such as " org.domain . Serivce " it means
knowing at each time who is the current owner and being notified
when the service owner changes ( i.e. the process implementing the
service change ) .
It is basically an abstraction for { ! OBus_bus.get_owner } and
{ ! OBus_bus.name_owner_changed } . You should prefer using it instead
of implementing your own name monitoring because resolver are
shared and obus internally uses them , so this avoids extra messages .
Note that with a peer - to - peer connection , resolver will always act
as if there is no owner .
- for a unique connection name, it means being notified when the
peer owning this name exits
- for a well-known name such as "org.domain.Serivce" it means
knowing at each time who is the current owner and being notified
when the service owner changes (i.e. the process implementing the
service change).
It is basically an abstraction for {!OBus_bus.get_owner} and
{!OBus_bus.name_owner_changed}. You should prefer using it instead
of implementing your own name monitoring because resolver are
shared and obus internally uses them, so this avoids extra messages.
Note that with a peer-to-peer connection, resolver will always act
as if there is no owner. *)
val make : ?switch : Lwt_switch.t -> OBus_connection.t -> OBus_name.bus -> OBus_name.bus React.signal Lwt.t
(** [make ?switch bus name] creates a resolver which will monitor
the name [name] on [bus]. It returns a signal holding the
current owner of the name. It holds [""] when there is no
owner. *)
| null | https://raw.githubusercontent.com/ocaml-community/obus/8d38ee6750587ae6519644630b75d53a0a011acd/src/protocol/oBus_resolver.mli | ocaml | * Bus name resolving
* [make ?switch bus name] creates a resolver which will monitor
the name [name] on [bus]. It returns a signal holding the
current owner of the name. It holds [""] when there is no
owner. |
* oBus_resolver.mli
* -----------------
* Copyright : ( c ) 2008 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* oBus_resolver.mli
* -----------------
* Copyright : (c) 2008, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
* This module implements bus name resolving and monitoring .
- for a unique connection name , it means being notified when the
peer owning this name exits
- for a well - known name such as " org.domain . Serivce " it means
knowing at each time who is the current owner and being notified
when the service owner changes ( i.e. the process implementing the
service change ) .
It is basically an abstraction for { ! OBus_bus.get_owner } and
{ ! OBus_bus.name_owner_changed } . You should prefer using it instead
of implementing your own name monitoring because resolver are
shared and obus internally uses them , so this avoids extra messages .
Note that with a peer - to - peer connection , resolver will always act
as if there is no owner .
- for a unique connection name, it means being notified when the
peer owning this name exits
- for a well-known name such as "org.domain.Serivce" it means
knowing at each time who is the current owner and being notified
when the service owner changes (i.e. the process implementing the
service change).
It is basically an abstraction for {!OBus_bus.get_owner} and
{!OBus_bus.name_owner_changed}. You should prefer using it instead
of implementing your own name monitoring because resolver are
shared and obus internally uses them, so this avoids extra messages.
Note that with a peer-to-peer connection, resolver will always act
as if there is no owner. *)
val make : ?switch : Lwt_switch.t -> OBus_connection.t -> OBus_name.bus -> OBus_name.bus React.signal Lwt.t
|
1122198f425c6be3c0fd64355d2f828bf882b071a74a762624160b23e49c7ca2 | rd--/hsc3 | tDelay.help.hs | -- tDelay
let z = impulse ar 2 0
z' = tDelay z 0.5
o = sinOsc ar 440 0 * 0.1
in mce [z * 0.1,toggleFF z' * o]
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/tDelay.help.hs | haskell | tDelay | let z = impulse ar 2 0
z' = tDelay z 0.5
o = sinOsc ar 440 0 * 0.1
in mce [z * 0.1,toggleFF z' * o]
|
a6cbeb16032b72ea4a5852433af9bb8abfe5f6d052cc7d242fbf0c43e8fd1199 | audreyt/openafp-utils | afp-split-scb.hs | module Main where
import OpenAFP
import System.Exit
import Data.Char (isDigit, isAlphaNum)
import Data.List (find)
import qualified Data.ByteString.Char8 as C
-- Algorithm:
Gather everything up to first BPG
write out each BPG / EPG chunks
append ENG+EDT
main :: IO ()
main = do
args <- getArgs
if null args then error "Usage: afp-split-scb file.afp [pages]" else do
let (inFile:outPages) = args
cs <- readAFP inFile
let (preamble:rest) = splitPages cs
_eng = encodeChunk $ Record _ENG
_edt = encodeChunk $ Record _EDT
pagePairs = map show [1..] `zip` rest
if null outPages
then forM_ pagePairs $ \(i, page) -> do
let Just tle = find (~~ _TLE) page
Just (_:av:_) = tle_Chunks `applyToChunk` tle
Just str = t_av `applyToChunk` av
pgs = filter (~~ _BPG) page
--
Just seg = find (~~ _IPS) page
Just name = ips `applyToChunk` seg
--
outFile = inFile
++ ('.':filter isDigit (fromAStr str))
++ ('.':takeWhile isAlphaNum (fromAStr name))
++ ('.':i)
++ ('.':show (length pgs))
putStrLn outFile
writeAFP outFile $ preamble ++ page ++ [_eng, _edt]
else do
let outFile = inFile ++ ".part"
writeAFP outFile $ preamble ++ concat [ page | (i, page) <- pagePairs, i `elem` outPages ] ++ [_eng, _edt]
putStrLn outFile
splitPages :: [AFP_] -> [[AFP_]]
splitPages cs = if null rest then [this] else case splitPages rest' of
[] -> [this, rest]
(y:ys) -> (this:(begins ++ y):ys)
where
(this, rest) = break isBeginPage cs
(begins, rest') = span isBeginPage rest
isBeginPage :: AFP_ -> Bool
isBeginPage t = (t ~~ _BNG)
| null | https://raw.githubusercontent.com/audreyt/openafp-utils/cbc59144e07638ba9f34685aba77c867e1a766ac/afp-split-scb.hs | haskell | Algorithm:
| module Main where
import OpenAFP
import System.Exit
import Data.Char (isDigit, isAlphaNum)
import Data.List (find)
import qualified Data.ByteString.Char8 as C
Gather everything up to first BPG
write out each BPG / EPG chunks
append ENG+EDT
main :: IO ()
main = do
args <- getArgs
if null args then error "Usage: afp-split-scb file.afp [pages]" else do
let (inFile:outPages) = args
cs <- readAFP inFile
let (preamble:rest) = splitPages cs
_eng = encodeChunk $ Record _ENG
_edt = encodeChunk $ Record _EDT
pagePairs = map show [1..] `zip` rest
if null outPages
then forM_ pagePairs $ \(i, page) -> do
let Just tle = find (~~ _TLE) page
Just (_:av:_) = tle_Chunks `applyToChunk` tle
Just str = t_av `applyToChunk` av
pgs = filter (~~ _BPG) page
Just seg = find (~~ _IPS) page
Just name = ips `applyToChunk` seg
outFile = inFile
++ ('.':filter isDigit (fromAStr str))
++ ('.':takeWhile isAlphaNum (fromAStr name))
++ ('.':i)
++ ('.':show (length pgs))
putStrLn outFile
writeAFP outFile $ preamble ++ page ++ [_eng, _edt]
else do
let outFile = inFile ++ ".part"
writeAFP outFile $ preamble ++ concat [ page | (i, page) <- pagePairs, i `elem` outPages ] ++ [_eng, _edt]
putStrLn outFile
splitPages :: [AFP_] -> [[AFP_]]
splitPages cs = if null rest then [this] else case splitPages rest' of
[] -> [this, rest]
(y:ys) -> (this:(begins ++ y):ys)
where
(this, rest) = break isBeginPage cs
(begins, rest') = span isBeginPage rest
isBeginPage :: AFP_ -> Bool
isBeginPage t = (t ~~ _BNG)
|
d453183e880f2f4dee3e68e955603f122be6b732bc7d55eea7a9e6a57f3b60b1 | stepcut/plugins | Plugin.hs | --
-- Plugin
--
module Plugin where
import API
import Modules.Flags as Flags
resource = plugin {
dbFunc = (\x -> Flags.f1 x)
}
| null | https://raw.githubusercontent.com/stepcut/plugins/52c660b5bc71182627d14c1d333d0234050cac01/testsuite/hier/hier1/Plugin.hs | haskell |
Plugin
|
module Plugin where
import API
import Modules.Flags as Flags
resource = plugin {
dbFunc = (\x -> Flags.f1 x)
}
|
9a8f0fb440c6dc509d31bbc0a00c8cb014a2073fff9c78dab4595f96c9b63f55 | libguestfs/virt-v2v | create_libvirt_xml.mli | virt - v2v
* Copyright ( C ) 2009 - 2020 Red Hat Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License along
* with this program ; if not , write to the Free Software Foundation , Inc. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2009-2020 Red Hat Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
(** Create libvirt XML for [-o libvirt] and [-o local]. *)
val create_libvirt_xml : ?pool:string -> Types.source ->
Types.inspect -> Types.target_meta ->
string list -> (int -> string) -> string -> string ->
DOM.doc
* [ create_libvirt_xml ? pool source inspect target_meta
target_features outdisk_map output_format output_name ]
creates the final libvirt XML for the output hypervisor .
target_features outdisk_map output_format output_name]
creates the final libvirt XML for the output hypervisor. *)
| null | https://raw.githubusercontent.com/libguestfs/virt-v2v/c331654848f9abdb6edb93cec54bf410c9f6ccd0/output/create_libvirt_xml.mli | ocaml | * Create libvirt XML for [-o libvirt] and [-o local]. | virt - v2v
* Copyright ( C ) 2009 - 2020 Red Hat Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License along
* with this program ; if not , write to the Free Software Foundation , Inc. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2009-2020 Red Hat Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
val create_libvirt_xml : ?pool:string -> Types.source ->
Types.inspect -> Types.target_meta ->
string list -> (int -> string) -> string -> string ->
DOM.doc
* [ create_libvirt_xml ? pool source inspect target_meta
target_features outdisk_map output_format output_name ]
creates the final libvirt XML for the output hypervisor .
target_features outdisk_map output_format output_name]
creates the final libvirt XML for the output hypervisor. *)
|
bce3fbbf3fde8c20dac6efe2cfd255c4efcd6fe2b52cffc0a912ae98947be2db | janestreet/async_unix | assign_try_with_log_exn.ml | open! Core
open! Async_kernel
open! Import
We want to get a log of errors sent to [ Monitor.try_with ] after the initial return , so
on initialization we redirect them to [ Log.Global.error ] . However , logging errors
is n't cheap and there are issues with thread fairness when outputting to stderr ( which
is the default in many cases for [ Global.error ] ) , so , to prevent the [ Log ] [ Writer.t ]
buffer from growing without bound , we limit the number of currently unflushed error
messages created by [ try_with_log_exn ] .
on initialization we redirect them to [Log.Global.error]. However, logging errors
isn't cheap and there are issues with thread fairness when outputting to stderr (which
is the default in many cases for [Global.error]), so, to prevent the [Log] [Writer.t]
buffer from growing without bound, we limit the number of currently unflushed error
messages created by [try_with_log_exn]. *)
let try_with_log_exn =
let max_unflushed_errors = 10 in
let current_unflushed_errors = ref 0 in
let log sexp = Log.Global.sexp sexp ~level:`Error in
fun exn ->
if !current_unflushed_errors < max_unflushed_errors
then (
incr current_unflushed_errors;
log
[%message
"Exception raised to [Monitor.try_with] that already returned."
"This error was captured by a default handler in [Async.Log]."
(exn : exn)];
if !current_unflushed_errors = max_unflushed_errors
then
log
[%message
"Stopped logging exceptions raised to [Monitor.try_with] that already \
returned until error log can be flushed."];
upon (Log.Global.flushed ()) (fun () -> decr current_unflushed_errors))
;;
let () = Async_kernel.Monitor.Expert.try_with_log_exn := try_with_log_exn
| null | https://raw.githubusercontent.com/janestreet/async_unix/2562a6b9316d7c6757726305482380bd7e6dba06/src/assign_try_with_log_exn.ml | ocaml | open! Core
open! Async_kernel
open! Import
We want to get a log of errors sent to [ Monitor.try_with ] after the initial return , so
on initialization we redirect them to [ Log.Global.error ] . However , logging errors
is n't cheap and there are issues with thread fairness when outputting to stderr ( which
is the default in many cases for [ Global.error ] ) , so , to prevent the [ Log ] [ Writer.t ]
buffer from growing without bound , we limit the number of currently unflushed error
messages created by [ try_with_log_exn ] .
on initialization we redirect them to [Log.Global.error]. However, logging errors
isn't cheap and there are issues with thread fairness when outputting to stderr (which
is the default in many cases for [Global.error]), so, to prevent the [Log] [Writer.t]
buffer from growing without bound, we limit the number of currently unflushed error
messages created by [try_with_log_exn]. *)
let try_with_log_exn =
let max_unflushed_errors = 10 in
let current_unflushed_errors = ref 0 in
let log sexp = Log.Global.sexp sexp ~level:`Error in
fun exn ->
if !current_unflushed_errors < max_unflushed_errors
then (
incr current_unflushed_errors;
log
[%message
"Exception raised to [Monitor.try_with] that already returned."
"This error was captured by a default handler in [Async.Log]."
(exn : exn)];
if !current_unflushed_errors = max_unflushed_errors
then
log
[%message
"Stopped logging exceptions raised to [Monitor.try_with] that already \
returned until error log can be flushed."];
upon (Log.Global.flushed ()) (fun () -> decr current_unflushed_errors))
;;
let () = Async_kernel.Monitor.Expert.try_with_log_exn := try_with_log_exn
|
|
fca21fe0bf8f853142b5f8a70b019257cc27a9d9500664f8770b8805b6e7a144 | poroh/ersip_proxy | erproxy_listener_sup.erl | %%
Copyright ( c ) 2018 Dmitry Poroh
%% All rights reserved.
Distributed under the terms of the MIT License . See the LICENSE file .
%%
%% Stateless proxy worker supervisor
%%
-module(erproxy_listener_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%%====================================================================
%% API functions
%%====================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%%====================================================================
%% Supervisor callbacks
%%====================================================================
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
SupFlags = #{
strategy => one_for_one,
intensity => 5,
period => 10
},
Listeners = application:get_env(erproxy, listeners, []),
ChildSpecs = [
#{
id => Id,
start => {erproxy_listener, start_link, [Config]},
type => supervisor
}
|| {Id, Config} <- Listeners
],
{ok, {SupFlags, ChildSpecs}}.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/poroh/ersip_proxy/8a67e676e255c07a63b88b970ef82ed4762debcb/apps/erproxy/src/erproxy_listener_sup.erl | erlang |
All rights reserved.
Stateless proxy worker supervisor
API
Supervisor callbacks
====================================================================
API functions
====================================================================
====================================================================
Supervisor callbacks
====================================================================
====================================================================
==================================================================== | Copyright ( c ) 2018 Dmitry Poroh
Distributed under the terms of the MIT License . See the LICENSE file .
-module(erproxy_listener_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules }
init([]) ->
SupFlags = #{
strategy => one_for_one,
intensity => 5,
period => 10
},
Listeners = application:get_env(erproxy, listeners, []),
ChildSpecs = [
#{
id => Id,
start => {erproxy_listener, start_link, [Config]},
type => supervisor
}
|| {Id, Config} <- Listeners
],
{ok, {SupFlags, ChildSpecs}}.
Internal functions
|
11a14529a87f9837e0ac4e7ea0b8e85ac70bd8941c2d01e18a8aa33a9255f4c0 | dselsam/arc | Spec.hs | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE StrictData #-}
module Synth.Spec where
import Util.Imports
import Search.SearchT
import Search.DFS
import Synth.ExInfo (ExInfo(ExInfo))
import Synth.Ex (Ex(Ex), ForTrain, ForTest)
import qualified Synth.Ex as Ex
type ReconstructFn a b = Ex a -> Maybe (Ex b)
type SynthFn m spec ctx a = spec ctx a -> SearchT m (Ex a)
type SynthFn1 m s1 c1 a1 s2 c2 a2 = s1 c1 a1 -> SearchT m (s2 c2 a2, ReconstructFn a2 a1)
class Spec spec ctx a where
info :: spec ctx a -> ExInfo
ctx :: spec ctx a -> ctx
check :: spec ctx a -> Ex a -> Bool
| null | https://raw.githubusercontent.com/dselsam/arc/7e68a7ed9508bf26926b0f68336db05505f4e765/src/Synth/Spec.hs | haskell | # LANGUAGE StrictData # | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
module Synth.Spec where
import Util.Imports
import Search.SearchT
import Search.DFS
import Synth.ExInfo (ExInfo(ExInfo))
import Synth.Ex (Ex(Ex), ForTrain, ForTest)
import qualified Synth.Ex as Ex
type ReconstructFn a b = Ex a -> Maybe (Ex b)
type SynthFn m spec ctx a = spec ctx a -> SearchT m (Ex a)
type SynthFn1 m s1 c1 a1 s2 c2 a2 = s1 c1 a1 -> SearchT m (s2 c2 a2, ReconstructFn a2 a1)
class Spec spec ctx a where
info :: spec ctx a -> ExInfo
ctx :: spec ctx a -> ctx
check :: spec ctx a -> Ex a -> Bool
|
c74509d009238e431bb8d2e7b0ac7a9e54f5e98b38c88f9d824e9173aa956875 | clojure/tools.gitlibs | test_impl.clj | (ns clojure.tools.gitlibs.test-impl
(:require
[clojure.test :refer :all]
[clojure.tools.gitlibs.impl :as impl]))
(deftest test-clean-url
(are [url expected-path]
(= expected-path (#'impl/clean-url url))
;; url formats - don't use user or port
"ssh://:3333/org/repo.git" "ssh/gitlab.com/org/repo"
"ssh" "ssh/gitlab.org.net/org/repo"
"ssh:///~user/repo.git/" "ssh/host.xz/_TILDE_user/repo"
"" "https/github.com/org/repo"
"git/" "git/host.xz/path/to/repo"
;; scp style url (most common github ssh url format)
":org/repo.git" "ssh/github.com/org/repo"
":dotted.org/dotted.repo.git" "ssh/github.com/dotted.org/dotted.repo"
"host.xz:~user/path/to/repo.git/" "ssh/host.xz/_TILDE_user/path/to/repo"
;; file scheme
"file" "file/Users/me/code/repo"
"file" "file/REL/_DOTDOT_/foo"
"file://~/path/repo.git" "file/REL/_TILDE_/path/repo"
;; file repos - handle relative vs absolute, handle . .. ~
"/Users/me/code/repo.git" "file/Users/me/code/repo"
"../foo.git" "file/REL/_DOTDOT_/foo"
"./foo.git" "file/REL/_DOT_/foo"
"~user/foo.git" "file/REL/_TILDE_user/foo"
git - unknown transport with url rewrite in gitconfig ( unusual , but do something useful )
"work:repo.git" "ssh/work/repo"))
| null | https://raw.githubusercontent.com/clojure/tools.gitlibs/8b699c68573d501bc49be6c805a17da1094ac1b2/src/test/clojure/clojure/tools/gitlibs/test_impl.clj | clojure | url formats - don't use user or port
scp style url (most common github ssh url format)
file scheme
file repos - handle relative vs absolute, handle . .. ~ | (ns clojure.tools.gitlibs.test-impl
(:require
[clojure.test :refer :all]
[clojure.tools.gitlibs.impl :as impl]))
(deftest test-clean-url
(are [url expected-path]
(= expected-path (#'impl/clean-url url))
"ssh://:3333/org/repo.git" "ssh/gitlab.com/org/repo"
"ssh" "ssh/gitlab.org.net/org/repo"
"ssh:///~user/repo.git/" "ssh/host.xz/_TILDE_user/repo"
"" "https/github.com/org/repo"
"git/" "git/host.xz/path/to/repo"
":org/repo.git" "ssh/github.com/org/repo"
":dotted.org/dotted.repo.git" "ssh/github.com/dotted.org/dotted.repo"
"host.xz:~user/path/to/repo.git/" "ssh/host.xz/_TILDE_user/path/to/repo"
"file" "file/Users/me/code/repo"
"file" "file/REL/_DOTDOT_/foo"
"file://~/path/repo.git" "file/REL/_TILDE_/path/repo"
"/Users/me/code/repo.git" "file/Users/me/code/repo"
"../foo.git" "file/REL/_DOTDOT_/foo"
"./foo.git" "file/REL/_DOT_/foo"
"~user/foo.git" "file/REL/_TILDE_user/foo"
git - unknown transport with url rewrite in gitconfig ( unusual , but do something useful )
"work:repo.git" "ssh/work/repo"))
|
540d8a74f64fba32487b4323b4d2dce1053ee5ed1cf6a39b2a446a3e0de09662 | javalib-team/sawja | wlist.mli |
* This file is part of SAWJA
* Copyright ( c)2009 ( INRIA )
*
* This program is free software : you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation , either version 3 of
* the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* General Public License for more details .
*
* You should have received a copy of the GNU General Public
* License along with this program . If not , see
* < / > .
* This file is part of SAWJA
* Copyright (c)2009 Nicolas Barre (INRIA)
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* </>.
*)
(** A growable when itering list. *)
(* TODO : add documentation *)
type 'a wlist
type 'a tail
* { 2 Basic operations . }
val create : unit -> 'a wlist
val tail : 'a wlist -> 'a tail
val add : 'a -> 'a wlist -> unit
val iter_to_head : ('a -> unit) -> 'a tail -> unit
val size : 'a wlist -> int
| null | https://raw.githubusercontent.com/javalib-team/sawja/da39f9c1c4fc52a1a1a6350be0e39789812b6c00/src/wlist.mli | ocaml | * A growable when itering list.
TODO : add documentation |
* This file is part of SAWJA
* Copyright ( c)2009 ( INRIA )
*
* This program is free software : you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation , either version 3 of
* the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* General Public License for more details .
*
* You should have received a copy of the GNU General Public
* License along with this program . If not , see
* < / > .
* This file is part of SAWJA
* Copyright (c)2009 Nicolas Barre (INRIA)
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* </>.
*)
type 'a wlist
type 'a tail
* { 2 Basic operations . }
val create : unit -> 'a wlist
val tail : 'a wlist -> 'a tail
val add : 'a -> 'a wlist -> unit
val iter_to_head : ('a -> unit) -> 'a tail -> unit
val size : 'a wlist -> int
|
79c2617a699ffb1b25cc74a6341a64daa84f7a68020fe97035fdafa48ba508e7 | c4-project/c4f | thread.mli | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
* : thread contexts .
open Base
open Import
(** Type of thread context. *)
type t = {tid: int; locals: Set.M(Common.C_id).t}
val when_local :
t
-> 'a
-> over:(unit, Common.C_id.t, 'a, getter) Accessor.t
-> f:('a -> 'a Or_error.t)
-> 'a Or_error.t
(** [when_local t x ~over ~f] returns [f x] when [x.@(over)] is local in [t],
and [x] otherwise. *)
val when_global :
t
-> 'a
-> over:(unit, Common.C_id.t, 'a, getter) Accessor.t
-> f:('a -> 'a Or_error.t)
-> 'a Or_error.t
(** [when_local t x ~over ~f] returns [x] when [x.@(over)] is local in [t],
and [f x] otherwise. *)
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/delitmus/src/thread.mli | ocaml | * Type of thread context.
* [when_local t x ~over ~f] returns [f x] when [x.@(over)] is local in [t],
and [x] otherwise.
* [when_local t x ~over ~f] returns [x] when [x.@(over)] is local in [t],
and [f x] otherwise. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
* : thread contexts .
open Base
open Import
type t = {tid: int; locals: Set.M(Common.C_id).t}
val when_local :
t
-> 'a
-> over:(unit, Common.C_id.t, 'a, getter) Accessor.t
-> f:('a -> 'a Or_error.t)
-> 'a Or_error.t
val when_global :
t
-> 'a
-> over:(unit, Common.C_id.t, 'a, getter) Accessor.t
-> f:('a -> 'a Or_error.t)
-> 'a Or_error.t
|
788e1cdaf3b5380cbff19b71ec4e2e60d6bb7d1b0af8a9e8e5d696de33b9f28c | jlahd/cacle | testsuite.lisp | (in-package :cacle)
#+5am
(5am:def-suite cacle-tests :description "cacle test suite")
#+5am
(5am:in-suite cacle-tests)
#+5am
(defmacro with-testing-cache ((var size &key policy lifetime item-size-modulus without-cleanup (cleanup-checks t)) &body body)
(let ((provider (gensym))
(cleanup (gensym))
(object (gensym))
(lock (gensym))
(arg (gensym)))
`(let ((,object 0)
(,lock (bt:make-lock "mutex for with-testing-cache")))
(flet ((,provider (,arg)
(bt:with-lock-held (,lock)
(values (list ,arg (incf ,object)) ,(if item-size-modulus
`(mod ,arg ,item-size-modulus)
arg))))
,@(and (not without-cleanup)
`((,cleanup (,arg)
,@(when cleanup-checks
`((5am:is (listp ,arg))
(5am:is (= 2 (length ,arg)))))
(setf (cdr ,arg) (list :cleaned-up (second ,arg))))
(fetch-and-release (cache key)
(multiple-value-bind (item tag)
(cache-fetch cache key)
(cache-release cache tag)
item))
(cleaned-up-p (,arg)
(cond ((eq (second ,arg) :cleaned-up)
t)
((integerp (second ,arg))
nil)
(t
(error "Corrupted cache data ~s" ,arg)))))))
(let ((,var (make-cache ,size #',provider
:policy (or ,policy :fifo)
,@(and (not without-cleanup)
`(:cleanup #',cleanup))
,@(and lifetime
`(:lifetime ,lifetime)))))
,@body)))))
#+5am
(5am:test bélády-replacement-policy
(5am:signals error (make-cache 100 #'list :policy :bélády)))
#+5am
(5am:test random-single-thread-testing
(let ((repetitions 100000))
(dolist (policy '(:fifo :lifo :lru :mru :random :lfu :lfuda))
(with-testing-cache (cache 1000 :policy policy :cleanup-checks nil)
(dotimes (i repetitions)
(let* ((key (1+ (random 100))))
(multiple-value-bind (data tag)
(cache-fetch cache key)
(unless (= (first data) key)
(5am:fail "attempt to fetch data for key ~a resulted in ~s" key data))
(cache-release cache tag))))
(5am:is (> (cache-size cache) 900))
(5am:is (> (cache-count cache) 10))
(handler-case
(cache-sanity-check cache)
(error (e)
(error "With policy ~a: ~a" policy e)))))))
#+5am
(5am:test random-multi-thread-testing
(let ((threads 4)
(repetitions 25000))
(dolist (policy '(:fifo :lifo :lru :mru :random :lfu :lfuda))
(with-testing-cache (cache 1000 :policy policy :cleanup-checks nil)
(let* ((out *standard-output*)
(threads (loop for i below threads
collect (bt:make-thread
#'(lambda ()
(let ((ok t))
(dotimes (i repetitions)
(let* ((key (1+ (random 100))))
(multiple-value-bind (data tag)
(cache-fetch cache key)
(unless (and (= (first data) key)
(not (cleaned-up-p data)))
(setf ok nil)
(format out "~%attempt to fetch data for key ~a resulted in ~s" key data)
(return))
(cache-release cache tag))))
ok))))))
(5am:is (zerop (count-if-not #'identity (mapcar #'bt:join-thread threads)))))
(5am:is (> (cache-size cache) 900))
(5am:is (> (cache-count cache) 10))
(handler-case
(cache-sanity-check cache)
(error (e)
(error "With policy ~a: ~a" policy e)))))))
| null | https://raw.githubusercontent.com/jlahd/cacle/4cbe8cfe227d2e097eaced14766f4f37aa05e617/src/testsuite.lisp | lisp | (in-package :cacle)
#+5am
(5am:def-suite cacle-tests :description "cacle test suite")
#+5am
(5am:in-suite cacle-tests)
#+5am
(defmacro with-testing-cache ((var size &key policy lifetime item-size-modulus without-cleanup (cleanup-checks t)) &body body)
(let ((provider (gensym))
(cleanup (gensym))
(object (gensym))
(lock (gensym))
(arg (gensym)))
`(let ((,object 0)
(,lock (bt:make-lock "mutex for with-testing-cache")))
(flet ((,provider (,arg)
(bt:with-lock-held (,lock)
(values (list ,arg (incf ,object)) ,(if item-size-modulus
`(mod ,arg ,item-size-modulus)
arg))))
,@(and (not without-cleanup)
`((,cleanup (,arg)
,@(when cleanup-checks
`((5am:is (listp ,arg))
(5am:is (= 2 (length ,arg)))))
(setf (cdr ,arg) (list :cleaned-up (second ,arg))))
(fetch-and-release (cache key)
(multiple-value-bind (item tag)
(cache-fetch cache key)
(cache-release cache tag)
item))
(cleaned-up-p (,arg)
(cond ((eq (second ,arg) :cleaned-up)
t)
((integerp (second ,arg))
nil)
(t
(error "Corrupted cache data ~s" ,arg)))))))
(let ((,var (make-cache ,size #',provider
:policy (or ,policy :fifo)
,@(and (not without-cleanup)
`(:cleanup #',cleanup))
,@(and lifetime
`(:lifetime ,lifetime)))))
,@body)))))
#+5am
(5am:test bélády-replacement-policy
(5am:signals error (make-cache 100 #'list :policy :bélády)))
#+5am
(5am:test random-single-thread-testing
(let ((repetitions 100000))
(dolist (policy '(:fifo :lifo :lru :mru :random :lfu :lfuda))
(with-testing-cache (cache 1000 :policy policy :cleanup-checks nil)
(dotimes (i repetitions)
(let* ((key (1+ (random 100))))
(multiple-value-bind (data tag)
(cache-fetch cache key)
(unless (= (first data) key)
(5am:fail "attempt to fetch data for key ~a resulted in ~s" key data))
(cache-release cache tag))))
(5am:is (> (cache-size cache) 900))
(5am:is (> (cache-count cache) 10))
(handler-case
(cache-sanity-check cache)
(error (e)
(error "With policy ~a: ~a" policy e)))))))
#+5am
(5am:test random-multi-thread-testing
(let ((threads 4)
(repetitions 25000))
(dolist (policy '(:fifo :lifo :lru :mru :random :lfu :lfuda))
(with-testing-cache (cache 1000 :policy policy :cleanup-checks nil)
(let* ((out *standard-output*)
(threads (loop for i below threads
collect (bt:make-thread
#'(lambda ()
(let ((ok t))
(dotimes (i repetitions)
(let* ((key (1+ (random 100))))
(multiple-value-bind (data tag)
(cache-fetch cache key)
(unless (and (= (first data) key)
(not (cleaned-up-p data)))
(setf ok nil)
(format out "~%attempt to fetch data for key ~a resulted in ~s" key data)
(return))
(cache-release cache tag))))
ok))))))
(5am:is (zerop (count-if-not #'identity (mapcar #'bt:join-thread threads)))))
(5am:is (> (cache-size cache) 900))
(5am:is (> (cache-count cache) 10))
(handler-case
(cache-sanity-check cache)
(error (e)
(error "With policy ~a: ~a" policy e)))))))
|
|
d8067434240d3a0d7fb87edb78215eb578eec09bd035df195da55517ef336aad | ujamjar/hardcaml-zinc | interp.mli | open Base
module type State = sig
type st
include Ops.S
(* machine registers *)
val get_reg : st -> Machine.Register.t -> t * st
val set_reg : st -> Machine.Register.t -> t -> st
(* memory access *)
val get_mem : st -> Machine.Cache.t -> t -> t * st
val set_mem : st -> Machine.Cache.t -> t -> t -> st
(* control *)
val cond : st -> t -> (st -> unit * st) -> (st -> unit * st) -> st
val iter_up : st -> t -> t -> (t -> st -> unit * st) -> st
val iter_dn : st -> t -> t -> (t -> st -> unit * st) -> st
(* oo *)
val dynmet : st -> t -> t -> t * st
(* debugging *)
val string_of_value : t -> string
end
module State_eval : State with type t = int64 and type st = Machine.state
type sp_cmd =
| Get_reg of int * Machine.Register.t
| Set_reg of Machine.Register.t * sp_t
| Get_mem of int * Machine.Cache.t * sp_t
| Set_mem of Machine.Cache.t * sp_t * sp_t
| Cond of sp_t * sp_cmd list * sp_cmd list
| Iter of bool * int * sp_t * sp_t * sp_cmd list
and sp_t =
| Op of string * sp_t * sp_t
| Val of int
| Const of int
and sp_st =
{ id : int
; cmd : sp_cmd list
}
[@@deriving sexp_of]
module State_poly : sig
include State with type t = sp_t and type st = sp_st
val empty : st
val normalise : sp_cmd list -> sp_cmd list
val print : st -> unit
end
module type Monad = sig
module S : State
type 'a t = S.st -> 'a * S.st
val bind : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
val ( >> ) : 'a t -> 'b t -> 'b t
val if_ : S.t -> unit t -> unit t -> unit t
val for_up : S.t -> S.t -> (S.t -> unit t) -> unit t
val for_dn : S.t -> S.t -> (S.t -> unit t) -> unit t
val step : S.st -> 'a t -> 'a * S.st
val trace : bool
val debug : string -> unit t
val write_reg : Machine.Register.t -> S.t -> unit t
val read_reg : Machine.Register.t -> S.t t
val modify_reg : Machine.Register.t -> (S.t -> S.t) -> unit t
val read_mem : Machine.Cache.t -> S.t -> S.t t
val write_mem : Machine.Cache.t -> S.t -> S.t -> unit t
val read_bytecode : S.t -> S.t t
val dynmet : S.t -> S.t -> S.t t
end
module Monad (T : sig
val trace : bool
end)
(S : State) : Monad with type S.st = S.st and type S.t = S.t
module Opcodes (M : Monad) : sig
type returns =
[ `step
| `stop
| `c_call of M.S.t * M.S.t
]
[@@deriving sexp_of]
type instr = unit M.t
type arg = M.S.t
val accn : arg -> instr
val acc : instr
val push : instr
val pushaccn : arg -> instr
val pushacc : instr
val pop : instr
val assign : instr
val envaccn : arg -> instr
val envacc : instr
val pushenvaccn : arg -> instr
val pushenvacc : instr
val push_retaddr : instr
val apply : instr
val applyn : int -> instr
val appterm : instr
val apptermn : int -> instr
val return_ : instr
val restart : instr
val grab : instr
val closure : instr
val closurerec : instr
val pushoffsetclosure : instr
val offsetclosure : instr
val pushoffsetclosurem2 : instr
val offsetclosurem2 : instr
val pushoffsetclosure0 : instr
val offsetclosure0 : instr
val pushoffsetclosure2 : instr
val offsetclosure2 : instr
val getglobal : instr
val pushgetglobal : instr
val getglobalfield : instr
val pushgetglobalfield : instr
val setglobal : instr
val atom0 : instr
val pushatom0 : instr
val atom : instr
val pushatom : instr
val makeblockn : arg -> instr
val makeblock : instr
val makefloatblock : instr
val getfieldn : arg -> instr
val getfield : instr
val getfloatfield : instr
val setfieldn : arg -> instr
val setfield : instr
val vectlength : instr
val getvectitem : instr
val setvectitem : instr
val getstringchar : instr
val setstringchar : instr
val branch : instr
val branchif : instr
val branchifnot : instr
val switch : instr
val boolnot : instr
val pushtrap : instr
val poptrap : instr
val raise_ : instr
val raise_notrace : instr
val reraise : instr
val check_signals : instr
val c_call : arg -> returns M.t
val c_calln : returns M.t
val constn : arg -> instr
val pushconstn : arg -> instr
val constint : instr
val pushconstint : instr
val negint : instr
val addint : instr
val subint : instr
val mulint : instr
val divint : instr
val modint : instr
val andint : instr
val orint : instr
val xorint : instr
val lslint : instr
val lsrint : instr
val asrint : instr
val eq : instr
val neq : instr
val ltint : instr
val leint : instr
val gtint : instr
val geint : instr
val ultint : instr
val ugeint : instr
val beq : instr
val bneq : instr
val bltint : instr
val bleint : instr
val bgtint : instr
val bgeint : instr
val bultint : instr
val bugeint : instr
val offsetint : instr
val offsetref : instr
val isint : instr
val getmethod : instr
val getdynmet : instr
val getpubmet : instr
val stop : instr
val event : instr
val break : instr
val dispatch : Opcode.t -> returns M.t
end
| null | https://raw.githubusercontent.com/ujamjar/hardcaml-zinc/ad9360a66ddd239550623e3a92fe5328934706fa/src/interp.mli | ocaml | machine registers
memory access
control
oo
debugging | open Base
module type State = sig
type st
include Ops.S
val get_reg : st -> Machine.Register.t -> t * st
val set_reg : st -> Machine.Register.t -> t -> st
val get_mem : st -> Machine.Cache.t -> t -> t * st
val set_mem : st -> Machine.Cache.t -> t -> t -> st
val cond : st -> t -> (st -> unit * st) -> (st -> unit * st) -> st
val iter_up : st -> t -> t -> (t -> st -> unit * st) -> st
val iter_dn : st -> t -> t -> (t -> st -> unit * st) -> st
val dynmet : st -> t -> t -> t * st
val string_of_value : t -> string
end
module State_eval : State with type t = int64 and type st = Machine.state
type sp_cmd =
| Get_reg of int * Machine.Register.t
| Set_reg of Machine.Register.t * sp_t
| Get_mem of int * Machine.Cache.t * sp_t
| Set_mem of Machine.Cache.t * sp_t * sp_t
| Cond of sp_t * sp_cmd list * sp_cmd list
| Iter of bool * int * sp_t * sp_t * sp_cmd list
and sp_t =
| Op of string * sp_t * sp_t
| Val of int
| Const of int
and sp_st =
{ id : int
; cmd : sp_cmd list
}
[@@deriving sexp_of]
module State_poly : sig
include State with type t = sp_t and type st = sp_st
val empty : st
val normalise : sp_cmd list -> sp_cmd list
val print : st -> unit
end
module type Monad = sig
module S : State
type 'a t = S.st -> 'a * S.st
val bind : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
val ( >> ) : 'a t -> 'b t -> 'b t
val if_ : S.t -> unit t -> unit t -> unit t
val for_up : S.t -> S.t -> (S.t -> unit t) -> unit t
val for_dn : S.t -> S.t -> (S.t -> unit t) -> unit t
val step : S.st -> 'a t -> 'a * S.st
val trace : bool
val debug : string -> unit t
val write_reg : Machine.Register.t -> S.t -> unit t
val read_reg : Machine.Register.t -> S.t t
val modify_reg : Machine.Register.t -> (S.t -> S.t) -> unit t
val read_mem : Machine.Cache.t -> S.t -> S.t t
val write_mem : Machine.Cache.t -> S.t -> S.t -> unit t
val read_bytecode : S.t -> S.t t
val dynmet : S.t -> S.t -> S.t t
end
module Monad (T : sig
val trace : bool
end)
(S : State) : Monad with type S.st = S.st and type S.t = S.t
module Opcodes (M : Monad) : sig
type returns =
[ `step
| `stop
| `c_call of M.S.t * M.S.t
]
[@@deriving sexp_of]
type instr = unit M.t
type arg = M.S.t
val accn : arg -> instr
val acc : instr
val push : instr
val pushaccn : arg -> instr
val pushacc : instr
val pop : instr
val assign : instr
val envaccn : arg -> instr
val envacc : instr
val pushenvaccn : arg -> instr
val pushenvacc : instr
val push_retaddr : instr
val apply : instr
val applyn : int -> instr
val appterm : instr
val apptermn : int -> instr
val return_ : instr
val restart : instr
val grab : instr
val closure : instr
val closurerec : instr
val pushoffsetclosure : instr
val offsetclosure : instr
val pushoffsetclosurem2 : instr
val offsetclosurem2 : instr
val pushoffsetclosure0 : instr
val offsetclosure0 : instr
val pushoffsetclosure2 : instr
val offsetclosure2 : instr
val getglobal : instr
val pushgetglobal : instr
val getglobalfield : instr
val pushgetglobalfield : instr
val setglobal : instr
val atom0 : instr
val pushatom0 : instr
val atom : instr
val pushatom : instr
val makeblockn : arg -> instr
val makeblock : instr
val makefloatblock : instr
val getfieldn : arg -> instr
val getfield : instr
val getfloatfield : instr
val setfieldn : arg -> instr
val setfield : instr
val vectlength : instr
val getvectitem : instr
val setvectitem : instr
val getstringchar : instr
val setstringchar : instr
val branch : instr
val branchif : instr
val branchifnot : instr
val switch : instr
val boolnot : instr
val pushtrap : instr
val poptrap : instr
val raise_ : instr
val raise_notrace : instr
val reraise : instr
val check_signals : instr
val c_call : arg -> returns M.t
val c_calln : returns M.t
val constn : arg -> instr
val pushconstn : arg -> instr
val constint : instr
val pushconstint : instr
val negint : instr
val addint : instr
val subint : instr
val mulint : instr
val divint : instr
val modint : instr
val andint : instr
val orint : instr
val xorint : instr
val lslint : instr
val lsrint : instr
val asrint : instr
val eq : instr
val neq : instr
val ltint : instr
val leint : instr
val gtint : instr
val geint : instr
val ultint : instr
val ugeint : instr
val beq : instr
val bneq : instr
val bltint : instr
val bleint : instr
val bgtint : instr
val bgeint : instr
val bultint : instr
val bugeint : instr
val offsetint : instr
val offsetref : instr
val isint : instr
val getmethod : instr
val getdynmet : instr
val getpubmet : instr
val stop : instr
val event : instr
val break : instr
val dispatch : Opcode.t -> returns M.t
end
|
a36c1bbdeda71c84864e60038b8bda8e90accfd3ddd657121da453c61de4558f | zmactep/hasbolt | Record.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
module Database.Bolt.Record where
import Database.Bolt.Value.Type
import Database.Bolt.Value.Instances ()
import Database.Bolt.Connection.Type
import Control.Monad.Except (MonadError (..), withExceptT)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M (lookup)
import Data.Text (Text)
-- |Result type for query requests
type Record = Map Text Value
-- |Get exact type from Value
class RecordValue a where
exactEither :: Value -> Either UnpackError a
exact :: (MonadError UnpackError m, RecordValue a) => Value -> m a
exact = either throwError pure . exactEither
exactMaybe :: RecordValue a => Value -> Maybe a
exactMaybe = either (const Nothing) Just . exactEither
instance RecordValue () where
exactEither (N _) = pure ()
exactEither _ = throwError NotNull
instance RecordValue Bool where
exactEither (B b) = pure b
exactEither _ = throwError NotBool
instance RecordValue Int where
exactEither (I i) = pure i
exactEither _ = throwError NotInt
instance RecordValue Double where
exactEither (F d) = pure d
exactEither _ = throwError NotFloat
instance RecordValue Text where
exactEither (T t) = pure t
exactEither _ = throwError NotString
instance RecordValue Value where
exactEither = pure
instance RecordValue a => RecordValue [a] where
exactEither (L l) = traverse exactEither l
exactEither _ = throwError NotList
instance RecordValue a => RecordValue (Maybe a) where
exactEither (N _) = pure Nothing
exactEither x = Just <$> exactEither x
instance RecordValue (Map Text Value) where
exactEither (M m) = pure m
exactEither _ = throwError NotDict
instance RecordValue Node where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Node"
instance RecordValue Relationship where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Relationship"
instance RecordValue URelationship where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "URelationship"
instance RecordValue Path where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Path"
-- |Gets result from obtained record
at :: (Monad m, RecordValue a) => Record -> Text -> BoltActionT m a
at record key = case M.lookup key record of
Just x -> liftE $ withExceptT WrongMessageFormat (exact x)
Nothing -> throwError $ RecordHasNoKey key
-- |Possibly gets result from obtained record
maybeAt :: (Monad m, RecordValue a) => Record -> Text -> BoltActionT m (Maybe a)
maybeAt record key = case M.lookup key record of
Just x -> liftE $ withExceptT WrongMessageFormat (exact x)
Nothing -> return Nothing
| null | https://raw.githubusercontent.com/zmactep/hasbolt/8f53d21f3db891fd74801cdd6ae996a41318b111/src/Database/Bolt/Record.hs | haskell | # LANGUAGE OverloadedStrings #
|Result type for query requests
|Get exact type from Value
|Gets result from obtained record
|Possibly gets result from obtained record | # LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
module Database.Bolt.Record where
import Database.Bolt.Value.Type
import Database.Bolt.Value.Instances ()
import Database.Bolt.Connection.Type
import Control.Monad.Except (MonadError (..), withExceptT)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M (lookup)
import Data.Text (Text)
type Record = Map Text Value
class RecordValue a where
exactEither :: Value -> Either UnpackError a
exact :: (MonadError UnpackError m, RecordValue a) => Value -> m a
exact = either throwError pure . exactEither
exactMaybe :: RecordValue a => Value -> Maybe a
exactMaybe = either (const Nothing) Just . exactEither
instance RecordValue () where
exactEither (N _) = pure ()
exactEither _ = throwError NotNull
instance RecordValue Bool where
exactEither (B b) = pure b
exactEither _ = throwError NotBool
instance RecordValue Int where
exactEither (I i) = pure i
exactEither _ = throwError NotInt
instance RecordValue Double where
exactEither (F d) = pure d
exactEither _ = throwError NotFloat
instance RecordValue Text where
exactEither (T t) = pure t
exactEither _ = throwError NotString
instance RecordValue Value where
exactEither = pure
instance RecordValue a => RecordValue [a] where
exactEither (L l) = traverse exactEither l
exactEither _ = throwError NotList
instance RecordValue a => RecordValue (Maybe a) where
exactEither (N _) = pure Nothing
exactEither x = Just <$> exactEither x
instance RecordValue (Map Text Value) where
exactEither (M m) = pure m
exactEither _ = throwError NotDict
instance RecordValue Node where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Node"
instance RecordValue Relationship where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Relationship"
instance RecordValue URelationship where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "URelationship"
instance RecordValue Path where
exactEither (S s) = fromStructure s
exactEither _ = throwError $ Not "Path"
at :: (Monad m, RecordValue a) => Record -> Text -> BoltActionT m a
at record key = case M.lookup key record of
Just x -> liftE $ withExceptT WrongMessageFormat (exact x)
Nothing -> throwError $ RecordHasNoKey key
maybeAt :: (Monad m, RecordValue a) => Record -> Text -> BoltActionT m (Maybe a)
maybeAt record key = case M.lookup key record of
Just x -> liftE $ withExceptT WrongMessageFormat (exact x)
Nothing -> return Nothing
|
b360955790a60f263672a108e7b8db8ca87bf6d966d60cca05fb404a66151936 | gilith/hol-light | main_thms.ml | let empty_mat = prove_by_refinement(
`interpmat [] [] [[]]`,
(* {{{ Proof *)
[
REWRITE_TAC[interpmat;ROL_EMPTY;interpsigns;ALL2;partition_line];
]);;
(* }}} *)
let empty_sgns = [ARITH_RULE `&1 > &0`];;
let monic_isign_lem = prove(
`(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Pos ==> interpsign s p Pos) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Pos ==> interpsign s p Neg) /\
(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Neg ==> interpsign s p Neg) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Neg ==> interpsign s p Pos) /\
(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Zero ==> interpsign s p Zero) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Zero ==> interpsign s p Zero)`,
(* {{{ Proof *)
REWRITE_TAC[interpsign] THEN REPEAT STRIP_TAC THEN
POP_ASSUM (fun x -> POP_ASSUM (fun y -> MP_TAC (MATCH_MP y x))) THEN
POP_ASSUM MP_TAC THEN
POP_ASSUM (ASSUME_TAC o GSYM o (ISPEC `x:real`)) THEN
ASM_REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt;REAL_ENTIRE] THEN
REAL_ARITH_TAC);;
(* }}} *)
let gtpos::ltpos::gtneg::ltneg::gtzero::ltzero::[] = CONJUNCTS monic_isign_lem;;
let main_lem000 = prove_by_refinement(
`!l n. (LENGTH l = SUC n) ==> 0 < LENGTH l`,
(* {{{ Proof *)
[
LIST_INDUCT_TAC;
REWRITE_TAC[LENGTH];
ARITH_TAC;
ARITH_TAC;
]);;
(* }}} *)
let main_lem001 = prove_by_refinement(
`x <> &0 ==> (LAST l = x) ==> LAST l <> &0`,
[MESON_TAC[]]);;
let main_lem002 = prove_by_refinement(
`(x <> y ==> x <> y) /\
(x < y ==> x <> y) /\
(x > y ==> x <> y) /\
(~(x >= y) ==> x <> y) /\
(~(x <= y) ==> x <> y) /\
(~(x = y) ==> x <> y)`,
(* {{{ Proof *)
[
REWRITE_TAC[NEQ] THEN REAL_ARITH_TAC
]);;
(* }}} *)
let factor_pos_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Pos ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt];
]);;
(* }}} *)
let factor_pos_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Neg ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt];
]);;
(* }}} *)
let factor_pos_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Zero ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_LT;REAL_ENTIRE;real_gt];
]);;
(* }}} *)
let factor_zero_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Pos ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[POW_0;num_CASES;];
]);;
(* }}} *)
let factor_zero_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Neg ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[POW_0;num_CASES;];
]);;
(* }}} *)
let factor_zero_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Zero ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REAL_ARITH_TAC;
]);;
(* }}} *)
let factor_neg_even_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Pos ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
(* }}} *)
let factor_neg_even_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Neg ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
(* }}} *)
let factor_neg_even_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Zero ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
]);;
(* }}} *)
let factor_neg_odd_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Pos ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
(* }}} *)
let factor_neg_odd_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Neg ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
(* }}} *)
let factor_neg_odd_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Zero ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
(* {{{ Proof *)
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
]);;
(* }}} *)
| null | https://raw.githubusercontent.com/gilith/hol-light/f3f131963f2298b4d65ee5fead6e986a4a14237a/Rqe/main_thms.ml | ocaml | {{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}}
{{{ Proof
}}} | let empty_mat = prove_by_refinement(
`interpmat [] [] [[]]`,
[
REWRITE_TAC[interpmat;ROL_EMPTY;interpsigns;ALL2;partition_line];
]);;
let empty_sgns = [ARITH_RULE `&1 > &0`];;
let monic_isign_lem = prove(
`(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Pos ==> interpsign s p Pos) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Pos ==> interpsign s p Neg) /\
(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Neg ==> interpsign s p Neg) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Neg ==> interpsign s p Pos) /\
(!s c mp p. (!x. c * p x = mp x) ==> c > &0 ==> interpsign s mp Zero ==> interpsign s p Zero) /\
(!s c mp p. (!x. c * p x = mp x) ==> c < &0 ==> interpsign s mp Zero ==> interpsign s p Zero)`,
REWRITE_TAC[interpsign] THEN REPEAT STRIP_TAC THEN
POP_ASSUM (fun x -> POP_ASSUM (fun y -> MP_TAC (MATCH_MP y x))) THEN
POP_ASSUM MP_TAC THEN
POP_ASSUM (ASSUME_TAC o GSYM o (ISPEC `x:real`)) THEN
ASM_REWRITE_TAC[REAL_MUL_LT;REAL_MUL_GT;real_gt;REAL_ENTIRE] THEN
REAL_ARITH_TAC);;
let gtpos::ltpos::gtneg::ltneg::gtzero::ltzero::[] = CONJUNCTS monic_isign_lem;;
let main_lem000 = prove_by_refinement(
`!l n. (LENGTH l = SUC n) ==> 0 < LENGTH l`,
[
LIST_INDUCT_TAC;
REWRITE_TAC[LENGTH];
ARITH_TAC;
ARITH_TAC;
]);;
let main_lem001 = prove_by_refinement(
`x <> &0 ==> (LAST l = x) ==> LAST l <> &0`,
[MESON_TAC[]]);;
let main_lem002 = prove_by_refinement(
`(x <> y ==> x <> y) /\
(x < y ==> x <> y) /\
(x > y ==> x <> y) /\
(~(x >= y) ==> x <> y) /\
(~(x <= y) ==> x <> y) /\
(~(x = y) ==> x <> y)`,
[
REWRITE_TAC[NEQ] THEN REAL_ARITH_TAC
]);;
let factor_pos_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Pos ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt];
]);;
let factor_pos_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Neg ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt];
]);;
let factor_pos_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Pos ==> interpsign s p Zero ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_LT;REAL_ENTIRE;real_gt];
]);;
let factor_zero_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Pos ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[POW_0;num_CASES;];
]);;
let factor_zero_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Neg ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[POW_0;num_CASES;];
]);;
let factor_zero_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Zero ==> interpsign s p Zero ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REAL_ARITH_TAC;
]);;
let factor_neg_even_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Pos ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
let factor_neg_even_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Neg ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt];
DISJ2_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
let factor_neg_even_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Zero ==> EVEN k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
]);;
let factor_neg_odd_pos = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Pos ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Neg`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
let factor_neg_odd_neg = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Neg ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Pos`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
DISJ1_TAC;
ASM_MESON_TAC[REAL_POW_LT;real_gt;PARITY_POW_LT];
]);;
let factor_neg_odd_zero = prove_by_refinement(
`interpsign s (\x. &0 + x * &1) Neg ==> interpsign s p Zero ==> ODD k ==> ~(k = 0) ==>
(!x. x pow k * p x = q x) ==> interpsign s q Zero`,
[
REWRITE_TAC[interpsign;REAL_ADD_LID;REAL_MUL_RID;];
REPEAT STRIP_TAC;
POP_ASSUM (fun x -> (RULE_ASSUM_TAC (fun y -> try MATCH_MP y x with _ -> y)));
POP_ASSUM (ASSUME_TAC o ISPEC rx o GSYM);
ASM_REWRITE_TAC[];
REWRITE_TAC[REAL_MUL_GT;REAL_MUL_LT;real_gt;REAL_ENTIRE];
]);;
|
149a50cb9d3a060e360ffa786509243586bfab38b8bbca27777f8e380ebc1cb3 | NorfairKing/exchangerates | Cache.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
-- | Caches for the raw API
module ExchangeRates.Cache
( ExchangeRatesCache(..)
, insertRates
, ExchangeRatesCacheResult(..)
, lookupRates
, emptyExchangeRatesCache
, RateCache(..)
, emptyRateCache
, insertRatesInCache
, lookupRatesInCache
, smartInsertInCache
, smartLookupRateInCache
-- Defaults
, defaultBaseCurrency
, allSymbolsExcept
-- Helpers
, convertToBaseWithRate
, rawInsertInCache
, rawLookupInCache
) where
import Control.Monad
import Data.Aeson
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe
import qualified Data.Set as S
import Data.Set (Set)
import Data.Time
import Data.Validity
import GHC.Generics (Generic)
import ExchangeRates.Types
-- | A complete cache for the raw API.
--
-- This includes a cache for the rates we get, as well as a cache for the
-- rates we do not get.
data ExchangeRatesCache = ExchangeRatesCache
{ fCacheRates :: RateCache
, fCacheDaysWithoutRates :: Set Day
} deriving (Show, Eq, Generic)
instance Validity ExchangeRatesCache
instance FromJSON ExchangeRatesCache where
parseJSON =
withObject "ExchangeRatesCache" $ \o ->
ExchangeRatesCache <$> o .: "rates" <*> o .: "days-without-rates"
instance ToJSON ExchangeRatesCache where
toJSON ExchangeRatesCache {..} =
object
[ "rates" .= fCacheRates
, "days-without-rates" .= fCacheDaysWithoutRates
]
| Insert a given raw response in a ' ExchangeRatesCache '
insertRates ::
Day -- ^ The current date
-> Day -- ^ The requested date
-> Rates
-> ExchangeRatesCache
-> ExchangeRatesCache
insertRates n d r fc
| ratesDate r == d =
let rc' = insertRatesInCache r $ fCacheRates fc
in fc {fCacheRates = rc'}
| d >= n = fc
| otherwise =
let dwr' = S.insert d $ fCacheDaysWithoutRates fc
in fc {fCacheDaysWithoutRates = dwr'}
| The result of looking up rates in a ' ExchangeRatesCache '
data ExchangeRatesCacheResult
= NotInCache
| CacheDateNotInPast -- ^ Because we requested a date in the future
^ Because it was on a weekend or holiday
| InCache Rates
deriving (Show, Eq, Generic)
instance Validity ExchangeRatesCacheResult
-- | Look up rates in cache
lookupRates ::
Day -- ^ The current date
-> Day -- ^ The requested date
-> Currency
-> Symbols
-> ExchangeRatesCache
-> ExchangeRatesCacheResult
lookupRates n d c s ExchangeRatesCache {..}
| d >= n = CacheDateNotInPast
| S.member d fCacheDaysWithoutRates = WillNeverExist
| otherwise =
case lookupRatesInCache d c s fCacheRates of
Nothing -> NotInCache
Just r -> InCache r
| The empty ' ExchangeRatesCache '
emptyExchangeRatesCache :: ExchangeRatesCache
emptyExchangeRatesCache =
ExchangeRatesCache
{fCacheRates = emptyRateCache, fCacheDaysWithoutRates = S.empty}
-- | A cache for currency rates
--
-- This cache uses 'EUR' as the base currency, but will still cache
-- rates appropriately if rates with a different base currency are cached.
newtype RateCache = RateCache
{ unRateCache :: Map Day (Map Currency (Map Currency Rate))
} deriving (Show, Eq, Generic, FromJSON, ToJSON)
instance Validity RateCache where
validate RateCache {..} =
mconcat
[ unRateCache <?!> "unRateCache"
, let go :: Map Currency (Map Currency Rate) -> Bool
go m =
not . or $
M.mapWithKey (\c m_ -> isJust (M.lookup c m_)) m
in all go unRateCache <?@>
"Does not contain conversions to from a currency to itself"
]
isValid = isValidByValidating
| The empty Cache
emptyRateCache :: RateCache
emptyRateCache = RateCache M.empty
-- | Insert a rate into the cache as-is.
--
-- You probably want to be using 'insertRatesInCache' or 'smartInsertInCache' instead.
rawInsertInCache ::
Day -> Currency -> Currency -> Rate -> RateCache -> RateCache
rawInsertInCache d from to rate (RateCache fc) = RateCache $ M.alter go1 d fc
where
go1 :: Maybe (Map Currency (Map Currency Rate))
-> Maybe (Map Currency (Map Currency Rate))
go1 Nothing = Just $ M.singleton from $ M.singleton to rate
go1 (Just c1) = Just $ M.alter go2 from c1
go2 :: Maybe (Map Currency Rate) -> Maybe (Map Currency Rate)
go2 Nothing = Just $ M.singleton to rate
go2 (Just c2) = Just $ M.insert to rate c2
-- | Lookup a rate in the cache as-is.
--
You probably want to be using ' smartLookupRateInCache ' instead .
rawLookupInCache :: Day -> Currency -> Currency -> RateCache -> Maybe Rate
rawLookupInCache d from to (RateCache fc) =
M.lookup d fc >>= M.lookup from >>= M.lookup to
-- | The default base currency. Currently this is 'EUR'
defaultBaseCurrency :: Currency
defaultBaseCurrency = EUR
-- | The symbols to get by default, given a base currency.
allSymbolsExcept :: Currency -> Symbols
allSymbolsExcept base =
Symbols $ NE.fromList $ filter (/= base) [minBound .. maxBound]
-- | Insert a result into the cache.
--
-- This is probably the function you want to use, it does all the smartness.
insertRatesInCache :: Rates -> RateCache -> RateCache
insertRatesInCache rs fc =
if ratesBase rs == defaultBaseCurrency
then insertRatesAsIs rs
-- If we're not already using the base, then we need to see if we can figure out how many
-- of this base we can get for the default base
We can figure this out in two ways :
1 if the default base is in the rates
else case M.lookup defaultBaseCurrency $ ratesRates rs of
Just r -> insertRatesAtOtherBase r rs
Nothing
-- or
2 if the default base is in the cache
->
case rawLookupInCache
(ratesDate rs)
(ratesBase rs)
defaultBaseCurrency
fc of
Just r -> insertRatesAtOtherBase r rs
Nothing
-- If we find neither, then we just save in the cache as-is
-> insertRatesAsIs rs
where
insertRatesAsIs :: Rates -> RateCache
insertRatesAsIs rates =
M.foldlWithKey (go (ratesBase rates)) fc $ ratesRates rates
insertRatesAtOtherBase :: Rate -> Rates -> RateCache
insertRatesAtOtherBase r =
insertRatesAsIs . convertToBaseWithRate defaultBaseCurrency r
go :: Currency -> RateCache -> Currency -> Rate -> RateCache
go base fc_ c r = smartInsertInCache (ratesDate rs) base c r fc_
-- | Insert a rate in a cache, but don't insert it if the from and to currencies are the same.
smartInsertInCache ::
Day -> Currency -> Currency -> Rate -> RateCache -> RateCache
smartInsertInCache date from to rate fc =
if from == to
then fc
else rawInsertInCache date from to rate fc
-- | Look up multiple rates in a cache.
--
This function uses ' smartLookupRateInCache ' for each requested symbol .
lookupRatesInCache :: Day -> Currency -> Symbols -> RateCache -> Maybe Rates
lookupRatesInCache date base (Symbols nec) fc =
Rates base date <$>
(M.fromList <$>
mapM
(\to -> (,) to <$> smartLookupRateInCache date base to fc)
(NE.filter (/= base) nec))
-- | Look up a rate in a cache.
--
-- This function will try to be smart about what it can find, but will
give up after one redirection .
smartLookupRateInCache :: Day -> Currency -> Currency -> RateCache -> Maybe Rate
smartLookupRateInCache date from to fc@(RateCache m) =
if from == to
then Just oneRate
else case rawLookupInCache date from to fc of
Just r -> pure r
First try to look up at the correct base currency
-- If that works, return it.
Otherwise , try all the other bases at that day , and convert if necessary .
Nothing -> do
dm <- M.lookup date m
msum $
M.elems $
flip M.mapWithKey dm $ \newFrom nfm ->
lookupVia newFrom from to nfm
lookupVia :: Currency -> Currency -> Currency -> Map Currency Rate -> Maybe Rate
lookupVia newFrom from to nfm = do
nfr <-
if newFrom == from
then Just oneRate
else M.lookup from nfm
-- This is the rate at which we can convert from newFrom to from
for each ' from ' , you get ' 1 / nfr ' newFroms
tr <-
if newFrom == to
then Just oneRate
else M.lookup to nfm
-- This is the rate at which we can convert from newFrom to to
pure $ divRate tr nfr
-- | Convert a set of rates to another base currency with the given rate of the new base currency
-- with respect to the old base currency.
-- In the map, we have the info that
for 1 base currency , you get s of the currency in the key .
--
If we now say that for 1 of the old base currency , you can get
-- r of the new base currency
--
This rate means for one of the new base currency , you can get s / r of
-- the currency in the key.
convertToBaseWithRate :: Currency -> Rate -> Rates -> Rates
convertToBaseWithRate new rate rs =
if ratesBase rs == new
then rs
else rs {ratesBase = new, ratesRates = newRates}
where
newRates =
M.map (`divRate` rate) . withOldBase . withoutNewBase $ ratesRates rs
withOldBase = M.insert (ratesBase rs) oneRate
withoutNewBase = M.delete new
| null | https://raw.githubusercontent.com/NorfairKing/exchangerates/6ee3ee31ed479259900ae728e6c4caa968e0dcda/src/ExchangeRates/Cache.hs | haskell | # LANGUAGE OverloadedStrings #
| Caches for the raw API
Defaults
Helpers
| A complete cache for the raw API.
This includes a cache for the rates we get, as well as a cache for the
rates we do not get.
^ The current date
^ The requested date
^ Because we requested a date in the future
| Look up rates in cache
^ The current date
^ The requested date
| A cache for currency rates
This cache uses 'EUR' as the base currency, but will still cache
rates appropriately if rates with a different base currency are cached.
| Insert a rate into the cache as-is.
You probably want to be using 'insertRatesInCache' or 'smartInsertInCache' instead.
| Lookup a rate in the cache as-is.
| The default base currency. Currently this is 'EUR'
| The symbols to get by default, given a base currency.
| Insert a result into the cache.
This is probably the function you want to use, it does all the smartness.
If we're not already using the base, then we need to see if we can figure out how many
of this base we can get for the default base
or
If we find neither, then we just save in the cache as-is
| Insert a rate in a cache, but don't insert it if the from and to currencies are the same.
| Look up multiple rates in a cache.
| Look up a rate in a cache.
This function will try to be smart about what it can find, but will
If that works, return it.
This is the rate at which we can convert from newFrom to from
This is the rate at which we can convert from newFrom to to
| Convert a set of rates to another base currency with the given rate of the new base currency
with respect to the old base currency.
In the map, we have the info that
r of the new base currency
the currency in the key. | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
module ExchangeRates.Cache
( ExchangeRatesCache(..)
, insertRates
, ExchangeRatesCacheResult(..)
, lookupRates
, emptyExchangeRatesCache
, RateCache(..)
, emptyRateCache
, insertRatesInCache
, lookupRatesInCache
, smartInsertInCache
, smartLookupRateInCache
, defaultBaseCurrency
, allSymbolsExcept
, convertToBaseWithRate
, rawInsertInCache
, rawLookupInCache
) where
import Control.Monad
import Data.Aeson
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe
import qualified Data.Set as S
import Data.Set (Set)
import Data.Time
import Data.Validity
import GHC.Generics (Generic)
import ExchangeRates.Types
data ExchangeRatesCache = ExchangeRatesCache
{ fCacheRates :: RateCache
, fCacheDaysWithoutRates :: Set Day
} deriving (Show, Eq, Generic)
instance Validity ExchangeRatesCache
instance FromJSON ExchangeRatesCache where
parseJSON =
withObject "ExchangeRatesCache" $ \o ->
ExchangeRatesCache <$> o .: "rates" <*> o .: "days-without-rates"
instance ToJSON ExchangeRatesCache where
toJSON ExchangeRatesCache {..} =
object
[ "rates" .= fCacheRates
, "days-without-rates" .= fCacheDaysWithoutRates
]
| Insert a given raw response in a ' ExchangeRatesCache '
insertRates ::
-> Rates
-> ExchangeRatesCache
-> ExchangeRatesCache
insertRates n d r fc
| ratesDate r == d =
let rc' = insertRatesInCache r $ fCacheRates fc
in fc {fCacheRates = rc'}
| d >= n = fc
| otherwise =
let dwr' = S.insert d $ fCacheDaysWithoutRates fc
in fc {fCacheDaysWithoutRates = dwr'}
| The result of looking up rates in a ' ExchangeRatesCache '
data ExchangeRatesCacheResult
= NotInCache
^ Because it was on a weekend or holiday
| InCache Rates
deriving (Show, Eq, Generic)
instance Validity ExchangeRatesCacheResult
lookupRates ::
-> Currency
-> Symbols
-> ExchangeRatesCache
-> ExchangeRatesCacheResult
lookupRates n d c s ExchangeRatesCache {..}
| d >= n = CacheDateNotInPast
| S.member d fCacheDaysWithoutRates = WillNeverExist
| otherwise =
case lookupRatesInCache d c s fCacheRates of
Nothing -> NotInCache
Just r -> InCache r
| The empty ' ExchangeRatesCache '
emptyExchangeRatesCache :: ExchangeRatesCache
emptyExchangeRatesCache =
ExchangeRatesCache
{fCacheRates = emptyRateCache, fCacheDaysWithoutRates = S.empty}
newtype RateCache = RateCache
{ unRateCache :: Map Day (Map Currency (Map Currency Rate))
} deriving (Show, Eq, Generic, FromJSON, ToJSON)
instance Validity RateCache where
validate RateCache {..} =
mconcat
[ unRateCache <?!> "unRateCache"
, let go :: Map Currency (Map Currency Rate) -> Bool
go m =
not . or $
M.mapWithKey (\c m_ -> isJust (M.lookup c m_)) m
in all go unRateCache <?@>
"Does not contain conversions to from a currency to itself"
]
isValid = isValidByValidating
| The empty Cache
emptyRateCache :: RateCache
emptyRateCache = RateCache M.empty
rawInsertInCache ::
Day -> Currency -> Currency -> Rate -> RateCache -> RateCache
rawInsertInCache d from to rate (RateCache fc) = RateCache $ M.alter go1 d fc
where
go1 :: Maybe (Map Currency (Map Currency Rate))
-> Maybe (Map Currency (Map Currency Rate))
go1 Nothing = Just $ M.singleton from $ M.singleton to rate
go1 (Just c1) = Just $ M.alter go2 from c1
go2 :: Maybe (Map Currency Rate) -> Maybe (Map Currency Rate)
go2 Nothing = Just $ M.singleton to rate
go2 (Just c2) = Just $ M.insert to rate c2
You probably want to be using ' smartLookupRateInCache ' instead .
rawLookupInCache :: Day -> Currency -> Currency -> RateCache -> Maybe Rate
rawLookupInCache d from to (RateCache fc) =
M.lookup d fc >>= M.lookup from >>= M.lookup to
defaultBaseCurrency :: Currency
defaultBaseCurrency = EUR
allSymbolsExcept :: Currency -> Symbols
allSymbolsExcept base =
Symbols $ NE.fromList $ filter (/= base) [minBound .. maxBound]
insertRatesInCache :: Rates -> RateCache -> RateCache
insertRatesInCache rs fc =
if ratesBase rs == defaultBaseCurrency
then insertRatesAsIs rs
We can figure this out in two ways :
1 if the default base is in the rates
else case M.lookup defaultBaseCurrency $ ratesRates rs of
Just r -> insertRatesAtOtherBase r rs
Nothing
2 if the default base is in the cache
->
case rawLookupInCache
(ratesDate rs)
(ratesBase rs)
defaultBaseCurrency
fc of
Just r -> insertRatesAtOtherBase r rs
Nothing
-> insertRatesAsIs rs
where
insertRatesAsIs :: Rates -> RateCache
insertRatesAsIs rates =
M.foldlWithKey (go (ratesBase rates)) fc $ ratesRates rates
insertRatesAtOtherBase :: Rate -> Rates -> RateCache
insertRatesAtOtherBase r =
insertRatesAsIs . convertToBaseWithRate defaultBaseCurrency r
go :: Currency -> RateCache -> Currency -> Rate -> RateCache
go base fc_ c r = smartInsertInCache (ratesDate rs) base c r fc_
smartInsertInCache ::
Day -> Currency -> Currency -> Rate -> RateCache -> RateCache
smartInsertInCache date from to rate fc =
if from == to
then fc
else rawInsertInCache date from to rate fc
This function uses ' smartLookupRateInCache ' for each requested symbol .
lookupRatesInCache :: Day -> Currency -> Symbols -> RateCache -> Maybe Rates
lookupRatesInCache date base (Symbols nec) fc =
Rates base date <$>
(M.fromList <$>
mapM
(\to -> (,) to <$> smartLookupRateInCache date base to fc)
(NE.filter (/= base) nec))
give up after one redirection .
smartLookupRateInCache :: Day -> Currency -> Currency -> RateCache -> Maybe Rate
smartLookupRateInCache date from to fc@(RateCache m) =
if from == to
then Just oneRate
else case rawLookupInCache date from to fc of
Just r -> pure r
First try to look up at the correct base currency
Otherwise , try all the other bases at that day , and convert if necessary .
Nothing -> do
dm <- M.lookup date m
msum $
M.elems $
flip M.mapWithKey dm $ \newFrom nfm ->
lookupVia newFrom from to nfm
lookupVia :: Currency -> Currency -> Currency -> Map Currency Rate -> Maybe Rate
lookupVia newFrom from to nfm = do
nfr <-
if newFrom == from
then Just oneRate
else M.lookup from nfm
for each ' from ' , you get ' 1 / nfr ' newFroms
tr <-
if newFrom == to
then Just oneRate
else M.lookup to nfm
pure $ divRate tr nfr
for 1 base currency , you get s of the currency in the key .
If we now say that for 1 of the old base currency , you can get
This rate means for one of the new base currency , you can get s / r of
convertToBaseWithRate :: Currency -> Rate -> Rates -> Rates
convertToBaseWithRate new rate rs =
if ratesBase rs == new
then rs
else rs {ratesBase = new, ratesRates = newRates}
where
newRates =
M.map (`divRate` rate) . withOldBase . withoutNewBase $ ratesRates rs
withOldBase = M.insert (ratesBase rs) oneRate
withoutNewBase = M.delete new
|
1fbdc9daaf4b91cdf2dc5e64c2adb1b9e2966dc5c619504a8b079ba7cd85b352 | semperos/clj-webdriver | chrome_test.clj | (ns ^:chrome webdriver.chrome-test
(:require [clojure.test :refer :all]
[clojure.tools.logging :as log]
[webdriver.test.helpers :refer :all]
[webdriver.core :refer [new-webdriver to quit]]
[webdriver.test.common :as c])
(:import org.openqa.selenium.remote.DesiredCapabilities
org.openqa.selenium.chrome.ChromeDriver))
;; Driver definitions
(log/debug "The Chrome driver requires a separate download. See the Selenium-WebDriver wiki for more information if Chrome fails to start.")
(def chrome-driver (atom nil))
;; Fixtures
(defn restart-browser
[f]
(when-not @chrome-driver
(reset! chrome-driver
(new-webdriver {:browser :chrome})))
(to @chrome-driver *base-url*)
(f))
(defn quit-browser
[f]
(f)
(quit @chrome-driver))
(use-fixtures :once start-system! stop-system! quit-browser)
(use-fixtures :each restart-browser)
(c/defcommontests "test-" @chrome-driver)
| null | https://raw.githubusercontent.com/semperos/clj-webdriver/508eb95cb6ad8a5838ff0772b2a5852dc802dde1/test/webdriver/chrome_test.clj | clojure | Driver definitions
Fixtures | (ns ^:chrome webdriver.chrome-test
(:require [clojure.test :refer :all]
[clojure.tools.logging :as log]
[webdriver.test.helpers :refer :all]
[webdriver.core :refer [new-webdriver to quit]]
[webdriver.test.common :as c])
(:import org.openqa.selenium.remote.DesiredCapabilities
org.openqa.selenium.chrome.ChromeDriver))
(log/debug "The Chrome driver requires a separate download. See the Selenium-WebDriver wiki for more information if Chrome fails to start.")
(def chrome-driver (atom nil))
(defn restart-browser
[f]
(when-not @chrome-driver
(reset! chrome-driver
(new-webdriver {:browser :chrome})))
(to @chrome-driver *base-url*)
(f))
(defn quit-browser
[f]
(f)
(quit @chrome-driver))
(use-fixtures :once start-system! stop-system! quit-browser)
(use-fixtures :each restart-browser)
(c/defcommontests "test-" @chrome-driver)
|
9e03a8e3f3f69dce6958f29f0e7e8ab5850d1f8db4a54774807f04a8ecae52f8 | dwango/fialyzer | from_erlang.mli | open Base
open Obeam
val expr_of_erlang_expr : Abstract_format.expr_t -> Ast.t
val code_to_module : Abstract_format.t -> (Ast.module_, exn) Result.t
(* export for unit-test *)
val extract_match_expr : Abstract_format.expr_t -> Abstract_format.expr_t list
| null | https://raw.githubusercontent.com/dwango/fialyzer/3c4b4fc2dacf84008910135bfef16e4ce79f9c89/lib/from_erlang.mli | ocaml | export for unit-test | open Base
open Obeam
val expr_of_erlang_expr : Abstract_format.expr_t -> Ast.t
val code_to_module : Abstract_format.t -> (Ast.module_, exn) Result.t
val extract_match_expr : Abstract_format.expr_t -> Abstract_format.expr_t list
|
169cc7abb07936ea21b3cb94d3d816091037925d0784faa5c7202a21aab744f3 | nyu-acsys/drift | prog2.ml |
let rec loop lx ly =
if lx <= 9 then
loop (lx + 1) (ly+1)
else
assert (ly >= 0)
let main (m:unit) =
let x = 0 in
let y = 0 in
loop x y
let _ = main () | null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DOrder/first/prog2.ml | ocaml |
let rec loop lx ly =
if lx <= 9 then
loop (lx + 1) (ly+1)
else
assert (ly >= 0)
let main (m:unit) =
let x = 0 in
let y = 0 in
loop x y
let _ = main () |
|
caa398e39ddef5928b1756cae0d1582374843f8f033a16d2c2ba2754ddd64538 | avsm/mirage-duniverse | test_macros.ml | open! Import
open Sexplib
open Sexplib.Conv
open Printf
module type Load = sig
val load_sexp_conv_exn : string -> (Sexp.t -> 'a) -> 'a
val load_sexps_conv : string -> (Sexp.t -> 'a) -> 'a Sexp.Annotated.conv list
end
let () =
Printexc.register_printer (fun exc ->
match Sexplib.Conv.sexp_of_exn_opt exc with
| None -> None
| Some sexp ->
Some (Sexp.to_string_hum ~indent:2 sexp))
let command_exn str =
match Sys.command str with
| 0 -> ()
| code -> failwith (sprintf "command %S exited with code %d" str code)
let make ?(reference : (module Load) option) (module Load : Load) =
shadowing Macro to avoid mistakenly calling it instead of Load
let module Macro = struct end in
let test_id = ref 0 in
let id x = x in
let with_files files ~f =
let time = Unix.time () in
incr test_id;
let dir =
sprintf "%s/macros-test/macros-test-%f-%d"
(Filename.get_temp_dir_name ()) time !test_id
in
List.iter (fun (file, contents) ->
let file_dir = Filename.concat dir (Filename.dirname file) in
command_exn ("mkdir -p " ^ file_dir);
let out_channel = open_out (Filename.concat dir file) in
output_string out_channel (contents ^ "\n");
close_out out_channel)
files;
let tear_down () =
command_exn ("rm -rf -- " ^ dir);
in
try let v = f dir in tear_down (); v
with e -> tear_down (); raise e
in
Not quite the same as [ ] functions because it reapplies itself , see the
use below to eliminate " /./././ ... " .
use below to eliminate "/./././...". *)
let replace ~sub ~by str =
let rec loop str i =
if i + String.length sub < String.length str then
if String.sub str i (String.length sub) = sub then
let str =
String.sub str 0 i ^
by ^
String.sub str (i + String.length sub) (String.length str - i - String.length sub)
in
loop str i
else loop str (i + 1)
else str
in loop str 0
in
let replace dir sexp =
sexp
|> sexp_to_string
|> replace ~sub:"/./" ~by:"/"
|> replace ~sub:dir ~by:"DIR"
in
let print_header description files =
let files =
List.map
(fun (file, contents) ->
match Sexp.of_string (String.concat "" [ "("; contents; ")" ]) with
| Atom _ -> assert false
| List contents -> [%sexp (file : string), (contents : Sexp.t list)]
| exception _ ->
[%sexp (file : string), (contents : string)])
files
in
print_s [%message
"test"
description
(files : Sexp.t list)]
in
let check_equal ~description ~files ~actual ~reference =
if actual = reference
then (
print_s [%message "test" description];
print_endline "Actual output agrees with reference output.")
else (
print_header description files;
print_string (Base.String.concat [ "\
Actual output does not agree with reference output.
Actual:
";actual;"\
Reference:
";reference ]))
in
let check ?(f = id) description files =
with_files files ~f:(fun dir ->
let output load =
match load (Filename.concat dir "input.sexp") f with
| output -> [%message (output : Sexp.t)] |> sexp_to_string
| exception exn -> replace dir [%sexp "raised", (exn : exn)]
in
let actual = output Load.load_sexp_conv_exn in
match reference with
| None ->
print_header description files;
print_string actual
| Some (module Reference) ->
check_equal ~description ~files ~actual
~reference:(output Reference.load_sexp_conv_exn));
print_newline ();
in
let check_error_count description ~f files =
with_files files ~f:(fun dir ->
let output load =
let results = load (Filename.concat dir "input.sexp") f in
replace dir [%sexp (results : _ Sexp.Annotated.conv list)] in
let actual = output Load.load_sexps_conv in
match reference with
| None ->
print_header description files;
print_string actual
| Some (module Reference) ->
check_equal ~description ~files ~actual
~reference:(output Reference.load_sexps_conv));
print_newline ();
in
check "simple"
[ "input.sexp"
, "(:include defs.sexp)
((field1 value1)
(field2 ((:include include.sexp) 0004 0005))
(field3 (:concat a (:use f (x (:use x))))))"
; "defs.sexp"
, "(:let x () y z)
(:let f (x) (:concat (:use x) (:use x)))"
; "include.sexp"
, "0001 0002 0003" ];
check "include chain with subdirectories"
[ "input.sexp" , "(:include include/a.sexp)"
; "include/a.sexp" , "(:include b.sexp)"
; "include/b.sexp" , "(this is include/b)" ];
check "hello world"
[ "input.sexp"
, "(:include defs.sexp)
(:include template.sexp)
(:use f (a (:use a)) (b (:use b)))"
; "defs.sexp"
, "(:let a () hello)
(:let b () \" world\")"
; "template.sexp"
, "(:let f (a b) (:concat (:use a) (:use b)))" ];
check "nested let"
[ "input.sexp"
, "(:let f (x)
(:let g (y)
(:use y) (:use y))
(:use g (y (:use x))) (:use g (y (:use x))))
(:concat (:use f (x x)))" ];
check "argument list scoping"
[ "input.sexp"
, "(:let a () a)
(:let b () b)
(:let f (b a) (:concat (:use b) (:use a)))
(:use f (b (:use a)) (a (:use b)))" ];
check "empty argument"
[ "input.sexp" , "(:let f (x) (:use x) bla)
(:use f (x))" ];
check "error evaluating macros"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (()) foo)" ];
check "error evaluating macros"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f x foo)" ];
check "unexpected :use"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:concat :use x)" ];
check "malformed argument"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (x) (:use x))
(:use f (()))" ];
check "argument mismatch"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (x) (:use x)) (:use f (y x))" ];
check "unused variable"
[ "input.sexp" , "(:let f (a) body of f) (:use f (a a))" ];
check "duplicated let argument"
[ "input.sexp", "(:let f (a a) (:concat (:use a) (:use a)))
(:use f (a foo) (a foo))" ];
check "undeclared arguments"
[ "input.sexp" , "(:include include.sexp) (:use f (x bla))"
; "include.sexp" , "(:let y () bla) (:let f (x) ((:use x) (:use y)))" ];
check "undefined variable"
[ "input.sexp" , "(:let x () x) (:include include.sexp)"
; "include.sexp" , "(:use x)" ];
check ":include can cause variable capture"
[ "input.sexp"
, "(:let x () 2)
(:include include.sexp)
(:use x)"
; "include.sexp"
, "(:let x () 1)" ];
check "malformed concat"
[ "input.sexp" , "(:concat (a b))" ];
check "malformed concat"
[ "input.sexp"
, "(:include include.sexp)
(:use f (a ()))"
; "include.sexp"
, "(:let f (a)
(:concat (:use a)))" ];
check "correct error location in a nested let"
[ "input.sexp"
, "(:let f ()
(:let g () (:let incorrect))
(:use g))
(:use f)" ];
check "correct location with chains of includes"
[ "input.sexp" , "(:include a)"
; "a" , "(:include b)"
; "b" , "something invalid like :concat" ];
check "empty let body"
[ "input.sexp" , "\n(:let f ())" ];
let rec conv_error = function
| Sexp.List [ Sexp.Atom "trigger"; Sexp.Atom "error" ] as t ->
raise (Pre_sexp.Of_sexp_error (Exit, t))
| Sexp.Atom _ -> ()
| Sexp.List ts -> List.iter conv_error ts in
let conv_error sexp = conv_error sexp; sexp in
check "error location for conversion errors"
~f:conv_error
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let err () error) (foo bar (trigger (:use err)))" ];
check_error_count "multiple conversion errors"
~f:conv_error
[ "input.sexp" , "(:include include.sexp) (:include include.sexp)"
; "include.sexp" , "(:let err () error) (foo bar (trigger (:use err)))" ];
check "include loop"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:include include.sexp)" ];
what stops this loop is that the filenames become too long . We have to rewrite the
error messages since the exact number of " ./ " in the path depends on the limit on
path length .
error messages since the exact number of "./" in the path depends on the limit on
path length. *)
check "sneaky include loop"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:include ././include.sexp)" ];
check "parsing error 1"
[ "input.sexp" , "(:include include.sexp) ()"
; "include.sexp" , ")" ];
check "parsing error 2"
[ "input.sexp" , "(:include include.sexp) ()"
; "include.sexp" , "(" ];
;;
let%expect_test _ =
make (module Macro);
[%expect {|
(test simple (
files (
(input.sexp (
(:include defs.sexp)
((field1 value1)
(field2 ((:include include.sexp) 0004 0005))
(field3 (:concat a (:use f (x (:use x))))))))
(defs.sexp (
(:let x () y z)
(:let f
(x)
(:concat
(:use x)
(:use x)))))
(include.sexp (0001 0002 0003)))))
(output ((field1 value1) (field2 (0001 0002 0003 0004 0005)) (field3 ayzyz)))
(test "include chain with subdirectories" (
files (
(input.sexp ((:include include/a.sexp)))
(include/a.sexp ((:include b.sexp)))
(include/b.sexp ((this is include/b))))))
(output (this is include/b))
(test "hello world" (
files (
(input.sexp (
(:include defs.sexp)
(:include template.sexp)
(:use f
(a (:use a))
(b (:use b)))))
(defs.sexp (
(:let a () hello)
(:let b () " world")))
(template.sexp ((
:let f
(a b)
(:concat
(:use a)
(:use b))))))))
(output "hello world")
(test "nested let" (
files ((
input.sexp (
(:let f
(x)
(:let g
(y)
(:use y)
(:use y))
(:use g (y (:use x)))
(:use g (y (:use x))))
(:concat (:use f (x x))))))))
(output xxxx)
(test "argument list scoping" (
files ((
input.sexp (
(:let a () a)
(:let b () b)
(:let f
(b a)
(:concat
(:use b)
(:use a)))
(:use f
(b (:use a))
(a (:use b))))))))
(output ab)
(test "empty argument" (
files ((input.sexp ((:let f (x) (:use x) bla) (:use f (x)))))))
(output bla)
(test "error evaluating macros" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:let f (()) foo))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:9
(Failure "Error evaluating macros: Atom expected"))
()))
(test "error evaluating macros" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:let f x foo))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:8
(Failure "Error evaluating macros: Atom list expected"))
x))
(test "unexpected :use" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:concat :use x))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:9
(Failure "Error evaluating macros: Unexpected :use"))
:use))
(test "malformed argument" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let f (x) (:use x)) (:use f (())))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:2:34
(Failure "Error evaluating macros: Malformed argument"))
(())))
(test "argument mismatch" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let f (x) (:use x)) (:use f (y x)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:22
(Failure
"Error evaluating macros: Formal args of f differ from supplied args, formal args are [x]"))
(:use f (y x))))
(test "unused variable" (
files ((input.sexp ((:let f (a) body of f) (:use f (a a)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure "Error evaluating macros: Unused variables: a"))
(:let f (a) body of f)))
(test "duplicated let argument" (
files ((
input.sexp (
(:let f
(a a)
(:concat
(:use a)
(:use a)))
(:use f
(a foo)
(a foo)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure "Error evaluating macros: Duplicated let argument: a"))
(:let f
(a a)
(:concat
(:use a)
(:use a)))))
(test "undeclared arguments" (
files (
(input.sexp ((:include include.sexp) (:use f (x bla))))
(include.sexp (
(:let y () bla)
(:let f
(x)
((:use x)
(:use y))))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:16
(Failure "Error evaluating macros: Undeclared arguments in let: y"))
(:let f
(x)
((:use x)
(:use y)))))
(test "undefined variable" (
files (
(input.sexp ((:let x () x) (:include include.sexp)))
(include.sexp ((:use x))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:6
(Failure
"Error evaluating macros: Undefined variable (included files cannot reference variables from outside)"))
x))
(test ":include can cause variable capture" (
files (
(input.sexp (
(:let x () 2)
(:include include.sexp)
(:use x)))
(include.sexp ((:let x () 1))))))
(output 1)
(test "malformed concat" (files ((input.sexp ((:concat (a b)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure
"Error evaluating macros: Malformed concat application: (:concat(a b))"))
(:concat (a b))))
(test "malformed concat" (
files (
(input.sexp ((:include include.sexp) (:use f (a ()))))
(include.sexp ((:let f (a) (:concat (:use a))))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:2:11
(Failure
"Error evaluating macros: Malformed concat application: (:concat())"))
(:concat (:use a))))
(test
"correct error location in a nested let"
(files ((
input.sexp ((:let f () (:let g () (:let incorrect)) (:use g)) (:use f))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:2:23
(Failure "Error evaluating macros: Unexpected :let"))
:let))
(test
"correct location with chains of includes"
(files (
(input.sexp ((:include a)))
(a ((:include b)))
(b (something invalid like :concat)))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/b:1:23
(Failure "Error evaluating macros: Unexpected :concat"))
:concat))
(test "empty let body" (files ((input.sexp ((:let f ()))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:2:0
(Failure "Error evaluating macros: Empty let bodies not allowed"))
(:let f ())))
(test "error location for conversion errors" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let err () error) (foo bar (trigger (:use err))))))))
(raised (
Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error)))))
(test "multiple conversion errors" (
files (
(input.sexp (
(:include include.sexp)
(:include include.sexp)))
(include.sexp ((:let err () error) (foo bar (trigger (:use err))))))))
((Error (
(Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error))))
(trigger (:use err))))
(Error (
(Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error))))
(trigger (:use err)))))
(test "include loop" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:include include.sexp))))))
(raised (
"Sexplib__Macro.Include_loop_detected(\"DIR/include.sexp\")"))
(test "sneaky include loop" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:include ././include.sexp))))))
(raised (
"Error in file DIR/include.sexp"
(Sys_error
"DIR/include.sexp: File name too long")))
(test "parsing error 1" (
files ((input.sexp ((:include include.sexp) ())) (include.sexp ")"))))
(raised (
Sexplib.Sexp.Parse_error (
(err_msg
"DIR/include.sexp: unexpected character: ')'")
(text_line 1)
(text_char 0)
(global_offset 0)
(buf_pos 0))))
(test "parsing error 2" (
files ((input.sexp ((:include include.sexp) ())) (include.sexp "("))))
(raised (
Failure
"DIR/include.sexp: Sexplib.Sexp.input_rev_sexps: reached EOF while in state Parsing_list")) |}];
;;
let%expect_test _ =
print_s [%sexp (Macro.expand_local_macros [Sexp.of_string "(:use x)"]
: Sexp.t list Macro.conv)];
[%expect {|
(Error ((Failure "Error evaluating macros: Undefined variable") x)) |}];
;;
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/sexplib/test/test_macros.ml | ocaml | open! Import
open Sexplib
open Sexplib.Conv
open Printf
module type Load = sig
val load_sexp_conv_exn : string -> (Sexp.t -> 'a) -> 'a
val load_sexps_conv : string -> (Sexp.t -> 'a) -> 'a Sexp.Annotated.conv list
end
let () =
Printexc.register_printer (fun exc ->
match Sexplib.Conv.sexp_of_exn_opt exc with
| None -> None
| Some sexp ->
Some (Sexp.to_string_hum ~indent:2 sexp))
let command_exn str =
match Sys.command str with
| 0 -> ()
| code -> failwith (sprintf "command %S exited with code %d" str code)
let make ?(reference : (module Load) option) (module Load : Load) =
shadowing Macro to avoid mistakenly calling it instead of Load
let module Macro = struct end in
let test_id = ref 0 in
let id x = x in
let with_files files ~f =
let time = Unix.time () in
incr test_id;
let dir =
sprintf "%s/macros-test/macros-test-%f-%d"
(Filename.get_temp_dir_name ()) time !test_id
in
List.iter (fun (file, contents) ->
let file_dir = Filename.concat dir (Filename.dirname file) in
command_exn ("mkdir -p " ^ file_dir);
let out_channel = open_out (Filename.concat dir file) in
output_string out_channel (contents ^ "\n");
close_out out_channel)
files;
let tear_down () =
command_exn ("rm -rf -- " ^ dir);
in
try let v = f dir in tear_down (); v
with e -> tear_down (); raise e
in
Not quite the same as [ ] functions because it reapplies itself , see the
use below to eliminate " /./././ ... " .
use below to eliminate "/./././...". *)
let replace ~sub ~by str =
let rec loop str i =
if i + String.length sub < String.length str then
if String.sub str i (String.length sub) = sub then
let str =
String.sub str 0 i ^
by ^
String.sub str (i + String.length sub) (String.length str - i - String.length sub)
in
loop str i
else loop str (i + 1)
else str
in loop str 0
in
let replace dir sexp =
sexp
|> sexp_to_string
|> replace ~sub:"/./" ~by:"/"
|> replace ~sub:dir ~by:"DIR"
in
let print_header description files =
let files =
List.map
(fun (file, contents) ->
match Sexp.of_string (String.concat "" [ "("; contents; ")" ]) with
| Atom _ -> assert false
| List contents -> [%sexp (file : string), (contents : Sexp.t list)]
| exception _ ->
[%sexp (file : string), (contents : string)])
files
in
print_s [%message
"test"
description
(files : Sexp.t list)]
in
let check_equal ~description ~files ~actual ~reference =
if actual = reference
then (
print_s [%message "test" description];
print_endline "Actual output agrees with reference output.")
else (
print_header description files;
print_string (Base.String.concat [ "\
Actual output does not agree with reference output.
Actual:
";actual;"\
Reference:
";reference ]))
in
let check ?(f = id) description files =
with_files files ~f:(fun dir ->
let output load =
match load (Filename.concat dir "input.sexp") f with
| output -> [%message (output : Sexp.t)] |> sexp_to_string
| exception exn -> replace dir [%sexp "raised", (exn : exn)]
in
let actual = output Load.load_sexp_conv_exn in
match reference with
| None ->
print_header description files;
print_string actual
| Some (module Reference) ->
check_equal ~description ~files ~actual
~reference:(output Reference.load_sexp_conv_exn));
print_newline ();
in
let check_error_count description ~f files =
with_files files ~f:(fun dir ->
let output load =
let results = load (Filename.concat dir "input.sexp") f in
replace dir [%sexp (results : _ Sexp.Annotated.conv list)] in
let actual = output Load.load_sexps_conv in
match reference with
| None ->
print_header description files;
print_string actual
| Some (module Reference) ->
check_equal ~description ~files ~actual
~reference:(output Reference.load_sexps_conv));
print_newline ();
in
check "simple"
[ "input.sexp"
, "(:include defs.sexp)
((field1 value1)
(field2 ((:include include.sexp) 0004 0005))
(field3 (:concat a (:use f (x (:use x))))))"
; "defs.sexp"
, "(:let x () y z)
(:let f (x) (:concat (:use x) (:use x)))"
; "include.sexp"
, "0001 0002 0003" ];
check "include chain with subdirectories"
[ "input.sexp" , "(:include include/a.sexp)"
; "include/a.sexp" , "(:include b.sexp)"
; "include/b.sexp" , "(this is include/b)" ];
check "hello world"
[ "input.sexp"
, "(:include defs.sexp)
(:include template.sexp)
(:use f (a (:use a)) (b (:use b)))"
; "defs.sexp"
, "(:let a () hello)
(:let b () \" world\")"
; "template.sexp"
, "(:let f (a b) (:concat (:use a) (:use b)))" ];
check "nested let"
[ "input.sexp"
, "(:let f (x)
(:let g (y)
(:use y) (:use y))
(:use g (y (:use x))) (:use g (y (:use x))))
(:concat (:use f (x x)))" ];
check "argument list scoping"
[ "input.sexp"
, "(:let a () a)
(:let b () b)
(:let f (b a) (:concat (:use b) (:use a)))
(:use f (b (:use a)) (a (:use b)))" ];
check "empty argument"
[ "input.sexp" , "(:let f (x) (:use x) bla)
(:use f (x))" ];
check "error evaluating macros"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (()) foo)" ];
check "error evaluating macros"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f x foo)" ];
check "unexpected :use"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:concat :use x)" ];
check "malformed argument"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (x) (:use x))
(:use f (()))" ];
check "argument mismatch"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let f (x) (:use x)) (:use f (y x))" ];
check "unused variable"
[ "input.sexp" , "(:let f (a) body of f) (:use f (a a))" ];
check "duplicated let argument"
[ "input.sexp", "(:let f (a a) (:concat (:use a) (:use a)))
(:use f (a foo) (a foo))" ];
check "undeclared arguments"
[ "input.sexp" , "(:include include.sexp) (:use f (x bla))"
; "include.sexp" , "(:let y () bla) (:let f (x) ((:use x) (:use y)))" ];
check "undefined variable"
[ "input.sexp" , "(:let x () x) (:include include.sexp)"
; "include.sexp" , "(:use x)" ];
check ":include can cause variable capture"
[ "input.sexp"
, "(:let x () 2)
(:include include.sexp)
(:use x)"
; "include.sexp"
, "(:let x () 1)" ];
check "malformed concat"
[ "input.sexp" , "(:concat (a b))" ];
check "malformed concat"
[ "input.sexp"
, "(:include include.sexp)
(:use f (a ()))"
; "include.sexp"
, "(:let f (a)
(:concat (:use a)))" ];
check "correct error location in a nested let"
[ "input.sexp"
, "(:let f ()
(:let g () (:let incorrect))
(:use g))
(:use f)" ];
check "correct location with chains of includes"
[ "input.sexp" , "(:include a)"
; "a" , "(:include b)"
; "b" , "something invalid like :concat" ];
check "empty let body"
[ "input.sexp" , "\n(:let f ())" ];
let rec conv_error = function
| Sexp.List [ Sexp.Atom "trigger"; Sexp.Atom "error" ] as t ->
raise (Pre_sexp.Of_sexp_error (Exit, t))
| Sexp.Atom _ -> ()
| Sexp.List ts -> List.iter conv_error ts in
let conv_error sexp = conv_error sexp; sexp in
check "error location for conversion errors"
~f:conv_error
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:let err () error) (foo bar (trigger (:use err)))" ];
check_error_count "multiple conversion errors"
~f:conv_error
[ "input.sexp" , "(:include include.sexp) (:include include.sexp)"
; "include.sexp" , "(:let err () error) (foo bar (trigger (:use err)))" ];
check "include loop"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:include include.sexp)" ];
what stops this loop is that the filenames become too long . We have to rewrite the
error messages since the exact number of " ./ " in the path depends on the limit on
path length .
error messages since the exact number of "./" in the path depends on the limit on
path length. *)
check "sneaky include loop"
[ "input.sexp" , "(:include include.sexp)"
; "include.sexp" , "(:include ././include.sexp)" ];
check "parsing error 1"
[ "input.sexp" , "(:include include.sexp) ()"
; "include.sexp" , ")" ];
check "parsing error 2"
[ "input.sexp" , "(:include include.sexp) ()"
; "include.sexp" , "(" ];
;;
let%expect_test _ =
make (module Macro);
[%expect {|
(test simple (
files (
(input.sexp (
(:include defs.sexp)
((field1 value1)
(field2 ((:include include.sexp) 0004 0005))
(field3 (:concat a (:use f (x (:use x))))))))
(defs.sexp (
(:let x () y z)
(:let f
(x)
(:concat
(:use x)
(:use x)))))
(include.sexp (0001 0002 0003)))))
(output ((field1 value1) (field2 (0001 0002 0003 0004 0005)) (field3 ayzyz)))
(test "include chain with subdirectories" (
files (
(input.sexp ((:include include/a.sexp)))
(include/a.sexp ((:include b.sexp)))
(include/b.sexp ((this is include/b))))))
(output (this is include/b))
(test "hello world" (
files (
(input.sexp (
(:include defs.sexp)
(:include template.sexp)
(:use f
(a (:use a))
(b (:use b)))))
(defs.sexp (
(:let a () hello)
(:let b () " world")))
(template.sexp ((
:let f
(a b)
(:concat
(:use a)
(:use b))))))))
(output "hello world")
(test "nested let" (
files ((
input.sexp (
(:let f
(x)
(:let g
(y)
(:use y)
(:use y))
(:use g (y (:use x)))
(:use g (y (:use x))))
(:concat (:use f (x x))))))))
(output xxxx)
(test "argument list scoping" (
files ((
input.sexp (
(:let a () a)
(:let b () b)
(:let f
(b a)
(:concat
(:use b)
(:use a)))
(:use f
(b (:use a))
(a (:use b))))))))
(output ab)
(test "empty argument" (
files ((input.sexp ((:let f (x) (:use x) bla) (:use f (x)))))))
(output bla)
(test "error evaluating macros" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:let f (()) foo))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:9
(Failure "Error evaluating macros: Atom expected"))
()))
(test "error evaluating macros" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:let f x foo))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:8
(Failure "Error evaluating macros: Atom list expected"))
x))
(test "unexpected :use" (
files (
(input.sexp ((:include include.sexp))) (include.sexp ((:concat :use x))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:9
(Failure "Error evaluating macros: Unexpected :use"))
:use))
(test "malformed argument" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let f (x) (:use x)) (:use f (())))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:2:34
(Failure "Error evaluating macros: Malformed argument"))
(())))
(test "argument mismatch" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let f (x) (:use x)) (:use f (y x)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:22
(Failure
"Error evaluating macros: Formal args of f differ from supplied args, formal args are [x]"))
(:use f (y x))))
(test "unused variable" (
files ((input.sexp ((:let f (a) body of f) (:use f (a a)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure "Error evaluating macros: Unused variables: a"))
(:let f (a) body of f)))
(test "duplicated let argument" (
files ((
input.sexp (
(:let f
(a a)
(:concat
(:use a)
(:use a)))
(:use f
(a foo)
(a foo)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure "Error evaluating macros: Duplicated let argument: a"))
(:let f
(a a)
(:concat
(:use a)
(:use a)))))
(test "undeclared arguments" (
files (
(input.sexp ((:include include.sexp) (:use f (x bla))))
(include.sexp (
(:let y () bla)
(:let f
(x)
((:use x)
(:use y))))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:16
(Failure "Error evaluating macros: Undeclared arguments in let: y"))
(:let f
(x)
((:use x)
(:use y)))))
(test "undefined variable" (
files (
(input.sexp ((:let x () x) (:include include.sexp)))
(include.sexp ((:use x))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:6
(Failure
"Error evaluating macros: Undefined variable (included files cannot reference variables from outside)"))
x))
(test ":include can cause variable capture" (
files (
(input.sexp (
(:let x () 2)
(:include include.sexp)
(:use x)))
(include.sexp ((:let x () 1))))))
(output 1)
(test "malformed concat" (files ((input.sexp ((:concat (a b)))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:1:0
(Failure
"Error evaluating macros: Malformed concat application: (:concat(a b))"))
(:concat (a b))))
(test "malformed concat" (
files (
(input.sexp ((:include include.sexp) (:use f (a ()))))
(include.sexp ((:let f (a) (:concat (:use a))))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:2:11
(Failure
"Error evaluating macros: Malformed concat application: (:concat())"))
(:concat (:use a))))
(test
"correct error location in a nested let"
(files ((
input.sexp ((:let f () (:let g () (:let incorrect)) (:use g)) (:use f))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:2:23
(Failure "Error evaluating macros: Unexpected :let"))
:let))
(test
"correct location with chains of includes"
(files (
(input.sexp ((:include a)))
(a ((:include b)))
(b (something invalid like :concat)))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/b:1:23
(Failure "Error evaluating macros: Unexpected :concat"))
:concat))
(test "empty let body" (files ((input.sexp ((:let f ()))))))
(raised (
Sexplib.Conv.Of_sexp_error
(Sexplib.Sexp.Annotated.Conv_exn
DIR/input.sexp:2:0
(Failure "Error evaluating macros: Empty let bodies not allowed"))
(:let f ())))
(test "error location for conversion errors" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:let err () error) (foo bar (trigger (:use err))))))))
(raised (
Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error)))))
(test "multiple conversion errors" (
files (
(input.sexp (
(:include include.sexp)
(:include include.sexp)))
(include.sexp ((:let err () error) (foo bar (trigger (:use err))))))))
((Error (
(Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error))))
(trigger (:use err))))
(Error (
(Sexplib.Macro.Macro_conv_error (
(Sexplib.Sexp.Annotated.Conv_exn
DIR/include.sexp:1:29
Exit)
(trigger (:use err))
(expanded (trigger error))))
(trigger (:use err)))))
(test "include loop" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:include include.sexp))))))
(raised (
"Sexplib__Macro.Include_loop_detected(\"DIR/include.sexp\")"))
(test "sneaky include loop" (
files (
(input.sexp ((:include include.sexp)))
(include.sexp ((:include ././include.sexp))))))
(raised (
"Error in file DIR/include.sexp"
(Sys_error
"DIR/include.sexp: File name too long")))
(test "parsing error 1" (
files ((input.sexp ((:include include.sexp) ())) (include.sexp ")"))))
(raised (
Sexplib.Sexp.Parse_error (
(err_msg
"DIR/include.sexp: unexpected character: ')'")
(text_line 1)
(text_char 0)
(global_offset 0)
(buf_pos 0))))
(test "parsing error 2" (
files ((input.sexp ((:include include.sexp) ())) (include.sexp "("))))
(raised (
Failure
"DIR/include.sexp: Sexplib.Sexp.input_rev_sexps: reached EOF while in state Parsing_list")) |}];
;;
let%expect_test _ =
print_s [%sexp (Macro.expand_local_macros [Sexp.of_string "(:use x)"]
: Sexp.t list Macro.conv)];
[%expect {|
(Error ((Failure "Error evaluating macros: Undefined variable") x)) |}];
;;
|
|
925b66dcd5ef80e80a68848644a65c62d8d26a1442f6b53a4956be9afd9b40cb | music-suite/music-score | Midi.hs |
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------------
-- |
Copyright : ( c ) 2012 - 2014
--
-- License : BSD-style
--
Maintainer :
-- Stability : experimental
Portability : non - portable ( TF , )
--
-- Provides MIDI import.
--
-- /Warning/ Experimental module.
--
-------------------------------------------------------------------------------------
module Music.Score.Import.Midi (
IsMidi(..),
fromMidi,
readMidi,
readMidiMaybe,
readMidiEither
) where
import Music.Pitch.Literal (IsPitch)
import Codec.Midi (Midi)
import Control.Applicative
import Control.Lens
import Control.Monad.Plus
-- import Control.Reactive hiding (Event)
-- import qualified Control.Reactive as R
import Control . Reactive . Midi
import Music.Dynamics.Literal
import Music.Pitch.Literal
import Music.Score.Articulation
import Music.Score.Dynamics
import Music.Score.Internal.Export
import Music.Score.Harmonics
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Slide
import Music.Score.Text
import Music.Score.Ties
import Music.Score.Tremolo
import Music.Time
import qualified Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Codec.Midi as Midi
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Text.Pretty as Pretty
import Data.Monoid
import qualified Music.Pitch.Literal as Pitch
import qualified Data . ByteString . Lazy as ByteString
-- |
This constraint includes all note types that can be constructed from a Midi representation .
--
type IsMidi a = (
TODO
IsPitch a,
HasPart' a,
Ord (Part a),
Enum (Part a),
HasPitch a ,
Num (Pitch a),
HasTremolo a,
HasArticulation a a,
Tiable a
)
-- type SimpleMidi = [ [ ( Time , Bool , Int , Int ) ] ] -- outer : track , inner : channel , time , on / off , pitch ,
-- -- -- Ignore offset velocities (can't represent them)
-- type SimpleMidi2 = [ [ ( Span , Int , Int ) ] ] -- outer : track , inner : channel , time , pitch ,
-- --
-- -- foo :: SimpleMidi2
-- -- foo = undefined
--
-- mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
-- mapWithIndex f = zipWith f [0..]
--
-- mapWithIndex2 :: (Int -> Int -> a -> b) -> [[a]] -> [b]
-- mapWithIndex2 f xss = concat $ zipWith (\m -> zipWith (f m) [0..]) [0..] xss
--
-- -- Last time the given key was pressed but not released (non-existant means it is not pressed)
type = Map Int Time
--
-- -- |
-- Convert a score from a Midi representation .
-- --
fromMidi :: IsMidi a => Midi -> Score a
fromMidi m = undefined
-- where
--
toAspects : : [ [ Event ( Midi . Channel , Midi . Key , Midi . Velocity ) ] ] - > [ Event ( Part , Int , Int ) ]
toAspects = mapWithIndex ( \trackN events - > over ( mapped.event ) ( \(s,(ch , key , ) ) - > undefined ) )
--
getMidi : : Midi . Midi - > [ [ Event ( Midi . Channel , Midi . Key , Midi . Velocity ) ] ]
getMidi ( Midi . Midi fileType timeDiv tracks ) = i d
$ compress ( ticksp timeDiv )
-- $ fmap mcatMaybes
$ fmap snd
-- $ fmap (List.mapAccumL g mempty)
$ fmap mcatMaybes $ over ( mapped.mapped ) tracks
-- where
g keyStatus ( t , onOff , c , p , v ) =
( updateKeys onOff p ( fromIntegral t ) keyStatus
-- , (if onOff then Nothing else Just (
-- (Data.Maybe.fromMaybe 0 (Map.lookup (fromIntegral t) keyStatus)<->fromIntegral t,(c,p,60))^.event))
-- )
-- TODO also store dynamics in pitch map ( to use onset value rather than offset value )
-- For now just assume 60
-- updateKeys True p t = Map.insert p t
-- updateKeys False p _ = Map.delete p
--
-- Amount to compress time ( after initially treating each tick as duration 1 )
ticksp ( Midi . TicksPerBeat n ) = 1 / fromIntegral n
ticksp ( Midi . TicksPerSecond _ _ ) = error " fromMidi : Can not parse TickePerSecond - based files "
--
getMsg ( t , Midi . NoteOff c p v ) = Just ( t , False , c , p , v )
getMsg ( t , Midi . NoteOn c p 0 ) = Just ( t , False , c , p,0 )
getMsg ( t , Midi . NoteOn c p v ) = Just ( t , True , c , p , v )
-- -- TODO key pressure
-- -- control change
-- -- program change
-- -- channel pressure
-- -- pitch wheel
-- -- etc.
-- getMsg _ = Nothing
--
Map each track to a part ( scanning for ProgramChange , name etc )
Subdivide parts based on channels
Set channel 10 tracks to " percussion "
Remove all non - used messages ( , ChannelPressure , ProgramChange )
-- Create reactives from variable values
-- Create notes
Superimpose variable values
-- Compose
-- Add meta-information
TODO
-- |
Read a Midi score from a file . Fails if the file could not be read or if a parsing
-- error occurs.
--
readMidi :: IsMidi a => FilePath -> IO (Score a)
readMidi path = fmap (either (\x -> error $ "Could not read MIDI file" ++ x) id) $ readMidiEither path
-- |
Read a Midi score from a file . Fails if the file could not be read , and returns
-- @Nothing@ if a parsing error occurs.
--
readMidiMaybe :: IsMidi a => FilePath -> IO (Maybe (Score a))
readMidiMaybe path = fmap (either (const Nothing) Just) $ readMidiEither path
-- |
Read a Midi score from a file . Fails if the file could not be read , and returns
-- @Left m@ if a parsing error occurs.
--
readMidiEither :: IsMidi a => FilePath -> IO (Either String (Score a))
readMidiEither path = fmap (fmap fromMidi) $ Midi.importFile path
| null | https://raw.githubusercontent.com/music-suite/music-score/aa7182d8ded25c03a56b83941fc625123a7931f8/src/Music/Score/Import/Midi.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE NoMonomorphismRestriction #
# LANGUAGE OverloadedStrings #
-----------------------------------------------------------------------------------
|
License : BSD-style
Stability : experimental
Provides MIDI import.
/Warning/ Experimental module.
-----------------------------------------------------------------------------------
import Control.Reactive hiding (Event)
import qualified Control.Reactive as R
|
type SimpleMidi = [ [ ( Time , Bool , Int , Int ) ] ] -- outer : track , inner : channel , time , on / off , pitch ,
-- -- Ignore offset velocities (can't represent them)
type SimpleMidi2 = [ [ ( Span , Int , Int ) ] ] -- outer : track , inner : channel , time , pitch ,
--
-- foo :: SimpleMidi2
-- foo = undefined
mapWithIndex :: (Int -> a -> b) -> [a] -> [b]
mapWithIndex f = zipWith f [0..]
mapWithIndex2 :: (Int -> Int -> a -> b) -> [[a]] -> [b]
mapWithIndex2 f xss = concat $ zipWith (\m -> zipWith (f m) [0..]) [0..] xss
-- Last time the given key was pressed but not released (non-existant means it is not pressed)
-- |
Convert a score from a Midi representation .
--
where
$ fmap mcatMaybes
$ fmap (List.mapAccumL g mempty)
where
, (if onOff then Nothing else Just (
(Data.Maybe.fromMaybe 0 (Map.lookup (fromIntegral t) keyStatus)<->fromIntegral t,(c,p,60))^.event))
)
TODO also store dynamics in pitch map ( to use onset value rather than offset value )
For now just assume 60
updateKeys True p t = Map.insert p t
updateKeys False p _ = Map.delete p
Amount to compress time ( after initially treating each tick as duration 1 )
-- TODO key pressure
-- control change
-- program change
-- channel pressure
-- pitch wheel
-- etc.
getMsg _ = Nothing
Create reactives from variable values
Create notes
Compose
Add meta-information
|
error occurs.
|
@Nothing@ if a parsing error occurs.
|
@Left m@ if a parsing error occurs.
|
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
Copyright : ( c ) 2012 - 2014
Maintainer :
Portability : non - portable ( TF , )
module Music.Score.Import.Midi (
IsMidi(..),
fromMidi,
readMidi,
readMidiMaybe,
readMidiEither
) where
import Music.Pitch.Literal (IsPitch)
import Codec.Midi (Midi)
import Control.Applicative
import Control.Lens
import Control.Monad.Plus
import Control . Reactive . Midi
import Music.Dynamics.Literal
import Music.Pitch.Literal
import Music.Score.Articulation
import Music.Score.Dynamics
import Music.Score.Internal.Export
import Music.Score.Harmonics
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Slide
import Music.Score.Text
import Music.Score.Ties
import Music.Score.Tremolo
import Music.Time
import qualified Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Codec.Midi as Midi
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Text.Pretty as Pretty
import Data.Monoid
import qualified Music.Pitch.Literal as Pitch
import qualified Data . ByteString . Lazy as ByteString
This constraint includes all note types that can be constructed from a Midi representation .
type IsMidi a = (
TODO
IsPitch a,
HasPart' a,
Ord (Part a),
Enum (Part a),
HasPitch a ,
Num (Pitch a),
HasTremolo a,
HasArticulation a a,
Tiable a
)
type = Map Int Time
fromMidi :: IsMidi a => Midi -> Score a
fromMidi m = undefined
toAspects : : [ [ Event ( Midi . Channel , Midi . Key , Midi . Velocity ) ] ] - > [ Event ( Part , Int , Int ) ]
toAspects = mapWithIndex ( \trackN events - > over ( mapped.event ) ( \(s,(ch , key , ) ) - > undefined ) )
getMidi : : Midi . Midi - > [ [ Event ( Midi . Channel , Midi . Key , Midi . Velocity ) ] ]
getMidi ( Midi . Midi fileType timeDiv tracks ) = i d
$ compress ( ticksp timeDiv )
$ fmap snd
$ fmap mcatMaybes $ over ( mapped.mapped ) tracks
g keyStatus ( t , onOff , c , p , v ) =
( updateKeys onOff p ( fromIntegral t ) keyStatus
ticksp ( Midi . TicksPerBeat n ) = 1 / fromIntegral n
ticksp ( Midi . TicksPerSecond _ _ ) = error " fromMidi : Can not parse TickePerSecond - based files "
getMsg ( t , Midi . NoteOff c p v ) = Just ( t , False , c , p , v )
getMsg ( t , Midi . NoteOn c p 0 ) = Just ( t , False , c , p,0 )
getMsg ( t , Midi . NoteOn c p v ) = Just ( t , True , c , p , v )
Map each track to a part ( scanning for ProgramChange , name etc )
Subdivide parts based on channels
Set channel 10 tracks to " percussion "
Remove all non - used messages ( , ChannelPressure , ProgramChange )
Superimpose variable values
TODO
Read a Midi score from a file . Fails if the file could not be read or if a parsing
readMidi :: IsMidi a => FilePath -> IO (Score a)
readMidi path = fmap (either (\x -> error $ "Could not read MIDI file" ++ x) id) $ readMidiEither path
Read a Midi score from a file . Fails if the file could not be read , and returns
readMidiMaybe :: IsMidi a => FilePath -> IO (Maybe (Score a))
readMidiMaybe path = fmap (either (const Nothing) Just) $ readMidiEither path
Read a Midi score from a file . Fails if the file could not be read , and returns
readMidiEither :: IsMidi a => FilePath -> IO (Either String (Score a))
readMidiEither path = fmap (fmap fromMidi) $ Midi.importFile path
|
5ac1ff1564b4b9631abe8cf418b078f9ffc04c5c376511fb3b6a6ce6e940a110 | jfeser/castor | fixed_point.mli | open Core
type t = { value : int; scale : int } [@@deriving hash, sexp]
include Comparable.S with type t := t
val convert : t -> int -> t
(** Convert to a new scale. *)
val pow10 : int -> int
val of_int : int -> t
val of_string : String.t -> t
val to_string : t -> string
val pp : Format.formatter -> t -> unit
val ( + ) : t -> t -> t
val ( ~- ) : t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( / ) : t -> t -> t
val min_value : t
val max_value : t
val epsilon : t
val of_float : Float.t -> t
val to_float : t -> Float.t
| null | https://raw.githubusercontent.com/jfeser/castor/39005df41a094fee816e85c4c673bfdb223139f7/lib/fixed_point.mli | ocaml | * Convert to a new scale. | open Core
type t = { value : int; scale : int } [@@deriving hash, sexp]
include Comparable.S with type t := t
val convert : t -> int -> t
val pow10 : int -> int
val of_int : int -> t
val of_string : String.t -> t
val to_string : t -> string
val pp : Format.formatter -> t -> unit
val ( + ) : t -> t -> t
val ( ~- ) : t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( / ) : t -> t -> t
val min_value : t
val max_value : t
val epsilon : t
val of_float : Float.t -> t
val to_float : t -> Float.t
|
47df4df628899285398768dfb42d3c3ae1e43b50056d34621fd0e79947815ecc | nrepl/nrepl | helpers_test.clj | (ns nrepl.helpers-test
{:author "Chas Emerick"}
(:require
[clojure.test :refer :all]
[nrepl.core :as nrepl]
[nrepl.core-test :refer [def-repl-test repl-server-fixture]]
[nrepl.helpers :as helpers])
(:import
(java.io File)))
(def ^File project-base-dir (File. (System/getProperty "nrepl.basedir" ".")))
(use-fixtures :once repl-server-fixture)
(def-repl-test load-code-with-debug-info
;; bizarrely, the path of the test script generated by clojure-maven-plugin
;; ends up being in the :file metadata here on Clojure 1.3.0+, but
;; passes in 1.2.0...
#_(repl-eval session "\n\n\n(defn function [])")
#_(is (= [{:file "NO_SOURCE_PATH" :line 4}]
(repl-values session "(-> #'function meta (select-keys [:file :line]))")))
(repl-values session
(helpers/load-file-command
"\n\n\n\n\n\n\n\n\n(defn dfunction [])"
"path/from/source/root.clj"
"root.clj"))
(is (= [{:file "path/from/source/root.clj" :line 10}]
(repl-values session
(nrepl/code
(-> #'dfunction
meta
(select-keys [:file :line])))))))
(def-repl-test load-file-with-debug-info
(repl-values session
(helpers/load-file-command
(File. project-base-dir "load-file-test/nrepl/load_file_sample.clj")
(File. project-base-dir "load-file-test")))
(is (= [{:file (.replace "nrepl/load_file_sample.clj" "/" File/separator)
:line 5}]
(repl-values session
(nrepl/code
(-> #'nrepl.load-file-sample/dfunction
meta
(select-keys [:file :line])))))))
| null | https://raw.githubusercontent.com/nrepl/nrepl/6eb53818c86bc2683ab80f695d3ab72bd006e049/test/clojure/nrepl/helpers_test.clj | clojure | bizarrely, the path of the test script generated by clojure-maven-plugin
ends up being in the :file metadata here on Clojure 1.3.0+, but
passes in 1.2.0... | (ns nrepl.helpers-test
{:author "Chas Emerick"}
(:require
[clojure.test :refer :all]
[nrepl.core :as nrepl]
[nrepl.core-test :refer [def-repl-test repl-server-fixture]]
[nrepl.helpers :as helpers])
(:import
(java.io File)))
(def ^File project-base-dir (File. (System/getProperty "nrepl.basedir" ".")))
(use-fixtures :once repl-server-fixture)
(def-repl-test load-code-with-debug-info
#_(repl-eval session "\n\n\n(defn function [])")
#_(is (= [{:file "NO_SOURCE_PATH" :line 4}]
(repl-values session "(-> #'function meta (select-keys [:file :line]))")))
(repl-values session
(helpers/load-file-command
"\n\n\n\n\n\n\n\n\n(defn dfunction [])"
"path/from/source/root.clj"
"root.clj"))
(is (= [{:file "path/from/source/root.clj" :line 10}]
(repl-values session
(nrepl/code
(-> #'dfunction
meta
(select-keys [:file :line])))))))
(def-repl-test load-file-with-debug-info
(repl-values session
(helpers/load-file-command
(File. project-base-dir "load-file-test/nrepl/load_file_sample.clj")
(File. project-base-dir "load-file-test")))
(is (= [{:file (.replace "nrepl/load_file_sample.clj" "/" File/separator)
:line 5}]
(repl-values session
(nrepl/code
(-> #'nrepl.load-file-sample/dfunction
meta
(select-keys [:file :line])))))))
|
d190ec9fcf37f7d358a2bbb0bfb7f9b4169c4c9dac6a10ac2b534746c21adb82 | hiroshi-unno/coar | fold_fun_list.ml | (*
USED: PEPM2013 as fold_fun_list
*)
let rec make_list n =
if n <= 0
then []
else (fun m -> n + m) :: make_list (n-1)
let rec fold_right f xs init =
match xs with
[] -> init
| x::xs' -> f x (fold_right f xs' init)
let compose f g x = f (g x)
let main n =
let xs = make_list n in
let f = fold_right compose xs (fun x -> x) in
assert (f 0 >= 0)
[@@@assert "typeof(main) <: int -> unit"]
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/benchmarks/OCaml/safety/tacas2015/fold_fun_list.ml | ocaml |
USED: PEPM2013 as fold_fun_list
|
let rec make_list n =
if n <= 0
then []
else (fun m -> n + m) :: make_list (n-1)
let rec fold_right f xs init =
match xs with
[] -> init
| x::xs' -> f x (fold_right f xs' init)
let compose f g x = f (g x)
let main n =
let xs = make_list n in
let f = fold_right compose xs (fun x -> x) in
assert (f 0 >= 0)
[@@@assert "typeof(main) <: int -> unit"]
|
79ecdc854f0ac3313c3bc6d7b5aaadee49cfd329fb9a2605b8599a07664a5983 | csabahruska/jhc-components | Values.hs | module E.Values where
import Control.Monad.Identity
import Data.Monoid
import List
import Ratio
import C.Prims
import E.E
import E.FreeVars()
import E.Subst
import E.TypeCheck
import Info.Info(HasInfo(..))
import Info.Types
import Name.Id
import Name.Name
import Name.Names
import Name.VConsts
import Support.CanType
import Support.FreeVars
import Support.Tuple
import Util.SetLike
import qualified Info.Info as Info
instance Tuple E where
tupleNil = vUnit
tupleMany es = ELit litCons { litName = nameTuple DataConstructor (length es), litArgs = es, litType = ltTuple ts } where
ts = map getType es
eTuple :: [E] -> E
eTuple = tuple
eTuple' es = ELit $ unboxedTuple es
unboxedTuple es = litCons { litName = unboxedNameTuple DataConstructor (length es), litArgs = es, litType = ltTuple' ts } where
ts = map getType es
unboxedUnit :: E
unboxedUnit = ELit $ unboxedTuple []
unboxedTyUnit :: E
unboxedTyUnit = ltTuple' []
class ToE a where
toE :: a -> E
typeE :: a -> E -- lazy in a
class ToEzh a where
toEzh :: a -> E
typeEzh :: a -> E
instance ToEzh Char where
toEzh ch = ELit $ LitInt (fromIntegral $ fromEnum ch) tCharzh
typeEzh _ = tCharzh
instance ToEzh Int where
toEzh ch = ELit $ LitInt (fromIntegral ch) tIntzh
typeEzh _ = tIntzh
instance ToEzh Integer where
toEzh ch = ELit $ LitInt (fromIntegral ch) tIntegerzh
typeEzh _ = tIntegerzh
instance ToE () where
toE () = vUnit
typeE _ = tUnit
instance ToE Bool where
toE True = vTrue
toE False = vFalse
typeE _ = tBool
instance ToE Char where
toE ch = ELit (litCons { litName = dc_Char, litArgs = [toEzh ch], litType = tChar })
typeE _ = tChar
instance ToE Rational where
toE rat = ELit (litCons { litName = dc_Ratio, litArgs = [toE (numerator rat), toE (denominator rat)], litType = tRational })
typeE _ = tRational
instance ToE Integer where
toE ch = ELit (litCons { litName = dc_Integer, litArgs = [toEzh ch], litType = tInteger })
typeE _ = tInteger
instance ToE Int where
toE ch = ELit (litCons { litName = dc_Int, litArgs = [toEzh ch], litType = tInt })
typeE _ = tInt
instance ToE a => ToE [a] where
toE xs@[] = eNil (typeE xs)
toE (x:xs) = eCons (toE x) (toE xs)
typeE (_::[a]) = ELit (litCons { litName = tc_List, litArgs = [typeE (undefined::a)], litType = eStar })
eInt x = ELit $ LitInt x tInt
eCons x xs = ELit $ litCons { litName = dc_Cons, litArgs = [x,xs], litType = getType xs }
eNil t = ELit $ litCons { litName = dc_EmptyList, litArgs = [], litType = t }
emptyCase = ECase {
eCaseAllFV = mempty,
eCaseDefault = Nothing,
eCaseAlts = [],
eCaseBind = error "emptyCase: bind",
eCaseType = error "emptyCase: type",
eCaseScrutinee = error "emptyCase: scrutinee"
}
eCaseTup e vs w = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType w, eCaseAlts = [Alt litCons { litName = nameTuple DataConstructor (length vs), litArgs = vs, litType = getType e } w] }
eCaseTup' e vs w = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType w, eCaseAlts = [Alt litCons { litName = unboxedNameTuple DataConstructor (length vs), litArgs = vs, litType = getType e} w] }
eJustIO w x = eTuple' [w,x]
eCase e alts@(alt:_) Unknown = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType alt, eCaseAlts = alts }
eCase e alts els = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseDefault = Just els, eCaseAlts = alts, eCaseType = getType els }
-- | This takes care of types right away, it simplifies various other things to do it this way.
eLet :: TVr -> E -> E -> E
eLet TVr { tvrIdent = eid } _ e' | eid == emptyId = e'
eLet t@(TVr { tvrType = ty}) e e'
| sortKindLike ty && isAtomic e = subst t e e'
| sortKindLike ty = ELetRec [(t,e)] (typeSubst mempty (msingleton (tvrIdent t) e) e')
| isUnboxed ty && isAtomic e = subst t e e'
| isUnboxed ty = eStrictLet t e e'
eLet t e e' = ELetRec [(t,e)] e'
-- | strict version of let, evaluates argument before assigning it.
eStrictLet t@(TVr { tvrType = ty }) v e | sortKindLike ty = eLet t v e
eStrictLet t v e = caseUpdate emptyCase { eCaseScrutinee = v, eCaseBind = t, eCaseDefault = Just e, eCaseType = getType e }
substLet :: [(TVr,E)] -> E -> E
substLet ds e = ans where
(as,nas) = partition (isAtomic . snd) (filter ((/= emptyId) . tvrIdent . fst) ds)
tas = filter (sortKindLike . tvrType . fst) nas
ans = eLetRec (as ++ nas) (typeSubst' (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- as]) (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- tas]) e)
substLet' :: [(TVr,E)] -> E -> E
substLet' ds' e = ans where
(hh,ds) = partition (isUnboxed . tvrType . fst) ds'
nas = filter ((/= emptyId) . tvrIdent . fst) ds
tas = filter (sortKindLike . tvrType . fst) nas
ans = case (nas,tas) of
([],_) -> hhh hh $ e
(nas,[]) -> hhh hh $ ELetRec nas e
_ -> let
f = typeSubst' mempty (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- tas])
nas' = [ (v,f e) | (v,e) <- nas]
in hhh hh $ ELetRec nas' (f e)
hhh [] e = e
hhh ((h,v):hh) e = eLet h v (hhh hh e)
eLetRec = substLet'
prim_seq a b | isWHNF a = b
prim_seq a b = caseUpdate emptyCase { eCaseScrutinee = a, eCaseBind = (tVr emptyId (getType a)), eCaseDefault = Just b, eCaseType = getType b }
prim_unsafeCoerce e t = p e' where
(_,e',p) = unsafeCoerceOpt $ EPrim p_unsafeCoerce [e] t
from_unsafeCoerce (EPrim pp [e] t) | pp == p_unsafeCoerce = return (e,t)
from_unsafeCoerce _ = fail "Not unsafeCoerce primitive"
isState_ e = case e of
ELit (LitCons { litName = name }) | name == tc_State_ -> True
_ -> False
unsafeCoerceOpt (EPrim uc [e] t) | uc == p_unsafeCoerce = f (0::Int) e t where
f n e t | Just (e',_) <- from_unsafeCoerce e = f (n + 1) e' t
f n (ELetRec ds e) t = (n + 1, ELetRec ds (p e'),id) where
(n,e',p) = f n e t
f n (EError err _) t = (n,EError err t,id)
f n (ELit (LitInt x _)) t = (n,ELit (LitInt x t),id)
f n (ELit lc@LitCons {}) t = (n,ELit lc { litType = t },id)
f n ec@ECase {} t = (n,caseUpdate nx { eCaseType = t },id) where
Identity nx = caseBodiesMapM (return . flip prim_unsafeCoerce t) ec
f n e t | getType e == t = (n,e,id)
f n e t = (n,e,\z -> EPrim p_unsafeCoerce [z] t)
unsafeCoerceOpt e = (0,e,id)
instance HasInfo TVr where
getInfo = tvrInfo
modifyInfo = tvrInfo_u
-- various routines used to classify expressions
-- many assume atomicity constraints are in place
-- | whether a value is a compile time constant
isFullyConst :: E -> Bool
isFullyConst (ELit LitCons { litArgs = [] }) = True
isFullyConst (ELit LitCons { litArgs = xs }) = all isFullyConst xs
isFullyConst ELit {} = True
isFullyConst (EPi (TVr { tvrType = t }) x) = isFullyConst t && isFullyConst x
isFullyConst (EPrim p as _) = primIsConstant p && all isFullyConst as
isFullyConst _ = False
-- | whether a value may be used as an argument to an application, literal, or primitive
-- these may be duplicated with no code size or runtime penalty
isAtomic :: E -> Bool
isAtomic EVar {} = True
isAtomic e | sortTypeLike e = True
isAtomic (EPrim don [x,y] _) | don == p_dependingOn = isAtomic x
isAtomic e = isFullyConst e
-- | whether a type is "obviously" atomic. fast and lazy, doesn't recurse
-- True -> definitely atomic
-- False -> maybe atomic
isManifestAtomic :: E -> Bool
isManifestAtomic EVar {} = True
isManifestAtomic (ELit LitInt {}) = True
isManifestAtomic (ELit LitCons { litArgs = []}) = True
isManifestAtomic _ = False
-- | whether an expression is small enough that it can be duplicated without code size growing too much. (work may be repeated)
isSmall e | isAtomic e = True
isSmall ELit {} = True
isSmall EPrim {} = True
isSmall EError {} = True
isSmall e | (EVar _,xs) <- fromAp e = length xs <= 4
isSmall _ = False
-- | whether an expression may be duplicated or pushed inside a lambda without duplicating too much work
isCheap :: E -> Bool
isCheap EError {} = True
isCheap ELit {} = True
isCheap EPi {} = True
isCheap ELam {} = True -- should exclude values dropped at compile time
isCheap x | isAtomic x = True
isCheap (EPrim p _ _) = primIsCheap p
isCheap ec@ECase {} = isCheap (eCaseScrutinee ec) && all isCheap (caseBodies ec)
isCheap e | (EVar v,xs) <- fromAp e, Just (Arity n b) <- Info.lookup (tvrInfo v) =
(length xs < n) -- Partial applications are cheap
|| (b && length xs >= n) -- bottoming out routines are cheap
isCheap _ = False
-- | determine if term can contain _|_
isLifted :: E -> Bool
isLifted x = sortTermLike x && not (isUnboxed (getType x))
-- Note: This does not treat lambdas as whnf
whnfOrBot :: E -> Bool
whnfOrBot (EError {}) = True
whnfOrBot (ELit LitCons { litArgs = xs }) = all isAtomic xs
whnfOrBot (EPi (TVr { tvrIdent = j, tvrType = x }) y) | not (j `member` (freeVars y :: IdSet)) = isAtomic x && isAtomic y
whnfOrBot ELam {} = True
whnfOrBot e | isAtomic e = True
whnfOrBot e | (EVar v,xs) <- fromAp e, Just (Arity n True) <- Info.lookup (tvrInfo v), length xs >= n = True
whnfOrBot _ = False
-- Determine if a type represents an unboxed value
isUnboxed :: E -> Bool
isUnboxed e@EPi {} = False
isUnboxed e = getType e == eHash
safeToDup ec@ECase {}
| EVar _ <- eCaseScrutinee ec = all safeToDup (caseBodies ec)
| EPrim p _ _ <- eCaseScrutinee ec, primIsCheap p = all safeToDup (caseBodies ec)
safeToDup (EPrim p _ _) = primIsCheap p
safeToDup e = whnfOrBot e || isELam e || isEPi e
eToPat e = f e where
f (ELit LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = do
ts <- mapM cv ts
return litCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }
f (ELit (LitInt e t)) = return (LitInt e t)
f (EPi (TVr { tvrType = a}) b) = do
a <- cv a
b <- cv b
return litCons { litName = tc_Arrow, litArgs = [a,b], litType = eStar }
f x = fail $ "E.Values.eToPat: " ++ show x
cv (EVar v) = return v
cv e = fail $ "E.Value.eToPat.cv: " ++ show e
patToE p = f p where
f LitCons { litName = arr, litArgs = [a,b], litType = t} | t == eStar = return $ EPi tvr { tvrType = EVar a } (EVar b)
f (LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = do
return $ ELit litCons { litAliasFor = af, litName = x, litArgs = map EVar ts, litType = t }
f (LitInt e t) = return $ ELit (LitInt e t)
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-core/src/E/Values.hs | haskell | lazy in a
| This takes care of types right away, it simplifies various other things to do it this way.
| strict version of let, evaluates argument before assigning it.
various routines used to classify expressions
many assume atomicity constraints are in place
| whether a value is a compile time constant
| whether a value may be used as an argument to an application, literal, or primitive
these may be duplicated with no code size or runtime penalty
| whether a type is "obviously" atomic. fast and lazy, doesn't recurse
True -> definitely atomic
False -> maybe atomic
| whether an expression is small enough that it can be duplicated without code size growing too much. (work may be repeated)
| whether an expression may be duplicated or pushed inside a lambda without duplicating too much work
should exclude values dropped at compile time
Partial applications are cheap
bottoming out routines are cheap
| determine if term can contain _|_
Note: This does not treat lambdas as whnf
Determine if a type represents an unboxed value | module E.Values where
import Control.Monad.Identity
import Data.Monoid
import List
import Ratio
import C.Prims
import E.E
import E.FreeVars()
import E.Subst
import E.TypeCheck
import Info.Info(HasInfo(..))
import Info.Types
import Name.Id
import Name.Name
import Name.Names
import Name.VConsts
import Support.CanType
import Support.FreeVars
import Support.Tuple
import Util.SetLike
import qualified Info.Info as Info
instance Tuple E where
tupleNil = vUnit
tupleMany es = ELit litCons { litName = nameTuple DataConstructor (length es), litArgs = es, litType = ltTuple ts } where
ts = map getType es
eTuple :: [E] -> E
eTuple = tuple
eTuple' es = ELit $ unboxedTuple es
unboxedTuple es = litCons { litName = unboxedNameTuple DataConstructor (length es), litArgs = es, litType = ltTuple' ts } where
ts = map getType es
unboxedUnit :: E
unboxedUnit = ELit $ unboxedTuple []
unboxedTyUnit :: E
unboxedTyUnit = ltTuple' []
class ToE a where
toE :: a -> E
class ToEzh a where
toEzh :: a -> E
typeEzh :: a -> E
instance ToEzh Char where
toEzh ch = ELit $ LitInt (fromIntegral $ fromEnum ch) tCharzh
typeEzh _ = tCharzh
instance ToEzh Int where
toEzh ch = ELit $ LitInt (fromIntegral ch) tIntzh
typeEzh _ = tIntzh
instance ToEzh Integer where
toEzh ch = ELit $ LitInt (fromIntegral ch) tIntegerzh
typeEzh _ = tIntegerzh
instance ToE () where
toE () = vUnit
typeE _ = tUnit
instance ToE Bool where
toE True = vTrue
toE False = vFalse
typeE _ = tBool
instance ToE Char where
toE ch = ELit (litCons { litName = dc_Char, litArgs = [toEzh ch], litType = tChar })
typeE _ = tChar
instance ToE Rational where
toE rat = ELit (litCons { litName = dc_Ratio, litArgs = [toE (numerator rat), toE (denominator rat)], litType = tRational })
typeE _ = tRational
instance ToE Integer where
toE ch = ELit (litCons { litName = dc_Integer, litArgs = [toEzh ch], litType = tInteger })
typeE _ = tInteger
instance ToE Int where
toE ch = ELit (litCons { litName = dc_Int, litArgs = [toEzh ch], litType = tInt })
typeE _ = tInt
instance ToE a => ToE [a] where
toE xs@[] = eNil (typeE xs)
toE (x:xs) = eCons (toE x) (toE xs)
typeE (_::[a]) = ELit (litCons { litName = tc_List, litArgs = [typeE (undefined::a)], litType = eStar })
eInt x = ELit $ LitInt x tInt
eCons x xs = ELit $ litCons { litName = dc_Cons, litArgs = [x,xs], litType = getType xs }
eNil t = ELit $ litCons { litName = dc_EmptyList, litArgs = [], litType = t }
emptyCase = ECase {
eCaseAllFV = mempty,
eCaseDefault = Nothing,
eCaseAlts = [],
eCaseBind = error "emptyCase: bind",
eCaseType = error "emptyCase: type",
eCaseScrutinee = error "emptyCase: scrutinee"
}
eCaseTup e vs w = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType w, eCaseAlts = [Alt litCons { litName = nameTuple DataConstructor (length vs), litArgs = vs, litType = getType e } w] }
eCaseTup' e vs w = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType w, eCaseAlts = [Alt litCons { litName = unboxedNameTuple DataConstructor (length vs), litArgs = vs, litType = getType e} w] }
eJustIO w x = eTuple' [w,x]
eCase e alts@(alt:_) Unknown = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseType = getType alt, eCaseAlts = alts }
eCase e alts els = caseUpdate emptyCase { eCaseScrutinee = e, eCaseBind = (tVr emptyId (getType e)), eCaseDefault = Just els, eCaseAlts = alts, eCaseType = getType els }
eLet :: TVr -> E -> E -> E
eLet TVr { tvrIdent = eid } _ e' | eid == emptyId = e'
eLet t@(TVr { tvrType = ty}) e e'
| sortKindLike ty && isAtomic e = subst t e e'
| sortKindLike ty = ELetRec [(t,e)] (typeSubst mempty (msingleton (tvrIdent t) e) e')
| isUnboxed ty && isAtomic e = subst t e e'
| isUnboxed ty = eStrictLet t e e'
eLet t e e' = ELetRec [(t,e)] e'
eStrictLet t@(TVr { tvrType = ty }) v e | sortKindLike ty = eLet t v e
eStrictLet t v e = caseUpdate emptyCase { eCaseScrutinee = v, eCaseBind = t, eCaseDefault = Just e, eCaseType = getType e }
substLet :: [(TVr,E)] -> E -> E
substLet ds e = ans where
(as,nas) = partition (isAtomic . snd) (filter ((/= emptyId) . tvrIdent . fst) ds)
tas = filter (sortKindLike . tvrType . fst) nas
ans = eLetRec (as ++ nas) (typeSubst' (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- as]) (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- tas]) e)
substLet' :: [(TVr,E)] -> E -> E
substLet' ds' e = ans where
(hh,ds) = partition (isUnboxed . tvrType . fst) ds'
nas = filter ((/= emptyId) . tvrIdent . fst) ds
tas = filter (sortKindLike . tvrType . fst) nas
ans = case (nas,tas) of
([],_) -> hhh hh $ e
(nas,[]) -> hhh hh $ ELetRec nas e
_ -> let
f = typeSubst' mempty (fromList [ (n,e) | (TVr { tvrIdent = n },e) <- tas])
nas' = [ (v,f e) | (v,e) <- nas]
in hhh hh $ ELetRec nas' (f e)
hhh [] e = e
hhh ((h,v):hh) e = eLet h v (hhh hh e)
eLetRec = substLet'
prim_seq a b | isWHNF a = b
prim_seq a b = caseUpdate emptyCase { eCaseScrutinee = a, eCaseBind = (tVr emptyId (getType a)), eCaseDefault = Just b, eCaseType = getType b }
prim_unsafeCoerce e t = p e' where
(_,e',p) = unsafeCoerceOpt $ EPrim p_unsafeCoerce [e] t
from_unsafeCoerce (EPrim pp [e] t) | pp == p_unsafeCoerce = return (e,t)
from_unsafeCoerce _ = fail "Not unsafeCoerce primitive"
isState_ e = case e of
ELit (LitCons { litName = name }) | name == tc_State_ -> True
_ -> False
unsafeCoerceOpt (EPrim uc [e] t) | uc == p_unsafeCoerce = f (0::Int) e t where
f n e t | Just (e',_) <- from_unsafeCoerce e = f (n + 1) e' t
f n (ELetRec ds e) t = (n + 1, ELetRec ds (p e'),id) where
(n,e',p) = f n e t
f n (EError err _) t = (n,EError err t,id)
f n (ELit (LitInt x _)) t = (n,ELit (LitInt x t),id)
f n (ELit lc@LitCons {}) t = (n,ELit lc { litType = t },id)
f n ec@ECase {} t = (n,caseUpdate nx { eCaseType = t },id) where
Identity nx = caseBodiesMapM (return . flip prim_unsafeCoerce t) ec
f n e t | getType e == t = (n,e,id)
f n e t = (n,e,\z -> EPrim p_unsafeCoerce [z] t)
unsafeCoerceOpt e = (0,e,id)
instance HasInfo TVr where
getInfo = tvrInfo
modifyInfo = tvrInfo_u
isFullyConst :: E -> Bool
isFullyConst (ELit LitCons { litArgs = [] }) = True
isFullyConst (ELit LitCons { litArgs = xs }) = all isFullyConst xs
isFullyConst ELit {} = True
isFullyConst (EPi (TVr { tvrType = t }) x) = isFullyConst t && isFullyConst x
isFullyConst (EPrim p as _) = primIsConstant p && all isFullyConst as
isFullyConst _ = False
isAtomic :: E -> Bool
isAtomic EVar {} = True
isAtomic e | sortTypeLike e = True
isAtomic (EPrim don [x,y] _) | don == p_dependingOn = isAtomic x
isAtomic e = isFullyConst e
isManifestAtomic :: E -> Bool
isManifestAtomic EVar {} = True
isManifestAtomic (ELit LitInt {}) = True
isManifestAtomic (ELit LitCons { litArgs = []}) = True
isManifestAtomic _ = False
isSmall e | isAtomic e = True
isSmall ELit {} = True
isSmall EPrim {} = True
isSmall EError {} = True
isSmall e | (EVar _,xs) <- fromAp e = length xs <= 4
isSmall _ = False
isCheap :: E -> Bool
isCheap EError {} = True
isCheap ELit {} = True
isCheap EPi {} = True
isCheap x | isAtomic x = True
isCheap (EPrim p _ _) = primIsCheap p
isCheap ec@ECase {} = isCheap (eCaseScrutinee ec) && all isCheap (caseBodies ec)
isCheap e | (EVar v,xs) <- fromAp e, Just (Arity n b) <- Info.lookup (tvrInfo v) =
isCheap _ = False
isLifted :: E -> Bool
isLifted x = sortTermLike x && not (isUnboxed (getType x))
whnfOrBot :: E -> Bool
whnfOrBot (EError {}) = True
whnfOrBot (ELit LitCons { litArgs = xs }) = all isAtomic xs
whnfOrBot (EPi (TVr { tvrIdent = j, tvrType = x }) y) | not (j `member` (freeVars y :: IdSet)) = isAtomic x && isAtomic y
whnfOrBot ELam {} = True
whnfOrBot e | isAtomic e = True
whnfOrBot e | (EVar v,xs) <- fromAp e, Just (Arity n True) <- Info.lookup (tvrInfo v), length xs >= n = True
whnfOrBot _ = False
isUnboxed :: E -> Bool
isUnboxed e@EPi {} = False
isUnboxed e = getType e == eHash
safeToDup ec@ECase {}
| EVar _ <- eCaseScrutinee ec = all safeToDup (caseBodies ec)
| EPrim p _ _ <- eCaseScrutinee ec, primIsCheap p = all safeToDup (caseBodies ec)
safeToDup (EPrim p _ _) = primIsCheap p
safeToDup e = whnfOrBot e || isELam e || isEPi e
eToPat e = f e where
f (ELit LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = do
ts <- mapM cv ts
return litCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }
f (ELit (LitInt e t)) = return (LitInt e t)
f (EPi (TVr { tvrType = a}) b) = do
a <- cv a
b <- cv b
return litCons { litName = tc_Arrow, litArgs = [a,b], litType = eStar }
f x = fail $ "E.Values.eToPat: " ++ show x
cv (EVar v) = return v
cv e = fail $ "E.Value.eToPat.cv: " ++ show e
patToE p = f p where
f LitCons { litName = arr, litArgs = [a,b], litType = t} | t == eStar = return $ EPi tvr { tvrType = EVar a } (EVar b)
f (LitCons { litAliasFor = af, litName = x, litArgs = ts, litType = t }) = do
return $ ELit litCons { litAliasFor = af, litName = x, litArgs = map EVar ts, litType = t }
f (LitInt e t) = return $ ELit (LitInt e t)
|
6af514a7084c31c5dffc293e80d91d4f51c46f25d4a2b6eb44d6fa04b17c3ba2 | emqx/emqttb | emqttb_http.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqttb_http).
%% API:
-export([start_link/0, doc/0]).
-export_type([rest_options/0]).
-include("emqttb.hrl").
-import(lee_doc, [sect/3, p/1, li/2, href/2]).
%%================================================================================
%% Type declarations
%%================================================================================
-type rest_options() :: map().
%%================================================================================
%% API funcions
%%================================================================================
-include_lib("kernel/include/logger.hrl").
-spec start_link() -> {ok, pid()} | {error, _}.
start_link() ->
{IP, Port} = ?CFG([restapi, listen_port]),
logger:info("Starting REST API at ~p:~p", [IP, Port]),
TransportOpts = #{ port => Port
, ip => IP
},
Env = #{dispatch => dispatch()},
ProtocolOpts = #{env => Env},
StartFun = case ?CFG([restapi, tls]) of
true ->
?LOG_INFO("Starting HTTPS listener with parameters ~p", [ProtocolOpts]),
fun cowboy:start_tls/3;
false ->
?LOG_INFO("Starting HTTP listener with parameters ~p", [ProtocolOpts]),
fun cowboy:start_clear/3
end,
StartFun(rest_api, maps:to_list(TransportOpts), ProtocolOpts).
doc() ->
[{listitem,
[{para,
[ href(":" ++ integer_to_list(?DEFAULT_PORT) ++ Path, Path)
, ": "
, Mod:descr()
]}]}
|| {Path, Mod, _} <- routes()].
%%================================================================================
Internal functions
%%================================================================================
dispatch() ->
cowboy_router:compile([{'_', routes()}]).
routes() ->
[ {"/healthcheck", emqttb_http_healthcheck, []}
, {"/metrics", emqttb_http_metrics, []}
, {"/scenario/:scenario/stage", emqttb_http_stage, []}
, {"/conf/reload", emqttb_http_sighup, []}
].
| null | https://raw.githubusercontent.com/emqx/emqttb/0b1b95935b0963c2f7a86f4d33f17c7e14ac6f15/src/restapi/emqttb_http.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
API:
================================================================================
Type declarations
================================================================================
================================================================================
API funcions
================================================================================
================================================================================
================================================================================ | Copyright ( c ) 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqttb_http).
-export([start_link/0, doc/0]).
-export_type([rest_options/0]).
-include("emqttb.hrl").
-import(lee_doc, [sect/3, p/1, li/2, href/2]).
-type rest_options() :: map().
-include_lib("kernel/include/logger.hrl").
-spec start_link() -> {ok, pid()} | {error, _}.
start_link() ->
{IP, Port} = ?CFG([restapi, listen_port]),
logger:info("Starting REST API at ~p:~p", [IP, Port]),
TransportOpts = #{ port => Port
, ip => IP
},
Env = #{dispatch => dispatch()},
ProtocolOpts = #{env => Env},
StartFun = case ?CFG([restapi, tls]) of
true ->
?LOG_INFO("Starting HTTPS listener with parameters ~p", [ProtocolOpts]),
fun cowboy:start_tls/3;
false ->
?LOG_INFO("Starting HTTP listener with parameters ~p", [ProtocolOpts]),
fun cowboy:start_clear/3
end,
StartFun(rest_api, maps:to_list(TransportOpts), ProtocolOpts).
doc() ->
[{listitem,
[{para,
[ href(":" ++ integer_to_list(?DEFAULT_PORT) ++ Path, Path)
, ": "
, Mod:descr()
]}]}
|| {Path, Mod, _} <- routes()].
Internal functions
dispatch() ->
cowboy_router:compile([{'_', routes()}]).
routes() ->
[ {"/healthcheck", emqttb_http_healthcheck, []}
, {"/metrics", emqttb_http_metrics, []}
, {"/scenario/:scenario/stage", emqttb_http_stage, []}
, {"/conf/reload", emqttb_http_sighup, []}
].
|
8a2ebf8f1b3a9f03b397af2aedd01ddec3bcbbbb4a69ecf770d0360c6cdc02b6 | lambdaisland/open-source | gh_actions.clj | (ns lioss.gh-actions
(:require [clojure.string :as str]))
;; -Actions/set-output-Truncates-Multiline-Strings/m-p/38372#M3322
(defn multiline-escape [s]
(-> s
(str/replace #"%" "%25")
(str/replace #"\n" "%0A")
(str/replace #"\r" "%0D")))
(defn changelog-stanza []
(-> "CHANGELOG.md"
slurp
(str/split #"\n")
(->> (drop-while #(not (re-find #"^# \d" %)))
next
(take-while #(not (re-find #"^# \d" %)))
(remove str/blank?)
(str/join "\n"))
multiline-escape))
(defn set-changelog-output [opts]
(println (str "::set-output name=changelog::" (changelog-stanza))))
| null | https://raw.githubusercontent.com/lambdaisland/open-source/02debf4a8feee5d1370413b9c30b6d33e28cdc45/src/lioss/gh_actions.clj | clojure | -Actions/set-output-Truncates-Multiline-Strings/m-p/38372#M3322 | (ns lioss.gh-actions
(:require [clojure.string :as str]))
(defn multiline-escape [s]
(-> s
(str/replace #"%" "%25")
(str/replace #"\n" "%0A")
(str/replace #"\r" "%0D")))
(defn changelog-stanza []
(-> "CHANGELOG.md"
slurp
(str/split #"\n")
(->> (drop-while #(not (re-find #"^# \d" %)))
next
(take-while #(not (re-find #"^# \d" %)))
(remove str/blank?)
(str/join "\n"))
multiline-escape))
(defn set-changelog-output [opts]
(println (str "::set-output name=changelog::" (changelog-stanza))))
|
c7f643884b1bf6096cf7069e90aaf942a7f45280051eb1eceaf80f95f13f1b1e | Bike/mother | env.lisp | ;;;; env.lisp
;;;; interface to environments
(in-package #:mother)
(defclass environment () ()) ; abstract, for subtyping
LOOKUP and FLAT - LOOKUP return two values , like GETHASH .
;;; FLAT- just means that any parents of the environments aren't relevant.
( SETF LOOKUP ) is presently mostly unimplemented because does n't need it .
(defgeneric lookup (environment key))
(defgeneric (setf lookup) (value environment key)
(:argument-precedence-order environment key value))
(defgeneric flat-lookup (environment key))
(defgeneric (setf flat-lookup) (value environment key)
(:argument-precedence-order environment key value))
| null | https://raw.githubusercontent.com/Bike/mother/be571bcc8ed2a9f6c65a5d73e5e711509499420b/env.lisp | lisp | env.lisp
interface to environments
abstract, for subtyping
FLAT- just means that any parents of the environments aren't relevant. |
(in-package #:mother)
LOOKUP and FLAT - LOOKUP return two values , like GETHASH .
( SETF LOOKUP ) is presently mostly unimplemented because does n't need it .
(defgeneric lookup (environment key))
(defgeneric (setf lookup) (value environment key)
(:argument-precedence-order environment key value))
(defgeneric flat-lookup (environment key))
(defgeneric (setf flat-lookup) (value environment key)
(:argument-precedence-order environment key value))
|
86134c062defe7cc5a2d3cf3206738d54ec8130f8e0ee7ec662e60813595d260 | guicho271828/eazy-project | actually-create-project.lisp | (in-package :eazy-project)
(lispn:define-namespace processor)
(defvar *done* nil)
(defun actually-create-project ()
(let ((*done* nil))
(iter (for failure =
(iter
(for (key value) in-hashtable *processor-table*)
(count (not (funcall value)))))
(for prev previous failure)
(until (zerop failure))
(unless (first-time-p)
(when (= failure prev)
(error "~&Dependency not satisfied! This is a shame, consult to a developper"))))
( format t " ~2&Processing templates .
;; Global Parameters:
~{~20@<~s~ > = ~s~%~ } " * config * )
(format t "~2&Processing templates.
Actual Parameters:
~{~20@<~s~> = ~s~%~}" *project-config*)
(let ((*default-pathname-defaults*
(uiop:ensure-directory-pathname
(merge-pathnames (l :name) (l :local-repository)))))
(ensure-directories-exist *default-pathname-defaults*)
;; creation
(unwind-protect-case ()
(let ((*print-case* :downcase))
(mapc #'process-file
(remove-if #'includes-p
(split "
"
(shell-command
(format nil "find ~a" (l :skeleton-directory)))))))
(:abort (shell-command
(format nil "rm -rf ~a"
*default-pathname-defaults*))))
;; git
(when (l :git)
(princ (shell-command
(format nil "cd ~a; git init; git add $(git ls-files -o); git commit -m \"Auto initial commit by eazy-project\""
*default-pathname-defaults*))))
;; autoload asd
(or (probe-file
(merge-pathnames
(format nil "~a.asd" (l :name))))
(error "failed to create a new repo!"))
(load (merge-pathnames
(format nil "~a.asd" (l :name))))
(asdf:load-system (l :name)))))
(defun includes-p (path)
(or (string=
"includes"
(lastcar
(pathname-directory path)))
(string=
"includes"
(pathname-name path))))
(defun process-file (file)
(handler-case
(let* ((tpl-path (merge-pathnames file))
(tpl-name (namestring tpl-path)))
;; might be confusing, but cl-emb treat pathnames and strings
;; differently
(register-emb tpl-name tpl-name)
(let* ((*default-pathname-defaults* tpl-path)
(processed-filename
(execute-emb ; convert the filename
tpl-name :env *project-config*))
e.g. /tmp / skeleton/<% @var x % > /<% @var y % >
;; -> . /tmp/skeleton/x/y.lisp
;; next, get the relative pathname
(relative-from-skeleton
(enough-namestring
processed-filename
(uiop:ensure-directory-pathname
(l :skeleton-directory))))
;; this should be x/y.lisp
then merge to the target
;; e.g. ~/myrepos/ + x/y.lisp
(final-pathname
(merge-pathnames
relative-from-skeleton
(l :local-repository))))
(ensure-directories-exist final-pathname :verbose t)
;; now convert the contents
(let ((str (execute-emb tpl-path :env *project-config*)))
(with-open-file (s final-pathname
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(princ str s)))))
(stream-error ()
;; failed to open a file; e.g. a file is a directory
(warn "Failed to process ~a" file))
(file-error ()
;; failed to open a file; e.g. a file is a directory
(warn "Failed to process ~a" file))))
(defmacro defprocessor ((key &optional
(global (gensym "G"))
(local (gensym "L"))
depends-on)
&body body)
(assert (listp depends-on))
`(add-processor
,key
',depends-on
(lambda ()
(symbol-macrolet ((,global (g ,key))
(,local (l ,key)))
(declare (ignorable ,global ,local))
,@body))))
(defun add-processor (key depends-on fn)
(setf (symbol-processor key)
(lambda ()
(if (done key)
t
(when (progn
(format t "~&Checking dependency of ~a: ~a"
key depends-on)
(every #'done depends-on))
(format t "~&Running processor ~a" key)
(funcall fn)
(push key *done*)
t)))))
(defun done (key)
(find key *done*))
;; local information supersedes the global settings by default.
(iter (for (key value . rest) on *config* by #'cddr)
(let ((key key))
(add-processor
key nil
(lambda ()
(format t "~% Superseding the global settings...")
(setf (l key)
(or (l key)
(g key)))
(print *project-config*)))))
;; however, few are not...
;; required field
(defprocessor (:name g l)
(handler-case
(assert l nil "the project name is not provided!")
(error (c)
(declare (ignore c))
(%name))))
(defprocessor (:description g l)
(handler-case
(assert l nil "the description is not provided! It annoys Zach on quicklisp submission!")
(error (c)
(declare (ignore c))
(%description))))
;; appended to global settings
(defprocessor (:depends-on g l) (setf l (union l g)))
;; depends on above fields
(defprocessor (:test-template g l (:test))
(setf l (format nil "~(~a~).lisp" ; includes/fiveam.lisp
(l :test))))
(defprocessor (:test-name g l (:name :test-subname :delimiter))
(setf l (format nil "~a~a~a"
(l :name)
(l :delimiter)
(l :test-subname))))
(defprocessor (:readme-filename g l (:readme-extension))
(setf l (format nil "README.~a"
(l :readme-extension))))
| null | https://raw.githubusercontent.com/guicho271828/eazy-project/518c8b6792975893a351ae6f76c0a2b5eb412773/src/create/actually-create-project.lisp | lisp | Global Parameters:
creation
git
autoload asd
might be confusing, but cl-emb treat pathnames and strings
differently
convert the filename
-> . /tmp/skeleton/x/y.lisp
next, get the relative pathname
this should be x/y.lisp
e.g. ~/myrepos/ + x/y.lisp
now convert the contents
failed to open a file; e.g. a file is a directory
failed to open a file; e.g. a file is a directory
local information supersedes the global settings by default.
however, few are not...
required field
appended to global settings
depends on above fields
includes/fiveam.lisp | (in-package :eazy-project)
(lispn:define-namespace processor)
(defvar *done* nil)
(defun actually-create-project ()
(let ((*done* nil))
(iter (for failure =
(iter
(for (key value) in-hashtable *processor-table*)
(count (not (funcall value)))))
(for prev previous failure)
(until (zerop failure))
(unless (first-time-p)
(when (= failure prev)
(error "~&Dependency not satisfied! This is a shame, consult to a developper"))))
( format t " ~2&Processing templates .
~{~20@<~s~ > = ~s~%~ } " * config * )
(format t "~2&Processing templates.
Actual Parameters:
~{~20@<~s~> = ~s~%~}" *project-config*)
(let ((*default-pathname-defaults*
(uiop:ensure-directory-pathname
(merge-pathnames (l :name) (l :local-repository)))))
(ensure-directories-exist *default-pathname-defaults*)
(unwind-protect-case ()
(let ((*print-case* :downcase))
(mapc #'process-file
(remove-if #'includes-p
(split "
"
(shell-command
(format nil "find ~a" (l :skeleton-directory)))))))
(:abort (shell-command
(format nil "rm -rf ~a"
*default-pathname-defaults*))))
(when (l :git)
(princ (shell-command
(format nil "cd ~a; git init; git add $(git ls-files -o); git commit -m \"Auto initial commit by eazy-project\""
*default-pathname-defaults*))))
(or (probe-file
(merge-pathnames
(format nil "~a.asd" (l :name))))
(error "failed to create a new repo!"))
(load (merge-pathnames
(format nil "~a.asd" (l :name))))
(asdf:load-system (l :name)))))
(defun includes-p (path)
(or (string=
"includes"
(lastcar
(pathname-directory path)))
(string=
"includes"
(pathname-name path))))
(defun process-file (file)
(handler-case
(let* ((tpl-path (merge-pathnames file))
(tpl-name (namestring tpl-path)))
(register-emb tpl-name tpl-name)
(let* ((*default-pathname-defaults* tpl-path)
(processed-filename
tpl-name :env *project-config*))
e.g. /tmp / skeleton/<% @var x % > /<% @var y % >
(relative-from-skeleton
(enough-namestring
processed-filename
(uiop:ensure-directory-pathname
(l :skeleton-directory))))
then merge to the target
(final-pathname
(merge-pathnames
relative-from-skeleton
(l :local-repository))))
(ensure-directories-exist final-pathname :verbose t)
(let ((str (execute-emb tpl-path :env *project-config*)))
(with-open-file (s final-pathname
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(princ str s)))))
(stream-error ()
(warn "Failed to process ~a" file))
(file-error ()
(warn "Failed to process ~a" file))))
(defmacro defprocessor ((key &optional
(global (gensym "G"))
(local (gensym "L"))
depends-on)
&body body)
(assert (listp depends-on))
`(add-processor
,key
',depends-on
(lambda ()
(symbol-macrolet ((,global (g ,key))
(,local (l ,key)))
(declare (ignorable ,global ,local))
,@body))))
(defun add-processor (key depends-on fn)
(setf (symbol-processor key)
(lambda ()
(if (done key)
t
(when (progn
(format t "~&Checking dependency of ~a: ~a"
key depends-on)
(every #'done depends-on))
(format t "~&Running processor ~a" key)
(funcall fn)
(push key *done*)
t)))))
(defun done (key)
(find key *done*))
(iter (for (key value . rest) on *config* by #'cddr)
(let ((key key))
(add-processor
key nil
(lambda ()
(format t "~% Superseding the global settings...")
(setf (l key)
(or (l key)
(g key)))
(print *project-config*)))))
(defprocessor (:name g l)
(handler-case
(assert l nil "the project name is not provided!")
(error (c)
(declare (ignore c))
(%name))))
(defprocessor (:description g l)
(handler-case
(assert l nil "the description is not provided! It annoys Zach on quicklisp submission!")
(error (c)
(declare (ignore c))
(%description))))
(defprocessor (:depends-on g l) (setf l (union l g)))
(defprocessor (:test-template g l (:test))
(l :test))))
(defprocessor (:test-name g l (:name :test-subname :delimiter))
(setf l (format nil "~a~a~a"
(l :name)
(l :delimiter)
(l :test-subname))))
(defprocessor (:readme-filename g l (:readme-extension))
(setf l (format nil "README.~a"
(l :readme-extension))))
|
85a4904ecef660476fc7870bf47501636f85d99113abef56f1604697bb41f32c | devonzuegel/smallworld | frontend.cljs |
(ns smallworld.frontend
(:require [reagent.core :as r]
[reitit.frontend :as rf]
[reitit.frontend.easy :as rfe]
[reitit.frontend.controllers :as rfc]
[reitit.ring :as ring]
[reitit.coercion.schema :as rsc]
[schema.core :as s]
[clojure.test :refer [deftest is]]
[fipp.edn :as fedn]
[smallworld.session :as session]
[smallworld.decorations :as decorations]
[smallworld.screens.settings :as settings]
[smallworld.util :as util]
[smallworld.screens.home :as home]
[clojure.pprint :as pp]
[cljsjs.mapbox]
[goog.dom]
[smallworld.admin :as admin]))
(def *debug? (r/atom false))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(util/fetch "/api/v1/settings" (fn [result]
(when @*debug?
(println "/api/v1/settings:")
(pp/pprint result))
(reset! settings/*settings result)
(reset! settings/*email-address (:email_address result))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn signin-page []
[:div.welcome
[:div.hero
[:p.serif {:style {:font-size "1.5em" :margin-top "8px" :margin-bottom "4px"}}
"welcome to"]
[:h1 {:style {:font-weight "bold" :font-size "2.6em"}}
"Small World"]
[:div#logo-animation.logo (decorations/animated-globe)]
[:h2
[:a#login-btn {:href "login"} (decorations/twitter-icon) "log in with Twitter"]]]
[:div.steps
[:p [:b "step 1:"] " log in with Twitter"]
[:p [:b "step 2:"] " update what city you're in"]
[:p [:b "step 3:"] " see a map of who's nearby"]]
[:div.info
[:p "Small World uses the location from your" [:br]
[:a {:href "" :target "_blank"}
"Twitter profile"] " to find nearby friends"]]
#_[:div.faq
[:div.question
[:p [:b "Q: how does small world work?"]]
[:p "small world checks to see if the people you follow on Twitter have updated their location. it looks at two places:"]
[:ul
[:li "their display name, which small world interprets as they're traveling to that location"]
[:li "their location, which small world interprets as they're living in that location"]]]
[:hr]
[:div.question
[:p [:b "Q: why isn't my friend showing up"]]
[:p "they may not have their location set on Twitter (either in their name or in the location field), or small world may not be able to parse the location yet."]
[:p "if they have their location set but it's just not showing up in the app, please " [:a {:href ""} "open a GitHub issue"] " and share more so I can improve the city parser."]]]])
(defn home-page []
(if (:welcome_flow_complete @settings/*settings)
[home/screen]
[settings/welcome-flow-screen]))
(defn not-found-404-page []
[:p {:style {:margin "30vh auto 0 auto" :text-align "center" :font-size "2em"}}
"404 not found"])
(defonce match (r/atom nil))
(defn redirect! [path]
(.replace (.-location js/window) path))
(defn current-page [] ; TODO: handle logged out state
(if (= :loading @session/*store)
(decorations/loading-screen)
(if (nil? @match)
not-found-404-page
(let [view (:view (:data @match))]
[view @match]))))
(defn if-session-loading [next-steps-fn]
#(if (= :loading @session/*store)
(util/fetch "/api/v1/session" next-steps-fn)
(next-steps-fn @session/*store)))
(def require-blank-session
[{:start (if-session-loading #(if (empty? %)
(session/update! %)
(redirect! "/")))}])
(def require-session
[{:start (if-session-loading #(if (empty? %)
(redirect! "/signin")
(session/update! %)))}])
(def require-admin
[{:start (if-session-loading #(when (not= admin/screen-name (:screen-name %))
(redirect! "/not-found")))}])
(def routes
(rf/router
["/"
["signin" {:name ::signin :view signin-page :controllers require-blank-session}]
["" {:name ::home :view home-page :controllers require-session}]
["settings" {:name ::settings :view settings/screen :controllers require-session}]
["admin" {:name ::admin :view admin/screen :controllers require-admin}]]
{:data {:coercion rsc/coercion}}))
note – this will not get run at the same time as the clj tests
(is (= (rf/match-by-path routes "/no-match") nil))
(is (not= (rf/match-by-path routes "/settings") nil))
(is (not= (rf/match-by-path routes "/settings/") nil)))
(defn init! []
(rfe/start!
routes
(fn [new-match]
(swap! match (fn [old-match]
(when new-match
(assoc new-match :controllers (rfc/apply-controllers (:controllers old-match) new-match)))))
(util/fetch "/api/v1/session" session/update!))
{:use-fragment false})
(r/render [current-page] (.getElementById js/document "app")))
(init!) | null | https://raw.githubusercontent.com/devonzuegel/smallworld/cc8bddaa548cc090eaa7b71da2b4c94845d23a82/src/smallworld/frontend.cljs | clojure |
TODO: handle logged out state |
(ns smallworld.frontend
(:require [reagent.core :as r]
[reitit.frontend :as rf]
[reitit.frontend.easy :as rfe]
[reitit.frontend.controllers :as rfc]
[reitit.ring :as ring]
[reitit.coercion.schema :as rsc]
[schema.core :as s]
[clojure.test :refer [deftest is]]
[fipp.edn :as fedn]
[smallworld.session :as session]
[smallworld.decorations :as decorations]
[smallworld.screens.settings :as settings]
[smallworld.util :as util]
[smallworld.screens.home :as home]
[clojure.pprint :as pp]
[cljsjs.mapbox]
[goog.dom]
[smallworld.admin :as admin]))
(def *debug? (r/atom false))
(util/fetch "/api/v1/settings" (fn [result]
(when @*debug?
(println "/api/v1/settings:")
(pp/pprint result))
(reset! settings/*settings result)
(reset! settings/*email-address (:email_address result))))
(defn signin-page []
[:div.welcome
[:div.hero
[:p.serif {:style {:font-size "1.5em" :margin-top "8px" :margin-bottom "4px"}}
"welcome to"]
[:h1 {:style {:font-weight "bold" :font-size "2.6em"}}
"Small World"]
[:div#logo-animation.logo (decorations/animated-globe)]
[:h2
[:a#login-btn {:href "login"} (decorations/twitter-icon) "log in with Twitter"]]]
[:div.steps
[:p [:b "step 1:"] " log in with Twitter"]
[:p [:b "step 2:"] " update what city you're in"]
[:p [:b "step 3:"] " see a map of who's nearby"]]
[:div.info
[:p "Small World uses the location from your" [:br]
[:a {:href "" :target "_blank"}
"Twitter profile"] " to find nearby friends"]]
#_[:div.faq
[:div.question
[:p [:b "Q: how does small world work?"]]
[:p "small world checks to see if the people you follow on Twitter have updated their location. it looks at two places:"]
[:ul
[:li "their display name, which small world interprets as they're traveling to that location"]
[:li "their location, which small world interprets as they're living in that location"]]]
[:hr]
[:div.question
[:p [:b "Q: why isn't my friend showing up"]]
[:p "they may not have their location set on Twitter (either in their name or in the location field), or small world may not be able to parse the location yet."]
[:p "if they have their location set but it's just not showing up in the app, please " [:a {:href ""} "open a GitHub issue"] " and share more so I can improve the city parser."]]]])
(defn home-page []
(if (:welcome_flow_complete @settings/*settings)
[home/screen]
[settings/welcome-flow-screen]))
(defn not-found-404-page []
[:p {:style {:margin "30vh auto 0 auto" :text-align "center" :font-size "2em"}}
"404 not found"])
(defonce match (r/atom nil))
(defn redirect! [path]
(.replace (.-location js/window) path))
(if (= :loading @session/*store)
(decorations/loading-screen)
(if (nil? @match)
not-found-404-page
(let [view (:view (:data @match))]
[view @match]))))
(defn if-session-loading [next-steps-fn]
#(if (= :loading @session/*store)
(util/fetch "/api/v1/session" next-steps-fn)
(next-steps-fn @session/*store)))
(def require-blank-session
[{:start (if-session-loading #(if (empty? %)
(session/update! %)
(redirect! "/")))}])
(def require-session
[{:start (if-session-loading #(if (empty? %)
(redirect! "/signin")
(session/update! %)))}])
(def require-admin
[{:start (if-session-loading #(when (not= admin/screen-name (:screen-name %))
(redirect! "/not-found")))}])
(def routes
(rf/router
["/"
["signin" {:name ::signin :view signin-page :controllers require-blank-session}]
["" {:name ::home :view home-page :controllers require-session}]
["settings" {:name ::settings :view settings/screen :controllers require-session}]
["admin" {:name ::admin :view admin/screen :controllers require-admin}]]
{:data {:coercion rsc/coercion}}))
note – this will not get run at the same time as the clj tests
(is (= (rf/match-by-path routes "/no-match") nil))
(is (not= (rf/match-by-path routes "/settings") nil))
(is (not= (rf/match-by-path routes "/settings/") nil)))
(defn init! []
(rfe/start!
routes
(fn [new-match]
(swap! match (fn [old-match]
(when new-match
(assoc new-match :controllers (rfc/apply-controllers (:controllers old-match) new-match)))))
(util/fetch "/api/v1/session" session/update!))
{:use-fragment false})
(r/render [current-page] (.getElementById js/document "app")))
(init!) |
d1d8b47b253b11459f765eef0ba13d1b30f8550ec5f755511d9604ba6765b022 | jellelicht/guix | gperf.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages gperf)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public gperf
(package
(name "gperf")
(version "3.0.4")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"0gnnm8iqcl52m8iha3sxrzrl9mcyhg7lfrhhqgdn4zj00ji14wbn"))))
(build-system gnu-build-system)
(arguments '(#:parallel-tests? #f))
(home-page "/")
(synopsis "Perfect hash function generator")
(description
"gperf is a perfect hash function generator. For a given list of
strings, it produces a hash function and hash table in C or C++ code. That
the hash function is perfect means that no collisions can exist and that
look-ups can be made by single string comparisons.")
(license gpl3+)))
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/gperf.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
| Copyright © 2012 , 2013 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages gperf)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public gperf
(package
(name "gperf")
(version "3.0.4")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"0gnnm8iqcl52m8iha3sxrzrl9mcyhg7lfrhhqgdn4zj00ji14wbn"))))
(build-system gnu-build-system)
(arguments '(#:parallel-tests? #f))
(home-page "/")
(synopsis "Perfect hash function generator")
(description
"gperf is a perfect hash function generator. For a given list of
strings, it produces a hash function and hash table in C or C++ code. That
the hash function is perfect means that no collisions can exist and that
look-ups can be made by single string comparisons.")
(license gpl3+)))
|
c2c04cef5072f86e091ea37015e423c6cdb8b114172aa8cc324b8f1007caa62a | danieljharvey/mimsa | RawSamples.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecursiveDo #
module Test.IR.RawSamples
( print42,
useId42,
useAdd42,
useConst42Curried,
useBasicIf,
oneTuple42,
twoTuple42,
nestedTuple42,
either42,
)
where
import LLVM.AST hiding (function)
import qualified LLVM.AST.Constant as C
import qualified LLVM.AST.Operand as Op
import LLVM.AST.Type as AST
import qualified LLVM.IRBuilder.Constant as C
import LLVM.IRBuilder.Instruction
import qualified LLVM.IRBuilder.Instruction as L
import LLVM.IRBuilder.Module
import qualified LLVM.IRBuilder.Monad as L
import Smol.Core.IR.ToLLVM.Helpers
print the number 42
print42 :: Module
print42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
function "main" [] AST.i32 $ \_ -> do
_ <- call pInt [(C.int32 42, [])]
ret (C.int32 0)
print the number 42 after using i d function
useId42 :: Module
useId42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
fnId <- function "id" [(AST.i32, "a")] AST.i32 $ \case
[a] -> ret a
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
a2 <- call fnId [(C.int32 42, [])]
_ <- call pInt [(a2, [])]
ret (C.int32 0)
print the number 42 after using the const function
-- this version passes the env but calls it immediately
useAdd42 :: Module
useAdd42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
-- inputs for const2
let const2Struct = AST.StructureType False [AST.i32]
-- fn is (arg, env)
-- this is the continuation of `const` below
fnAdd2 <- function "add2" [(AST.i32, "b"), (pointerType const2Struct, "env")] AST.i32 $ \case
[b, env] -> do
% a = load i32 , i32 * % 1
a <- loadFromStruct env [0]
-- add them
res <- add a b
-- return a
ret res
other -> error (show other)
fnAdd <- function "add" [(AST.i32, "a"), (AST.i32, "b")] AST.i32 $ \case
[a, b] -> do
-- allocate room for a struct
env2 <- allocLocal "const2-struct" const2Struct
store a in
storePrimInStruct env2 [0] a
-- run next function
result <- call fnAdd2 [(b, []), (env2, [])]
-- return result
ret result
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
a2 <-
call
fnAdd
[ (C.int32 20, []),
(C.int32 22, [])
]
-- print output
_ <- call pInt [(a2, [])]
ret (C.int32 0)
-- make a one tuple, fetch from it, sum items
oneTuple42 :: Module
oneTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyOneTuple = AST.StructureType False [AST.i32]
mkTuple <- function "mkTuple" [(AST.i32, "a"), (pointerType tyOneTuple, "sret")] AST.void $ \case
[a, sRet] -> do
store a in slot 0
storePrimInStruct sRet [0] a
-- output nothing
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
oneTuple <- callWithReturnStruct mkTuple tyOneTuple [C.int32 42]
get 1st
res <- loadFromStruct oneTuple [0]
-- print output
_ <- call pInt [(res, [])]
ret (C.int32 0)
make a two tuple , fetch from it , sum items
twoTuple42 :: Module
twoTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyTwoTuple = AST.StructureType False [AST.i32, AST.i32]
mkTuple <- function
"mkTuple"
[ (AST.i32, "a"),
(AST.i32, "b"),
(pointerType tyTwoTuple, "sRet")
]
AST.void
$ \case
[a, b, sRet] -> do
llStruct <- allocLocal "mktuplestruct" tyTwoTuple
store a in
storePrimInStruct llStruct [0] a
store b in slot2
storePrimInStruct llStruct [1] b
moveToStruct llStruct sRet
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
twoTuple <- callWithReturnStruct mkTuple tyTwoTuple [C.int32 20, C.int32 22]
get 1st
var1 <- loadFromStruct twoTuple [0]
get 2nd
var2 <- loadFromStruct twoTuple [1]
-- sum the responses
res <- add var1 var2
-- print output
_ <- call pInt [(res, [])]
ret (C.int32 0)
make a nested tuple ( 10 , ( 12 , 20 ) ) and adds it all
nestedTuple42 :: Module
nestedTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyNested = struct [AST.i32, struct [AST.i32, AST.i32]]
mkNestedTuple <- function
"mkNestedTuple"
[ (AST.i32, "a"),
(AST.i32, "b"),
(AST.i32, "c"),
(pointerType tyNested, "sRet")
]
AST.void
$ \case
[a, b, c, sRet] -> do
store a in
storePrimInStruct sRet [0] a
store b in slot2
storePrimInStruct sRet [1, 0] b
-- store c
storePrimInStruct sRet [1, 1] c
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
nestedTuple <-
callWithReturnStruct
mkNestedTuple
tyNested
[ C.int32 10,
C.int32 12,
C.int32 20
]
-- get (a, (_,_))
varA <- loadFromStruct nestedTuple [0]
-- get (_, (b,_))
varB <- loadFromStruct nestedTuple [1, 0]
-- get (_, (_, c))
varC <- loadFromStruct nestedTuple [1, 1]
-- sum the responses
res1 <- add varA varB
res2 <- add res1 varC
-- print output
_ <- call pInt [(res2, [])]
ret (C.int32 0)
if True then 1 else 2
useBasicIf :: Module
useBasicIf = buildModule "exampleModule" $ do
pInt <- getPrintInt
function "main" [] AST.i32 $ \_ -> mdo
result <- alloca AST.i32 Nothing 0
let predVal = C.bit 1 -- True
L.condBr predVal thenBlock elseBlock
thenBlock <- L.block `L.named` "then"
set result to 1
store result 0 (C.int32 1)
L.br mergeBlock
elseBlock <- L.block `L.named` "else"
set result to 2
store result 0 (C.int32 2)
L.br mergeBlock
mergeBlock <- L.block `L.named` "merge"
-- do bothing
finalResult <- load result 0
_ <- call pInt [(finalResult, [])]
ret (C.int32 0)
print the number 42 after using the const function
-- this version passes the env and returns the next function
useConst42Curried :: Module
useConst42Curried = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
-- inputs for const2
let const2Struct = AST.StructureType False [AST.i32]
-- fn is (arg, env)
-- this is the continuation of `const` below
-- (int, [int]) -> int
(_fnConst2, const2Func) <- functionAndType
"const2"
[ (AST.i32, "b"),
(pointerType const2Struct, "env")
]
AST.i32
$ \case
[_b, env] ->
loadFromStruct env [0] >>= ret
other -> error (show other)
-- closure function type of const2 (fn*, env)
let const2ClosureType =
AST.StructureType
False
[ pointerType const2Func,
const2Struct
]
-- (int, (fn, [int])) -> void
fnConst <- function
"const"
[ (AST.i32, "a"),
(pointerType const2ClosureType, "sRet")
]
AST.void
$ \case
[a, sRet] -> do
store a in of env
storePrimInStruct sRet [1, 0] a
-- put fn in it
storePrimInStruct
sRet
[0]
( Op.ConstantOperand
(C.GlobalReference (pointerType const2Func) "const2")
)
-- return nothing
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
closure <- callWithReturnStruct fnConst const2ClosureType [C.int32 42]
-- call fn with env + arg
a2 <- callClosure closure (C.int32 43)
-- print output
_ <- call pInt [(a2, [])]
ret (C.int32 0)
-- -high-level-constructs-to-llvm-ir.readthedocs.io/en/latest/basic-constructs/unions.html?highlight=rust#tagged-unions
-- make a maybe, get the value out again
either42 :: Module
either42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
-- this type is only here to stake out memory
let tyEitherBoolInt = AST.StructureType False [AST.i32, AST.ArrayType 1 AST.i32]
tyRightInt = pointerType (AST.StructureType False [AST.i32, AST.i32])
tyLeftBool = pointerType (AST.StructureType False [AST.i32, AST.i1])
function "main" [] AST.i32 $ \_ -> do
CREATING RIGHT 41
first we create an Either Bool Int and put Right Int in it
rStruct <- allocLocal "mkrightstruct" tyEitherBoolInt
store 0 ( for " Right " ) in
storePrimInStruct rStruct [0] (C.int32 0)
-- case to Right Int
rStruct' <- bitcast rStruct tyRightInt
store a in slot2
storePrimInStruct rStruct' [1] (C.int32 41)
turn it back into Right Int
rStruct'' <- bitcast rStruct' (pointerType tyEitherBoolInt)
CREATING LEFT 1
first we create an Either Bool Int and put Right Int in it
lStruct <- allocLocal "mkleftStruct" tyEitherBoolInt
store 1 ( for " Left " ) in
storePrimInStruct lStruct [0] (C.int32 1)
cast to
lStruct' <- bitcast lStruct tyLeftBool
store a in slot2
storePrimInStruct lStruct' [1] (C.bit 1)
turn it back into Right Int
lStruct'' <- bitcast lStruct' (pointerType tyEitherBoolInt)
( Either Int )
fnDeconstruct <- function
"const"
[ (pointerType tyEitherBoolInt, "either")
]
AST.i32
$ \case
[input] -> mdo
-- now we pattern match
-- we're going to return this later
result <- alloca AST.i32 Nothing 0
-- get the constructor
discriminator <- loadFromStruct input [0]
L.switch discriminator rightBlock [(C.Int 32 0, rightBlock), (C.Int 32 1, leftBlock)]
rightBlock <- L.block `L.named` "right"
-- it's a Right Int
casted <- bitcast input tyRightInt
-- get the int out
myInt <- loadFromStruct casted [1]
set result to 1
store result 0 myInt
-- and merge!
L.br mergeBlock
leftBlock <- L.block `L.named` "left"
lCasted <- bitcast input tyLeftBool
myBool <- loadFromStruct lCasted [1]
intFromBool <- zext myBool AST.i32
store result 0 intFromBool
L.br mergeBlock
mergeBlock <- L.block `L.named` "merge"
-- do bothing
realResult <- load result 0
ret realResult
other -> error (show other)
rStructPointer <- gep rStruct'' [C.int32 0]
rightResult <- call fnDeconstruct [(rStructPointer, mempty)]
lStructPointer <- gep lStruct'' [C.int32 0]
leftResult <- call fnDeconstruct [(lStructPointer, mempty)]
finalResult <- add leftResult rightResult
_ <- call pInt [(finalResult, [])]
ret (C.int32 0)
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/152e4a65edcc48c2f0bec9750f2526a9dde4e99d/smol-core/test/Test/IR/RawSamples.hs | haskell | # LANGUAGE OverloadedStrings #
this version passes the env but calls it immediately
inputs for const2
fn is (arg, env)
this is the continuation of `const` below
add them
return a
allocate room for a struct
run next function
return result
print output
make a one tuple, fetch from it, sum items
output nothing
print output
sum the responses
print output
store c
get (a, (_,_))
get (_, (b,_))
get (_, (_, c))
sum the responses
print output
True
do bothing
this version passes the env and returns the next function
inputs for const2
fn is (arg, env)
this is the continuation of `const` below
(int, [int]) -> int
closure function type of const2 (fn*, env)
(int, (fn, [int])) -> void
put fn in it
return nothing
call fn with env + arg
print output
-high-level-constructs-to-llvm-ir.readthedocs.io/en/latest/basic-constructs/unions.html?highlight=rust#tagged-unions
make a maybe, get the value out again
this type is only here to stake out memory
case to Right Int
now we pattern match
we're going to return this later
get the constructor
it's a Right Int
get the int out
and merge!
do bothing | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecursiveDo #
module Test.IR.RawSamples
( print42,
useId42,
useAdd42,
useConst42Curried,
useBasicIf,
oneTuple42,
twoTuple42,
nestedTuple42,
either42,
)
where
import LLVM.AST hiding (function)
import qualified LLVM.AST.Constant as C
import qualified LLVM.AST.Operand as Op
import LLVM.AST.Type as AST
import qualified LLVM.IRBuilder.Constant as C
import LLVM.IRBuilder.Instruction
import qualified LLVM.IRBuilder.Instruction as L
import LLVM.IRBuilder.Module
import qualified LLVM.IRBuilder.Monad as L
import Smol.Core.IR.ToLLVM.Helpers
print the number 42
print42 :: Module
print42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
function "main" [] AST.i32 $ \_ -> do
_ <- call pInt [(C.int32 42, [])]
ret (C.int32 0)
print the number 42 after using i d function
useId42 :: Module
useId42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
fnId <- function "id" [(AST.i32, "a")] AST.i32 $ \case
[a] -> ret a
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
a2 <- call fnId [(C.int32 42, [])]
_ <- call pInt [(a2, [])]
ret (C.int32 0)
print the number 42 after using the const function
useAdd42 :: Module
useAdd42 = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
let const2Struct = AST.StructureType False [AST.i32]
fnAdd2 <- function "add2" [(AST.i32, "b"), (pointerType const2Struct, "env")] AST.i32 $ \case
[b, env] -> do
% a = load i32 , i32 * % 1
a <- loadFromStruct env [0]
res <- add a b
ret res
other -> error (show other)
fnAdd <- function "add" [(AST.i32, "a"), (AST.i32, "b")] AST.i32 $ \case
[a, b] -> do
env2 <- allocLocal "const2-struct" const2Struct
store a in
storePrimInStruct env2 [0] a
result <- call fnAdd2 [(b, []), (env2, [])]
ret result
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
a2 <-
call
fnAdd
[ (C.int32 20, []),
(C.int32 22, [])
]
_ <- call pInt [(a2, [])]
ret (C.int32 0)
oneTuple42 :: Module
oneTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyOneTuple = AST.StructureType False [AST.i32]
mkTuple <- function "mkTuple" [(AST.i32, "a"), (pointerType tyOneTuple, "sret")] AST.void $ \case
[a, sRet] -> do
store a in slot 0
storePrimInStruct sRet [0] a
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
oneTuple <- callWithReturnStruct mkTuple tyOneTuple [C.int32 42]
get 1st
res <- loadFromStruct oneTuple [0]
_ <- call pInt [(res, [])]
ret (C.int32 0)
make a two tuple , fetch from it , sum items
twoTuple42 :: Module
twoTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyTwoTuple = AST.StructureType False [AST.i32, AST.i32]
mkTuple <- function
"mkTuple"
[ (AST.i32, "a"),
(AST.i32, "b"),
(pointerType tyTwoTuple, "sRet")
]
AST.void
$ \case
[a, b, sRet] -> do
llStruct <- allocLocal "mktuplestruct" tyTwoTuple
store a in
storePrimInStruct llStruct [0] a
store b in slot2
storePrimInStruct llStruct [1] b
moveToStruct llStruct sRet
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
twoTuple <- callWithReturnStruct mkTuple tyTwoTuple [C.int32 20, C.int32 22]
get 1st
var1 <- loadFromStruct twoTuple [0]
get 2nd
var2 <- loadFromStruct twoTuple [1]
res <- add var1 var2
_ <- call pInt [(res, [])]
ret (C.int32 0)
make a nested tuple ( 10 , ( 12 , 20 ) ) and adds it all
nestedTuple42 :: Module
nestedTuple42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyNested = struct [AST.i32, struct [AST.i32, AST.i32]]
mkNestedTuple <- function
"mkNestedTuple"
[ (AST.i32, "a"),
(AST.i32, "b"),
(AST.i32, "c"),
(pointerType tyNested, "sRet")
]
AST.void
$ \case
[a, b, c, sRet] -> do
store a in
storePrimInStruct sRet [0] a
store b in slot2
storePrimInStruct sRet [1, 0] b
storePrimInStruct sRet [1, 1] c
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
nestedTuple <-
callWithReturnStruct
mkNestedTuple
tyNested
[ C.int32 10,
C.int32 12,
C.int32 20
]
varA <- loadFromStruct nestedTuple [0]
varB <- loadFromStruct nestedTuple [1, 0]
varC <- loadFromStruct nestedTuple [1, 1]
res1 <- add varA varB
res2 <- add res1 varC
_ <- call pInt [(res2, [])]
ret (C.int32 0)
if True then 1 else 2
useBasicIf :: Module
useBasicIf = buildModule "exampleModule" $ do
pInt <- getPrintInt
function "main" [] AST.i32 $ \_ -> mdo
result <- alloca AST.i32 Nothing 0
L.condBr predVal thenBlock elseBlock
thenBlock <- L.block `L.named` "then"
set result to 1
store result 0 (C.int32 1)
L.br mergeBlock
elseBlock <- L.block `L.named` "else"
set result to 2
store result 0 (C.int32 2)
L.br mergeBlock
mergeBlock <- L.block `L.named` "merge"
finalResult <- load result 0
_ <- call pInt [(finalResult, [])]
ret (C.int32 0)
print the number 42 after using the const function
useConst42Curried :: Module
useConst42Curried = buildModule "exampleModule" $ mdo
pInt <- getPrintInt
let const2Struct = AST.StructureType False [AST.i32]
(_fnConst2, const2Func) <- functionAndType
"const2"
[ (AST.i32, "b"),
(pointerType const2Struct, "env")
]
AST.i32
$ \case
[_b, env] ->
loadFromStruct env [0] >>= ret
other -> error (show other)
let const2ClosureType =
AST.StructureType
False
[ pointerType const2Func,
const2Struct
]
fnConst <- function
"const"
[ (AST.i32, "a"),
(pointerType const2ClosureType, "sRet")
]
AST.void
$ \case
[a, sRet] -> do
store a in of env
storePrimInStruct sRet [1, 0] a
storePrimInStruct
sRet
[0]
( Op.ConstantOperand
(C.GlobalReference (pointerType const2Func) "const2")
)
retVoid
other -> error (show other)
function "main" [] AST.i32 $ \_ -> do
closure <- callWithReturnStruct fnConst const2ClosureType [C.int32 42]
a2 <- callClosure closure (C.int32 43)
_ <- call pInt [(a2, [])]
ret (C.int32 0)
either42 :: Module
either42 = buildModule "exampleModule" $ do
pInt <- getPrintInt
let tyEitherBoolInt = AST.StructureType False [AST.i32, AST.ArrayType 1 AST.i32]
tyRightInt = pointerType (AST.StructureType False [AST.i32, AST.i32])
tyLeftBool = pointerType (AST.StructureType False [AST.i32, AST.i1])
function "main" [] AST.i32 $ \_ -> do
CREATING RIGHT 41
first we create an Either Bool Int and put Right Int in it
rStruct <- allocLocal "mkrightstruct" tyEitherBoolInt
store 0 ( for " Right " ) in
storePrimInStruct rStruct [0] (C.int32 0)
rStruct' <- bitcast rStruct tyRightInt
store a in slot2
storePrimInStruct rStruct' [1] (C.int32 41)
turn it back into Right Int
rStruct'' <- bitcast rStruct' (pointerType tyEitherBoolInt)
CREATING LEFT 1
first we create an Either Bool Int and put Right Int in it
lStruct <- allocLocal "mkleftStruct" tyEitherBoolInt
store 1 ( for " Left " ) in
storePrimInStruct lStruct [0] (C.int32 1)
cast to
lStruct' <- bitcast lStruct tyLeftBool
store a in slot2
storePrimInStruct lStruct' [1] (C.bit 1)
turn it back into Right Int
lStruct'' <- bitcast lStruct' (pointerType tyEitherBoolInt)
( Either Int )
fnDeconstruct <- function
"const"
[ (pointerType tyEitherBoolInt, "either")
]
AST.i32
$ \case
[input] -> mdo
result <- alloca AST.i32 Nothing 0
discriminator <- loadFromStruct input [0]
L.switch discriminator rightBlock [(C.Int 32 0, rightBlock), (C.Int 32 1, leftBlock)]
rightBlock <- L.block `L.named` "right"
casted <- bitcast input tyRightInt
myInt <- loadFromStruct casted [1]
set result to 1
store result 0 myInt
L.br mergeBlock
leftBlock <- L.block `L.named` "left"
lCasted <- bitcast input tyLeftBool
myBool <- loadFromStruct lCasted [1]
intFromBool <- zext myBool AST.i32
store result 0 intFromBool
L.br mergeBlock
mergeBlock <- L.block `L.named` "merge"
realResult <- load result 0
ret realResult
other -> error (show other)
rStructPointer <- gep rStruct'' [C.int32 0]
rightResult <- call fnDeconstruct [(rStructPointer, mempty)]
lStructPointer <- gep lStruct'' [C.int32 0]
leftResult <- call fnDeconstruct [(lStructPointer, mempty)]
finalResult <- add leftResult rightResult
_ <- call pInt [(finalResult, [])]
ret (C.int32 0)
|
363db5c87fd748fa942083c73866338986c9a07a4ecd1d53a70d24e37f7271d1 | gtk2hs/gtk2hs | Setup.hs | # LANGUAGE CPP , ViewPatterns #
-- Adjustments specific to this package,
-- all Gtk2Hs-specific boilerplate is kept in
gtk2hs - buildtools : Gtk2HsSetup
--
import Distribution.Simple ( defaultMainWithHooks, UserHooks(postConf),
PackageIdentifier(..), PackageName(..) )
import Gtk2HsSetup ( gtk2hsUserHooks, getPkgConfigPackages)
import Distribution.Simple.Setup ( ConfigFlags(configVerbosity), fromFlag)
import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.BuildPaths ( autogenPackageModulesDir )
import Distribution.Text ( display )
import Distribution.Version ( Version(..) )
import Distribution.Verbosity
import Distribution.Simple.Utils hiding (die)
import System.FilePath
import System.Exit (die)
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Version ( versionNumbers )
import Distribution.Types.PackageName ( unPackageName )
#endif
main =
defaultMainWithHooks gtk2hsUserHooks {
postConf = \args cf pd lbi -> do
let verb = (fromFlag (configVerbosity cf))
cPkgs <- getPkgConfigPackages verb lbi pd
let [pangoVersion] = [ v | PackageIdentifier (unPackageName -> "pango") v <- cPkgs ]
writePangoVersionHeaderFile verb lbi pangoVersion
postConf gtk2hsUserHooks args cf pd lbi
}
------------------------------------------------------------------------------
Generate CPP defines for version of C libs .
------------------------------------------------------------------------------
writePangoVersionHeaderFile :: Verbosity -> LocalBuildInfo -> Version -> IO ()
#if MIN_VERSION_Cabal(2,0,0)
writePangoVersionHeaderFile verbosity lbi (versionNumbers -> (major:minor:micro:_)) = do
#else
writePangoVersionHeaderFile verbosity lbi (Version (major:minor:micro:_) []) = do
#endif
createDirectoryIfMissingVerbose verbosity True targetDir
rewriteFileEx verbosity targetFile $ unlines
[ "#define PANGO_VERSION_MAJOR " ++ show major
, "#define PANGO_VERSION_MINOR " ++ show minor
, "#define PANGO_VERSION_MICRO " ++ show micro
]
where
targetDir = autogenPackageModulesDir lbi
targetFile = targetDir </> "hspangoversion.h"
writeVersionHeaderFile _ _ version =
die $ "unexpected pango version number: " ++ display version
| null | https://raw.githubusercontent.com/gtk2hs/gtk2hs/0f90caa1dae319a0f4bbab76ed1a84f17c730adf/pango/Setup.hs | haskell | Adjustments specific to this package,
all Gtk2Hs-specific boilerplate is kept in
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | # LANGUAGE CPP , ViewPatterns #
gtk2hs - buildtools : Gtk2HsSetup
import Distribution.Simple ( defaultMainWithHooks, UserHooks(postConf),
PackageIdentifier(..), PackageName(..) )
import Gtk2HsSetup ( gtk2hsUserHooks, getPkgConfigPackages)
import Distribution.Simple.Setup ( ConfigFlags(configVerbosity), fromFlag)
import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.BuildPaths ( autogenPackageModulesDir )
import Distribution.Text ( display )
import Distribution.Version ( Version(..) )
import Distribution.Verbosity
import Distribution.Simple.Utils hiding (die)
import System.FilePath
import System.Exit (die)
#if MIN_VERSION_Cabal(2,0,0)
import Distribution.Version ( versionNumbers )
import Distribution.Types.PackageName ( unPackageName )
#endif
main =
defaultMainWithHooks gtk2hsUserHooks {
postConf = \args cf pd lbi -> do
let verb = (fromFlag (configVerbosity cf))
cPkgs <- getPkgConfigPackages verb lbi pd
let [pangoVersion] = [ v | PackageIdentifier (unPackageName -> "pango") v <- cPkgs ]
writePangoVersionHeaderFile verb lbi pangoVersion
postConf gtk2hsUserHooks args cf pd lbi
}
Generate CPP defines for version of C libs .
writePangoVersionHeaderFile :: Verbosity -> LocalBuildInfo -> Version -> IO ()
#if MIN_VERSION_Cabal(2,0,0)
writePangoVersionHeaderFile verbosity lbi (versionNumbers -> (major:minor:micro:_)) = do
#else
writePangoVersionHeaderFile verbosity lbi (Version (major:minor:micro:_) []) = do
#endif
createDirectoryIfMissingVerbose verbosity True targetDir
rewriteFileEx verbosity targetFile $ unlines
[ "#define PANGO_VERSION_MAJOR " ++ show major
, "#define PANGO_VERSION_MINOR " ++ show minor
, "#define PANGO_VERSION_MICRO " ++ show micro
]
where
targetDir = autogenPackageModulesDir lbi
targetFile = targetDir </> "hspangoversion.h"
writeVersionHeaderFile _ _ version =
die $ "unexpected pango version number: " ++ display version
|
0fcd8061183920914ffa98c43975016c77c42144898f7bf9131791b8949818b2 | input-output-hk/plutus | DeBruijn.hs | {-# LANGUAGE DerivingStrategies #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
| Support for using de Bruijn indices for term names .
module UntypedPlutusCore.DeBruijn
( Index (..)
, HasIndex (..)
, DeBruijn (..)
, NamedDeBruijn (..)
, FakeNamedDeBruijn (..)
, FreeVariableError (..)
, AsFreeVariableError (..)
, deBruijnTerm
, unDeBruijnTerm
, unNameDeBruijn
, fakeNameDeBruijn
-- * unsafe api, use with care
, deBruijnTermWith
, unDeBruijnTermWith
, freeIndexAsConsistentLevel
, deBruijnInitIndex
) where
import PlutusCore.DeBruijn.Internal
import PlutusCore.Name
import PlutusCore.Quote
import UntypedPlutusCore.Core
import Control.Lens hiding (Index, Level, index)
import Control.Monad.Except
import Control.Monad.Reader
{- Note [Comparison with typed deBruijn conversion]
This module is just a boring port of the typed version.
-}
| Convert a ' Term ' with ' Name 's into a ' Term ' with ' 's .
-- Will throw an error if a free variable is encountered.
deBruijnTerm
:: (AsFreeVariableError e, MonadError e m)
=> Term Name uni fun ann -> m (Term NamedDeBruijn uni fun ann)
deBruijnTerm = deBruijnTermWith freeUniqueThrow
| Convert a ' Term ' with ' 's into a ' Term ' with ' Name 's .
-- Will throw an error if a free variable is encountered.
unDeBruijnTerm
:: (MonadQuote m, AsFreeVariableError e, MonadError e m)
=> Term NamedDeBruijn uni fun ann -> m (Term Name uni fun ann)
unDeBruijnTerm = unDeBruijnTermWith freeIndexThrow
-- | Takes a "handler" function to execute when encountering free variables.
deBruijnTermWith
:: Monad m
=> (Unique -> ReaderT Levels m Index)
-> Term Name uni fun ann
-> m (Term NamedDeBruijn uni fun ann)
deBruijnTermWith = (runDeBruijnT .) . deBruijnTermWithM
-- | Takes a "handler" function to execute when encountering free variables.
unDeBruijnTermWith
:: MonadQuote m
=> (Index -> ReaderT Levels m Unique)
-> Term NamedDeBruijn uni fun ann
-> m (Term Name uni fun ann)
unDeBruijnTermWith = (runDeBruijnT .) . unDeBruijnTermWithM
deBruijnTermWithM
:: MonadReader Levels m
=> (Unique -> m Index)
-> Term Name uni fun ann
-> m (Term NamedDeBruijn uni fun ann)
deBruijnTermWithM h = go
where
go = \case
-- variable case
Var ann n -> Var ann <$> nameToDeBruijn h n
-- binder cases
LamAbs ann n t -> declareUnique n $ do
n' <- nameToDeBruijn h n
withScope $ LamAbs ann n' <$> go t
-- boring recursive cases
Apply ann t1 t2 -> Apply ann <$> go t1 <*> go t2
Delay ann t -> Delay ann <$> go t
Force ann t -> Force ann <$> go t
-- boring non-recursive cases
Constant ann con -> pure $ Constant ann con
Builtin ann bn -> pure $ Builtin ann bn
Error ann -> pure $ Error ann
-- | Takes a "handler" function to execute when encountering free variables.
unDeBruijnTermWithM
:: (MonadReader Levels m, MonadQuote m)
=> (Index -> m Unique)
-> Term NamedDeBruijn uni fun ann
-> m (Term Name uni fun ann)
unDeBruijnTermWithM h = go
where
go = \case
-- variable case
Var ann n -> Var ann <$> deBruijnToName h n
-- binder cases
LamAbs ann n t ->
See NOTE : [ indices of Binders ]
declareBinder $ do
n' <- deBruijnToName h $ set index deBruijnInitIndex n
withScope $ LamAbs ann n' <$> go t
-- boring recursive cases
Apply ann t1 t2 -> Apply ann <$> go t1 <*> go t2
Delay ann t -> Delay ann <$> go t
Force ann t -> Force ann <$> go t
-- boring non-recursive cases
Constant ann con -> pure $ Constant ann con
Builtin ann bn -> pure $ Builtin ann bn
Error ann -> pure $ Error ann
| null | https://raw.githubusercontent.com/input-output-hk/plutus/fffd9f76eba31de0b10ff8dbcea6f49c3c04bdaf/plutus-core/untyped-plutus-core/src/UntypedPlutusCore/DeBruijn.hs | haskell | # LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
* unsafe api, use with care
Note [Comparison with typed deBruijn conversion]
This module is just a boring port of the typed version.
Will throw an error if a free variable is encountered.
Will throw an error if a free variable is encountered.
| Takes a "handler" function to execute when encountering free variables.
| Takes a "handler" function to execute when encountering free variables.
variable case
binder cases
boring recursive cases
boring non-recursive cases
| Takes a "handler" function to execute when encountering free variables.
variable case
binder cases
boring recursive cases
boring non-recursive cases | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
| Support for using de Bruijn indices for term names .
module UntypedPlutusCore.DeBruijn
( Index (..)
, HasIndex (..)
, DeBruijn (..)
, NamedDeBruijn (..)
, FakeNamedDeBruijn (..)
, FreeVariableError (..)
, AsFreeVariableError (..)
, deBruijnTerm
, unDeBruijnTerm
, unNameDeBruijn
, fakeNameDeBruijn
, deBruijnTermWith
, unDeBruijnTermWith
, freeIndexAsConsistentLevel
, deBruijnInitIndex
) where
import PlutusCore.DeBruijn.Internal
import PlutusCore.Name
import PlutusCore.Quote
import UntypedPlutusCore.Core
import Control.Lens hiding (Index, Level, index)
import Control.Monad.Except
import Control.Monad.Reader
| Convert a ' Term ' with ' Name 's into a ' Term ' with ' 's .
deBruijnTerm
:: (AsFreeVariableError e, MonadError e m)
=> Term Name uni fun ann -> m (Term NamedDeBruijn uni fun ann)
deBruijnTerm = deBruijnTermWith freeUniqueThrow
| Convert a ' Term ' with ' 's into a ' Term ' with ' Name 's .
unDeBruijnTerm
:: (MonadQuote m, AsFreeVariableError e, MonadError e m)
=> Term NamedDeBruijn uni fun ann -> m (Term Name uni fun ann)
unDeBruijnTerm = unDeBruijnTermWith freeIndexThrow
deBruijnTermWith
:: Monad m
=> (Unique -> ReaderT Levels m Index)
-> Term Name uni fun ann
-> m (Term NamedDeBruijn uni fun ann)
deBruijnTermWith = (runDeBruijnT .) . deBruijnTermWithM
unDeBruijnTermWith
:: MonadQuote m
=> (Index -> ReaderT Levels m Unique)
-> Term NamedDeBruijn uni fun ann
-> m (Term Name uni fun ann)
unDeBruijnTermWith = (runDeBruijnT .) . unDeBruijnTermWithM
deBruijnTermWithM
:: MonadReader Levels m
=> (Unique -> m Index)
-> Term Name uni fun ann
-> m (Term NamedDeBruijn uni fun ann)
deBruijnTermWithM h = go
where
go = \case
Var ann n -> Var ann <$> nameToDeBruijn h n
LamAbs ann n t -> declareUnique n $ do
n' <- nameToDeBruijn h n
withScope $ LamAbs ann n' <$> go t
Apply ann t1 t2 -> Apply ann <$> go t1 <*> go t2
Delay ann t -> Delay ann <$> go t
Force ann t -> Force ann <$> go t
Constant ann con -> pure $ Constant ann con
Builtin ann bn -> pure $ Builtin ann bn
Error ann -> pure $ Error ann
unDeBruijnTermWithM
:: (MonadReader Levels m, MonadQuote m)
=> (Index -> m Unique)
-> Term NamedDeBruijn uni fun ann
-> m (Term Name uni fun ann)
unDeBruijnTermWithM h = go
where
go = \case
Var ann n -> Var ann <$> deBruijnToName h n
LamAbs ann n t ->
See NOTE : [ indices of Binders ]
declareBinder $ do
n' <- deBruijnToName h $ set index deBruijnInitIndex n
withScope $ LamAbs ann n' <$> go t
Apply ann t1 t2 -> Apply ann <$> go t1 <*> go t2
Delay ann t -> Delay ann <$> go t
Force ann t -> Force ann <$> go t
Constant ann con -> pure $ Constant ann con
Builtin ann bn -> pure $ Builtin ann bn
Error ann -> pure $ Error ann
|
5a773f82b01957d9434785602079345f6df650a7e6f448dd8456dc7ded7257e4 | scheme-live/live | output.scm | #f | null | https://raw.githubusercontent.com/scheme-live/live/4c7c9d80f2fcf80692614e10935fa66be69e3708/live/json/data/y-structure-lonely-false/output.scm | scheme | #f |
|
463eac722e713688a0d8835228df9423666dc2fb7ded16f756c86f9c774b791b | input-output-hk/plutus-apps | Run.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
-- | Start a local cluster of cardano nodes and PAB(s)
module Plutus.PAB.LocalCluster.Run where
import Cardano.Api qualified as CAPI
import Cardano.Api.NetworkId.Extra (NetworkIdWrapper (NetworkIdWrapper))
import Cardano.BM.Backend.EKGView qualified as EKG
import Cardano.BM.Data.Severity (Severity (Notice))
import Cardano.BM.Data.Tracer (HasPrivacyAnnotation, HasSeverityAnnotation)
import Cardano.BM.Plugin (loadPlugin)
import Cardano.BM.Tracing (HasSeverityAnnotation (getSeverityAnnotation), Severity (Debug, Info))
import Cardano.CLI (LogOutput (LogToFile, LogToStdStreams), Port, ekgEnabled, getEKGURL, getPrometheusURL,
withLoggingNamed)
import Cardano.ChainIndex.Types qualified as PAB.CI
import Cardano.Launcher.Node (nodeSocketFile)
import Cardano.Mnemonic (SomeMnemonic (SomeMnemonic))
import Cardano.Node.Emulator.TimeSlot (SlotConfig (SlotConfig))
import Cardano.Node.Emulator.TimeSlot qualified as TimeSlot
import Cardano.Node.Types (NodeMode (AlonzoNode),
PABServerConfig (pscKeptBlocks, pscNetworkId, pscNodeMode, pscSlotConfig, pscSocketPath))
import Cardano.Startup (installSignalHandlers, setDefaultFilePermissions, withUtf8Encoding)
import Cardano.Wallet.Api.Client qualified as WalletClient
import Cardano.Wallet.Api.Server (Listen (ListenOnPort))
import Cardano.Wallet.Api.Types (ApiMnemonicT (ApiMnemonicT), ApiT (ApiT), ApiWallet (ApiWallet),
EncodeAddress (encodeAddress), WalletOrAccountPostData (WalletOrAccountPostData),
postData)
import Cardano.Wallet.Api.Types qualified as Wallet.Types
import Cardano.Wallet.Logging (stdoutTextTracer, trMessageText)
import Cardano.Wallet.Primitive.AddressDerivation (NetworkDiscriminant (Mainnet))
import Cardano.Wallet.Primitive.Passphrase.Types (Passphrase (Passphrase))
import Cardano.Wallet.Primitive.SyncProgress (SyncTolerance (SyncTolerance))
import Cardano.Wallet.Primitive.Types (GenesisParameters (GenesisParameters),
NetworkParameters (NetworkParameters, slottingParameters),
SlotLength (SlotLength),
SlottingParameters (SlottingParameters, getSecurityParameter),
StartTime (StartTime), WalletName (WalletName))
import Cardano.Wallet.Primitive.Types.Coin (Coin (Coin))
import Cardano.Wallet.Shelley (SomeNetworkDiscriminant (SomeNetworkDiscriminant), serveWallet, setupTracers,
tracerSeverities)
import Cardano.Wallet.Shelley.BlockchainSource (BlockchainSource (NodeSource))
import Cardano.Wallet.Shelley.Launch (withSystemTempDir)
import Cardano.Wallet.Shelley.Launch.Cluster (ClusterLog, Credential (KeyCredential), RunningNode (RunningNode),
localClusterConfigFromEnv, moveInstantaneousRewardsTo, oneMillionAda,
sendFaucetAssetsTo, testMinSeverityFromEnv, tokenMetadataServerFromEnv,
walletMinSeverityFromEnv, withCluster)
import Cardano.Wallet.Types (WalletUrl (WalletUrl))
import Cardano.Wallet.Types qualified as Wallet.Config
import Control.Arrow (first)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async)
import Control.Lens (contramap, set, (&), (.~), (^.))
import Control.Monad (void, when)
import Control.Monad.Freer.Extras.Beam.Sqlite (DbConfig (dbConfigFile))
import Control.Tracer (traceWith)
import Data.Aeson (FromJSON, ToJSON)
import Data.Default (Default (def))
import Data.OpenApi.Schema qualified as OpenApi
import Data.Proxy (Proxy (Proxy))
import Data.Quantity (Quantity (getQuantity))
import Data.String (IsString (fromString))
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Class (ToText (toText))
import Data.Time.Clock (nominalDiffTimeToSeconds)
import Network.HTTP.Client (defaultManagerSettings, newManager)
import Ouroboros.Network.Client.Wallet (tunedForMainnetPipeliningStrategy)
import Plutus.ChainIndex.App qualified as ChainIndex
import Plutus.ChainIndex.Config qualified as CI
import Plutus.ChainIndex.Logging qualified as ChainIndex.Logging
import Plutus.ChainIndex.Types (Point (..))
import Plutus.PAB.App (StorageBackend (BeamBackend))
import Plutus.PAB.Effects.Contract.Builtin (BuiltinHandler, HasDefinitions)
import Plutus.PAB.Run qualified as PAB.Run
import Plutus.PAB.Run.Command (ConfigCommand (Migrate, PABWebserver))
import Plutus.PAB.Run.CommandParser (AppOpts (AppOpts, cmd, configPath, logConfigPath, minLogLevel, resumeFrom, rollbackHistory, runEkgServer, storageBackend))
import Plutus.PAB.Run.CommandParser qualified as PAB.Command
import Plutus.PAB.Types (ChainQueryConfig (ChainIndexConfig),
Config (chainQueryConfig, dbConfig, nodeServerConfig, walletServerConfig), DbConfig (SqliteDB))
import Plutus.PAB.Types qualified as PAB.Config
import Prettyprinter (Pretty)
import Servant qualified
import Servant.Client (BaseUrl (BaseUrl, baseUrlHost, baseUrlPath, baseUrlPort, baseUrlScheme), Scheme (Http),
mkClientEnv, runClientM)
import System.Directory (createDirectory)
import System.FilePath ((</>))
import Test.Integration.Faucet (genRewardAccounts, maryIntegrationTestAssets, mirMnemonics, shelleyIntegrationTestFunds)
import Test.Integration.Faucet qualified as Faucet
import Test.Integration.Framework.DSL (fixturePassphrase)
data LogOutputs =
LogOutputs
{ loCluster :: [LogOutput]
, loWallet :: [LogOutput]
}
-- Do all the program setup required for running the local cluster, create a
-- temporary directory, log output configurations, and pass these to the given
-- main action.
withLocalClusterSetup
:: (FilePath -> LogOutputs -> IO a)
-> IO a
withLocalClusterSetup action = do
putStrLn "Starting PAB local cluster. Please make sure the SHELLEY_TEST_DATA environment variable is set to 'plutus-pab/local-cluster/cluster-data/cardano-node-shelley' in the plutus-apps repository."
-- Handle SIGTERM properly
installSignalHandlers (putStrLn "Terminated")
-- Ensure key files have correct permissions for cardano-cli
setDefaultFilePermissions
-- Set UTF-8, regardless of user locale
withUtf8Encoding $
-- This temporary directory will contain logs, and all other data
-- produced by the local test cluster.
withSystemTempDir stdoutTextTracer "test-cluster" $ \dir -> do
let logOutputs name minSev =
[ LogToFile (dir </> name) (min minSev Info)
, LogToStdStreams minSev ]
lops <-
LogOutputs
<$> (logOutputs "cluster.log" <$> testMinSeverityFromEnv)
<*> (logOutputs "wallet.log" <$> walletMinSeverityFromEnv)
action dir lops
runWith :: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a
-> IO ()
runWith userContractHandler = withLocalClusterSetup $ \dir lo@LogOutputs{loCluster} ->
withLoggingNamed "cluster" loCluster $ \(_, (_, trCluster)) -> do
let tr' = contramap MsgCluster $ trMessageText trCluster
clusterCfg <- localClusterConfigFromEnv
let initialFunds = shelleyIntegrationTestFunds
withCluster tr' dir clusterCfg initialFunds
(whenReady dir (trMessageText trCluster) lo)
where
setupFaucet dir trCluster (RunningNode socketPath _ _ _) = do
traceWith trCluster MsgSettingUpFaucet
let trCluster' = contramap MsgCluster trCluster
let encodeAddresses = map (first (T.unpack . encodeAddress @'Mainnet))
let accts = KeyCredential <$> concatMap genRewardAccounts mirMnemonics
let rewards = (, Coin $ fromIntegral oneMillionAda) <$> accts
sendFaucetAssetsTo trCluster' socketPath dir 20 $ encodeAddresses $
maryIntegrationTestAssets (Coin 1_000_000_000)
moveInstantaneousRewardsTo trCluster' socketPath dir rewards
whenReady dir trCluster LogOutputs{loWallet} rn@(RunningNode socketPath block0 (gp, vData) poolCertificates) = do
withLoggingNamed "cardano-wallet" loWallet $ \(sb, (cfg, tr)) -> do
setupFaucet dir trCluster rn
let walletHost = "127.0.0.1"
walletPort = 46493
setupPABServices userContractHandler walletHost walletPort dir rn
ekgEnabled >>= flip when (EKG.plugin cfg tr sb >>= loadPlugin sb)
let tracers = setupTracers (tracerSeverities (Just Debug)) tr
let db = dir </> "wallets"
createDirectory db
tokenMetadataServer <- tokenMetadataServerFromEnv
prometheusUrl <- maybe "none"
(\(h, p) -> T.pack h <> ":" <> toText @(Port "Prometheus") p)
<$> getPrometheusURL
ekgUrl <- maybe "none"
(\(h, p) -> T.pack h <> ":" <> toText @(Port "EKG") p)
<$> getEKGURL
void $ serveWallet
(NodeSource socketPath vData (SyncTolerance 10))
gp
tunedForMainnetPipeliningStrategy
(SomeNetworkDiscriminant $ Proxy @'Mainnet)
poolCertificates
tracers
(Just db)
Nothing
(fromString walletHost)
(ListenOnPort walletPort)
Nothing
Nothing
tokenMetadataServer
block0
(\u -> traceWith trCluster $ MsgBaseUrl (T.pack . show $ u)
ekgUrl prometheusUrl)
newtype ChainIndexPort = ChainIndexPort Int
setupPABServices
:: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a -> String -> Int -> FilePath -> RunningNode -> IO ()
setupPABServices userContractHandler walletHost walletPort dir rn = void $ async $ do -- TODO: better types for arguments
walletUrl <- restoreWallets walletHost walletPort
chainIndexPort <- launchChainIndex dir rn
launchPAB userContractHandler fixturePassphrase dir walletUrl rn chainIndexPort
{-| Launch the chain index in a separate thread.
-}
launchChainIndex :: FilePath -> RunningNode -> IO ChainIndexPort
launchChainIndex dir (RunningNode socketPath _block0 (_gp, _vData) _) = do
config <- ChainIndex.Logging.defaultConfig
let dbPath = dir </> "chain-index.db"
chainIndexConfig = CI.defaultConfig
& CI.socketPath .~ nodeSocketFile socketPath
& CI.dbPath .~ dbPath
& CI.networkId .~ CAPI.Mainnet
void . async $ void $ ChainIndex.runMain config chainIndexConfig
return $ ChainIndexPort $ chainIndexConfig ^. CI.port
{-| Launch the PAB in a separate thread.
-}
launchPAB
:: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a
-> Text -- ^ Passphrase
-> FilePath -- ^ Temp directory
-> BaseUrl -- ^ wallet url
-> RunningNode -- ^ Socket path
-> ChainIndexPort -- ^ Port of the chain index
-> IO ()
launchPAB userContractHandler
passPhrase
dir
walletUrl
(RunningNode socketPath _block0 (networkParameters, _) _)
(ChainIndexPort chainIndexPort) = do
let opts = AppOpts { minLogLevel = Nothing
, logConfigPath = Nothing
, configPath = Nothing
, rollbackHistory = Nothing
, resumeFrom = PointAtGenesis
, runEkgServer = False
, storageBackend = BeamBackend
, cmd = PABWebserver
, PAB.Command.passphrase = Just passPhrase
}
networkID = NetworkIdWrapper CAPI.Mainnet
-- TODO: Remove when PAB queries local node for slot config
slotConfig = slotConfigOfNetworkParameters networkParameters
-- TODO: Remove when PAB queries local node for security param
securityParam = fromIntegral
$ getQuantity
$ getSecurityParameter
$ slottingParameters networkParameters
config =
PAB.Config.defaultConfig
{ nodeServerConfig = def
{ pscSocketPath = nodeSocketFile socketPath
, pscNodeMode = AlonzoNode
, pscNetworkId = networkID
, pscSlotConfig = slotConfig
, pscKeptBlocks = securityParam
}
, dbConfig = SqliteDB def{ dbConfigFile = T.pack (dir </> "plutus-pab.db") }
, chainQueryConfig = ChainIndexConfig def{PAB.CI.ciBaseUrl = PAB.CI.ChainIndexUrl $ BaseUrl Http "localhost" chainIndexPort ""}
, walletServerConfig = set (Wallet.Config.walletSettingsL . Wallet.Config.baseUrlL) (WalletUrl walletUrl) def
}
PAB.Run.runWithOpts userContractHandler (Just config) opts { cmd = Migrate }
PAB.Run.runWithOpts userContractHandler (Just config) opts { cmd = PABWebserver }
slotConfigOfNetworkParameters :: NetworkParameters -> SlotConfig
slotConfigOfNetworkParameters
(NetworkParameters
(GenesisParameters _ (StartTime startUtcTime))
(SlottingParameters (SlotLength nominalDiffTime) _ _ _) _) =
SlotConfig (floor $ 1000 * nominalDiffTimeToSeconds nominalDiffTime) (TimeSlot.utcTimeToPOSIXTime startUtcTime)
{-| Set up wallets
-}
restoreWallets :: String -> Int -> IO BaseUrl
restoreWallets walletHost walletPort = do
sleep 15
manager <- newManager defaultManagerSettings
let baseUrl = BaseUrl{baseUrlScheme=Http,baseUrlHost=walletHost,baseUrlPort=walletPort,baseUrlPath=""}
clientEnv = mkClientEnv manager baseUrl
mnemonic :: ApiMnemonicT '[15, 18, 21, 24] = ApiMnemonicT $ SomeMnemonic $ head Faucet.seqMnemonics
wpData = Wallet.Types.WalletPostData
Nothing
mnemonic
Nothing
(ApiT $ WalletName "plutus-wallet")
(ApiT $ Passphrase $ fromString $ T.unpack fixturePassphrase)
walletAcc = WalletOrAccountPostData{postData=Left wpData}
result <- flip runClientM clientEnv $ WalletClient.postWallet WalletClient.walletClient walletAcc
case result of
Left err -> do
putStrLn "restoreWallet failed"
putStrLn $ "Error: " <> show err
putStrLn "restoreWallet: trying again in 30s"
sleep 15
restoreWallets walletHost walletPort
Right (ApiWallet (ApiT i) _ _ _ _ _ _ _ _) -> do
putStrLn $ "Restored wallet: " <> show i
putStrLn $ "Passphrase: " <> T.unpack fixturePassphrase
return baseUrl
sleep :: Int -> IO ()
sleep n = threadDelay $ n * 1_000_000
-- Logging
data TestsLog
= MsgBaseUrl Text Text Text -- wallet url, ekg url, prometheus url
| MsgSettingUpFaucet
| MsgCluster ClusterLog
deriving (Show)
instance ToText TestsLog where
toText = \case
MsgBaseUrl walletUrl ekgUrl prometheusUrl -> mconcat
[ "Wallet url: " , walletUrl
, ", EKG url: " , ekgUrl
, ", Prometheus url:", prometheusUrl
]
MsgSettingUpFaucet -> "Setting up faucet..."
MsgCluster msg -> toText msg
instance HasPrivacyAnnotation TestsLog
instance HasSeverityAnnotation TestsLog where
getSeverityAnnotation = \case
MsgSettingUpFaucet -> Notice
MsgBaseUrl {} -> Notice
MsgCluster msg -> getSeverityAnnotation msg
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/8706e6c7c525b4973a7b6d2ed7c9d0ef9cd4ef46/plutus-pab/src/Plutus/PAB/LocalCluster/Run.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE NumericUnderscores #
# LANGUAGE OverloadedStrings #
| Start a local cluster of cardano nodes and PAB(s)
Do all the program setup required for running the local cluster, create a
temporary directory, log output configurations, and pass these to the given
main action.
Handle SIGTERM properly
Ensure key files have correct permissions for cardano-cli
Set UTF-8, regardless of user locale
This temporary directory will contain logs, and all other data
produced by the local test cluster.
TODO: better types for arguments
| Launch the chain index in a separate thread.
| Launch the PAB in a separate thread.
^ Passphrase
^ Temp directory
^ wallet url
^ Socket path
^ Port of the chain index
TODO: Remove when PAB queries local node for slot config
TODO: Remove when PAB queries local node for security param
| Set up wallets
Logging
wallet url, ekg url, prometheus url | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
module Plutus.PAB.LocalCluster.Run where
import Cardano.Api qualified as CAPI
import Cardano.Api.NetworkId.Extra (NetworkIdWrapper (NetworkIdWrapper))
import Cardano.BM.Backend.EKGView qualified as EKG
import Cardano.BM.Data.Severity (Severity (Notice))
import Cardano.BM.Data.Tracer (HasPrivacyAnnotation, HasSeverityAnnotation)
import Cardano.BM.Plugin (loadPlugin)
import Cardano.BM.Tracing (HasSeverityAnnotation (getSeverityAnnotation), Severity (Debug, Info))
import Cardano.CLI (LogOutput (LogToFile, LogToStdStreams), Port, ekgEnabled, getEKGURL, getPrometheusURL,
withLoggingNamed)
import Cardano.ChainIndex.Types qualified as PAB.CI
import Cardano.Launcher.Node (nodeSocketFile)
import Cardano.Mnemonic (SomeMnemonic (SomeMnemonic))
import Cardano.Node.Emulator.TimeSlot (SlotConfig (SlotConfig))
import Cardano.Node.Emulator.TimeSlot qualified as TimeSlot
import Cardano.Node.Types (NodeMode (AlonzoNode),
PABServerConfig (pscKeptBlocks, pscNetworkId, pscNodeMode, pscSlotConfig, pscSocketPath))
import Cardano.Startup (installSignalHandlers, setDefaultFilePermissions, withUtf8Encoding)
import Cardano.Wallet.Api.Client qualified as WalletClient
import Cardano.Wallet.Api.Server (Listen (ListenOnPort))
import Cardano.Wallet.Api.Types (ApiMnemonicT (ApiMnemonicT), ApiT (ApiT), ApiWallet (ApiWallet),
EncodeAddress (encodeAddress), WalletOrAccountPostData (WalletOrAccountPostData),
postData)
import Cardano.Wallet.Api.Types qualified as Wallet.Types
import Cardano.Wallet.Logging (stdoutTextTracer, trMessageText)
import Cardano.Wallet.Primitive.AddressDerivation (NetworkDiscriminant (Mainnet))
import Cardano.Wallet.Primitive.Passphrase.Types (Passphrase (Passphrase))
import Cardano.Wallet.Primitive.SyncProgress (SyncTolerance (SyncTolerance))
import Cardano.Wallet.Primitive.Types (GenesisParameters (GenesisParameters),
NetworkParameters (NetworkParameters, slottingParameters),
SlotLength (SlotLength),
SlottingParameters (SlottingParameters, getSecurityParameter),
StartTime (StartTime), WalletName (WalletName))
import Cardano.Wallet.Primitive.Types.Coin (Coin (Coin))
import Cardano.Wallet.Shelley (SomeNetworkDiscriminant (SomeNetworkDiscriminant), serveWallet, setupTracers,
tracerSeverities)
import Cardano.Wallet.Shelley.BlockchainSource (BlockchainSource (NodeSource))
import Cardano.Wallet.Shelley.Launch (withSystemTempDir)
import Cardano.Wallet.Shelley.Launch.Cluster (ClusterLog, Credential (KeyCredential), RunningNode (RunningNode),
localClusterConfigFromEnv, moveInstantaneousRewardsTo, oneMillionAda,
sendFaucetAssetsTo, testMinSeverityFromEnv, tokenMetadataServerFromEnv,
walletMinSeverityFromEnv, withCluster)
import Cardano.Wallet.Types (WalletUrl (WalletUrl))
import Cardano.Wallet.Types qualified as Wallet.Config
import Control.Arrow (first)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async)
import Control.Lens (contramap, set, (&), (.~), (^.))
import Control.Monad (void, when)
import Control.Monad.Freer.Extras.Beam.Sqlite (DbConfig (dbConfigFile))
import Control.Tracer (traceWith)
import Data.Aeson (FromJSON, ToJSON)
import Data.Default (Default (def))
import Data.OpenApi.Schema qualified as OpenApi
import Data.Proxy (Proxy (Proxy))
import Data.Quantity (Quantity (getQuantity))
import Data.String (IsString (fromString))
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Class (ToText (toText))
import Data.Time.Clock (nominalDiffTimeToSeconds)
import Network.HTTP.Client (defaultManagerSettings, newManager)
import Ouroboros.Network.Client.Wallet (tunedForMainnetPipeliningStrategy)
import Plutus.ChainIndex.App qualified as ChainIndex
import Plutus.ChainIndex.Config qualified as CI
import Plutus.ChainIndex.Logging qualified as ChainIndex.Logging
import Plutus.ChainIndex.Types (Point (..))
import Plutus.PAB.App (StorageBackend (BeamBackend))
import Plutus.PAB.Effects.Contract.Builtin (BuiltinHandler, HasDefinitions)
import Plutus.PAB.Run qualified as PAB.Run
import Plutus.PAB.Run.Command (ConfigCommand (Migrate, PABWebserver))
import Plutus.PAB.Run.CommandParser (AppOpts (AppOpts, cmd, configPath, logConfigPath, minLogLevel, resumeFrom, rollbackHistory, runEkgServer, storageBackend))
import Plutus.PAB.Run.CommandParser qualified as PAB.Command
import Plutus.PAB.Types (ChainQueryConfig (ChainIndexConfig),
Config (chainQueryConfig, dbConfig, nodeServerConfig, walletServerConfig), DbConfig (SqliteDB))
import Plutus.PAB.Types qualified as PAB.Config
import Prettyprinter (Pretty)
import Servant qualified
import Servant.Client (BaseUrl (BaseUrl, baseUrlHost, baseUrlPath, baseUrlPort, baseUrlScheme), Scheme (Http),
mkClientEnv, runClientM)
import System.Directory (createDirectory)
import System.FilePath ((</>))
import Test.Integration.Faucet (genRewardAccounts, maryIntegrationTestAssets, mirMnemonics, shelleyIntegrationTestFunds)
import Test.Integration.Faucet qualified as Faucet
import Test.Integration.Framework.DSL (fixturePassphrase)
data LogOutputs =
LogOutputs
{ loCluster :: [LogOutput]
, loWallet :: [LogOutput]
}
withLocalClusterSetup
:: (FilePath -> LogOutputs -> IO a)
-> IO a
withLocalClusterSetup action = do
putStrLn "Starting PAB local cluster. Please make sure the SHELLEY_TEST_DATA environment variable is set to 'plutus-pab/local-cluster/cluster-data/cardano-node-shelley' in the plutus-apps repository."
installSignalHandlers (putStrLn "Terminated")
setDefaultFilePermissions
withUtf8Encoding $
withSystemTempDir stdoutTextTracer "test-cluster" $ \dir -> do
let logOutputs name minSev =
[ LogToFile (dir </> name) (min minSev Info)
, LogToStdStreams minSev ]
lops <-
LogOutputs
<$> (logOutputs "cluster.log" <$> testMinSeverityFromEnv)
<*> (logOutputs "wallet.log" <$> walletMinSeverityFromEnv)
action dir lops
runWith :: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a
-> IO ()
runWith userContractHandler = withLocalClusterSetup $ \dir lo@LogOutputs{loCluster} ->
withLoggingNamed "cluster" loCluster $ \(_, (_, trCluster)) -> do
let tr' = contramap MsgCluster $ trMessageText trCluster
clusterCfg <- localClusterConfigFromEnv
let initialFunds = shelleyIntegrationTestFunds
withCluster tr' dir clusterCfg initialFunds
(whenReady dir (trMessageText trCluster) lo)
where
setupFaucet dir trCluster (RunningNode socketPath _ _ _) = do
traceWith trCluster MsgSettingUpFaucet
let trCluster' = contramap MsgCluster trCluster
let encodeAddresses = map (first (T.unpack . encodeAddress @'Mainnet))
let accts = KeyCredential <$> concatMap genRewardAccounts mirMnemonics
let rewards = (, Coin $ fromIntegral oneMillionAda) <$> accts
sendFaucetAssetsTo trCluster' socketPath dir 20 $ encodeAddresses $
maryIntegrationTestAssets (Coin 1_000_000_000)
moveInstantaneousRewardsTo trCluster' socketPath dir rewards
whenReady dir trCluster LogOutputs{loWallet} rn@(RunningNode socketPath block0 (gp, vData) poolCertificates) = do
withLoggingNamed "cardano-wallet" loWallet $ \(sb, (cfg, tr)) -> do
setupFaucet dir trCluster rn
let walletHost = "127.0.0.1"
walletPort = 46493
setupPABServices userContractHandler walletHost walletPort dir rn
ekgEnabled >>= flip when (EKG.plugin cfg tr sb >>= loadPlugin sb)
let tracers = setupTracers (tracerSeverities (Just Debug)) tr
let db = dir </> "wallets"
createDirectory db
tokenMetadataServer <- tokenMetadataServerFromEnv
prometheusUrl <- maybe "none"
(\(h, p) -> T.pack h <> ":" <> toText @(Port "Prometheus") p)
<$> getPrometheusURL
ekgUrl <- maybe "none"
(\(h, p) -> T.pack h <> ":" <> toText @(Port "EKG") p)
<$> getEKGURL
void $ serveWallet
(NodeSource socketPath vData (SyncTolerance 10))
gp
tunedForMainnetPipeliningStrategy
(SomeNetworkDiscriminant $ Proxy @'Mainnet)
poolCertificates
tracers
(Just db)
Nothing
(fromString walletHost)
(ListenOnPort walletPort)
Nothing
Nothing
tokenMetadataServer
block0
(\u -> traceWith trCluster $ MsgBaseUrl (T.pack . show $ u)
ekgUrl prometheusUrl)
newtype ChainIndexPort = ChainIndexPort Int
setupPABServices
:: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a -> String -> Int -> FilePath -> RunningNode -> IO ()
walletUrl <- restoreWallets walletHost walletPort
chainIndexPort <- launchChainIndex dir rn
launchPAB userContractHandler fixturePassphrase dir walletUrl rn chainIndexPort
launchChainIndex :: FilePath -> RunningNode -> IO ChainIndexPort
launchChainIndex dir (RunningNode socketPath _block0 (_gp, _vData) _) = do
config <- ChainIndex.Logging.defaultConfig
let dbPath = dir </> "chain-index.db"
chainIndexConfig = CI.defaultConfig
& CI.socketPath .~ nodeSocketFile socketPath
& CI.dbPath .~ dbPath
& CI.networkId .~ CAPI.Mainnet
void . async $ void $ ChainIndex.runMain config chainIndexConfig
return $ ChainIndexPort $ chainIndexConfig ^. CI.port
launchPAB
:: forall a.
( Show a
, Ord a
, FromJSON a
, ToJSON a
, Pretty a
, Servant.MimeUnrender Servant.JSON a
, HasDefinitions a
, OpenApi.ToSchema a
)
=> BuiltinHandler a
-> IO ()
launchPAB userContractHandler
passPhrase
dir
walletUrl
(RunningNode socketPath _block0 (networkParameters, _) _)
(ChainIndexPort chainIndexPort) = do
let opts = AppOpts { minLogLevel = Nothing
, logConfigPath = Nothing
, configPath = Nothing
, rollbackHistory = Nothing
, resumeFrom = PointAtGenesis
, runEkgServer = False
, storageBackend = BeamBackend
, cmd = PABWebserver
, PAB.Command.passphrase = Just passPhrase
}
networkID = NetworkIdWrapper CAPI.Mainnet
slotConfig = slotConfigOfNetworkParameters networkParameters
securityParam = fromIntegral
$ getQuantity
$ getSecurityParameter
$ slottingParameters networkParameters
config =
PAB.Config.defaultConfig
{ nodeServerConfig = def
{ pscSocketPath = nodeSocketFile socketPath
, pscNodeMode = AlonzoNode
, pscNetworkId = networkID
, pscSlotConfig = slotConfig
, pscKeptBlocks = securityParam
}
, dbConfig = SqliteDB def{ dbConfigFile = T.pack (dir </> "plutus-pab.db") }
, chainQueryConfig = ChainIndexConfig def{PAB.CI.ciBaseUrl = PAB.CI.ChainIndexUrl $ BaseUrl Http "localhost" chainIndexPort ""}
, walletServerConfig = set (Wallet.Config.walletSettingsL . Wallet.Config.baseUrlL) (WalletUrl walletUrl) def
}
PAB.Run.runWithOpts userContractHandler (Just config) opts { cmd = Migrate }
PAB.Run.runWithOpts userContractHandler (Just config) opts { cmd = PABWebserver }
slotConfigOfNetworkParameters :: NetworkParameters -> SlotConfig
slotConfigOfNetworkParameters
(NetworkParameters
(GenesisParameters _ (StartTime startUtcTime))
(SlottingParameters (SlotLength nominalDiffTime) _ _ _) _) =
SlotConfig (floor $ 1000 * nominalDiffTimeToSeconds nominalDiffTime) (TimeSlot.utcTimeToPOSIXTime startUtcTime)
restoreWallets :: String -> Int -> IO BaseUrl
restoreWallets walletHost walletPort = do
sleep 15
manager <- newManager defaultManagerSettings
let baseUrl = BaseUrl{baseUrlScheme=Http,baseUrlHost=walletHost,baseUrlPort=walletPort,baseUrlPath=""}
clientEnv = mkClientEnv manager baseUrl
mnemonic :: ApiMnemonicT '[15, 18, 21, 24] = ApiMnemonicT $ SomeMnemonic $ head Faucet.seqMnemonics
wpData = Wallet.Types.WalletPostData
Nothing
mnemonic
Nothing
(ApiT $ WalletName "plutus-wallet")
(ApiT $ Passphrase $ fromString $ T.unpack fixturePassphrase)
walletAcc = WalletOrAccountPostData{postData=Left wpData}
result <- flip runClientM clientEnv $ WalletClient.postWallet WalletClient.walletClient walletAcc
case result of
Left err -> do
putStrLn "restoreWallet failed"
putStrLn $ "Error: " <> show err
putStrLn "restoreWallet: trying again in 30s"
sleep 15
restoreWallets walletHost walletPort
Right (ApiWallet (ApiT i) _ _ _ _ _ _ _ _) -> do
putStrLn $ "Restored wallet: " <> show i
putStrLn $ "Passphrase: " <> T.unpack fixturePassphrase
return baseUrl
sleep :: Int -> IO ()
sleep n = threadDelay $ n * 1_000_000
data TestsLog
| MsgSettingUpFaucet
| MsgCluster ClusterLog
deriving (Show)
instance ToText TestsLog where
toText = \case
MsgBaseUrl walletUrl ekgUrl prometheusUrl -> mconcat
[ "Wallet url: " , walletUrl
, ", EKG url: " , ekgUrl
, ", Prometheus url:", prometheusUrl
]
MsgSettingUpFaucet -> "Setting up faucet..."
MsgCluster msg -> toText msg
instance HasPrivacyAnnotation TestsLog
instance HasSeverityAnnotation TestsLog where
getSeverityAnnotation = \case
MsgSettingUpFaucet -> Notice
MsgBaseUrl {} -> Notice
MsgCluster msg -> getSeverityAnnotation msg
|
8af7b76ffb53a6901490e0a52600a86af43f3ff62cbc59637aec20e86649a15c | Ekatereana/CommonLispWorks | groupby.lisp |
(defun create_mini_table (table value id)
(let ((result (simple-table:make-table)))
(simple-table:with-rows (table row)
(if (funcall (get_equal (aref row id)) (aref row id) value)
(setq result (simple-table:add-to-table row result)))
)
(return-from create_mini_table result)
)
)
(defun union_groups (table id)
(let ((result (simple-table:make-table)))
(simple-table:with-rows (table row)
(if (not (in_table result row id))
(setq result (concatenate 'vector result (create_mini_table table (aref row id) id)))
)
)
(return-from union_groups result)
)
)
(defun group_by (table id &optional (agregate_functions '()))
(let ((result (simple-table:make-table)))
(if agregate_functions
(setq result (union_groups table (car id)))
(progn
(setq result (distinct table (car id)))))
(return-from group_by result)
)
)
| null | https://raw.githubusercontent.com/Ekatereana/CommonLispWorks/13111f7c45ec4d672dfdf3689ba22554d5c60727/groupby.lisp | lisp |
(defun create_mini_table (table value id)
(let ((result (simple-table:make-table)))
(simple-table:with-rows (table row)
(if (funcall (get_equal (aref row id)) (aref row id) value)
(setq result (simple-table:add-to-table row result)))
)
(return-from create_mini_table result)
)
)
(defun union_groups (table id)
(let ((result (simple-table:make-table)))
(simple-table:with-rows (table row)
(if (not (in_table result row id))
(setq result (concatenate 'vector result (create_mini_table table (aref row id) id)))
)
)
(return-from union_groups result)
)
)
(defun group_by (table id &optional (agregate_functions '()))
(let ((result (simple-table:make-table)))
(if agregate_functions
(setq result (union_groups table (car id)))
(progn
(setq result (distinct table (car id)))))
(return-from group_by result)
)
)
|
|
1db7e2275b4dd46e2e90795e56fe20218dfc6f5f507b1532f8318544f7ab9cd2 | mirage/synjitsu | config.ml | open Mirage
let main = foreign "Synjitsu.Main" (console @-> network @-> stackv4 @-> job)
let ipv4_config =
let address = Ipaddr.V4.of_string_exn "192.168.2.140" in
let netmask = Ipaddr.V4.of_string_exn "255.255.255.0" in
let gateways = [Ipaddr.V4.of_string_exn "192.168.2.1"] in
{ address; netmask; gateways }
let stack = direct_stackv4_with_static_ipv4 default_console tap0 ipv4_config
let platform =
match get_mode () with
| `Xen -> "xen"
| _ -> "unix"
let () =
add_to_opam_packages [
"mirage-conduit" ;
"cstruct" ;
"mirage-" ^ platform;
"mirage-net-" ^ platform;
"mirage-clock-" ^ platform;
"mirage-" ^ platform;
"mirage-types" ;
"tcpip" ];
add_to_ocamlfind_libraries [
"mirage-net-" ^ platform ;
"mirage-" ^ platform;
"mirage-clock-" ^ platform;
"tcpip.stack-direct" ;
"cstruct" ;
"cstruct.syntax" ;
"conduit" ;
"conduit.mirage-xen" ;
"mirage-types" ];
register "synjitsu" [ main $ default_console $ tap0 $ stack ]
| null | https://raw.githubusercontent.com/mirage/synjitsu/68adda5260802f936e7cc84b3d009c6a59ff055e/synjitsu/config.ml | ocaml | open Mirage
let main = foreign "Synjitsu.Main" (console @-> network @-> stackv4 @-> job)
let ipv4_config =
let address = Ipaddr.V4.of_string_exn "192.168.2.140" in
let netmask = Ipaddr.V4.of_string_exn "255.255.255.0" in
let gateways = [Ipaddr.V4.of_string_exn "192.168.2.1"] in
{ address; netmask; gateways }
let stack = direct_stackv4_with_static_ipv4 default_console tap0 ipv4_config
let platform =
match get_mode () with
| `Xen -> "xen"
| _ -> "unix"
let () =
add_to_opam_packages [
"mirage-conduit" ;
"cstruct" ;
"mirage-" ^ platform;
"mirage-net-" ^ platform;
"mirage-clock-" ^ platform;
"mirage-" ^ platform;
"mirage-types" ;
"tcpip" ];
add_to_ocamlfind_libraries [
"mirage-net-" ^ platform ;
"mirage-" ^ platform;
"mirage-clock-" ^ platform;
"tcpip.stack-direct" ;
"cstruct" ;
"cstruct.syntax" ;
"conduit" ;
"conduit.mirage-xen" ;
"mirage-types" ];
register "synjitsu" [ main $ default_console $ tap0 $ stack ]
|
|
8dce6b795517454e711c9a26813ef15aff5dc77d24ae7c6e0789f0c6d6865435 | db48x/xe2 | ldoc.lisp | ldoc.lisp --- extract and format documentation from lisp files
Copyright ( C ) 2009
Author : < >
;; Keywords: lisp, tools
;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :xe2)
;; todo show parent name if any
(defun clon-prototype-p (form)
(when (symbolp form)
(let* ((name (symbol-name form))
(len (length name)))
(and (string= "=" (subseq name 0 1))
(string= "=" (subseq name (- len 1) len))))))
(defun clon-method-p (form)
(when (symbolp form)
(let* ((delimiter ">>")
(name (symbol-name form))
(len (length name))
(delimiter-pos (search delimiter name)))
(when (numberp delimiter-pos)
(values (subseq name 0 delimiter-pos)
(subseq name (+ 2 delimiter-pos)))))))
(defun clon-parent-name (form)
(when (and (symbolp form) (boundp form))
(assert (symbol-value form))
(let ((parent (object-parent (symbol-value form))))
(when parent
(object-name parent)))))
(defun remove-delimiters (form)
(let* ((name (symbol-name form))
(len (length name)))
(subseq name 1 (- len 1))))
(defun document-symbol (symbol stream)
"Documentation string."
(let* ((type (if (clon-prototype-p symbol)
'variable
(if (fboundp symbol)
(if (macro-function symbol)
'function
'function)
'variable)))
(type-name (if (clon-method-p symbol)
"method" (if (clon-prototype-p symbol)
"prototype"
(if (fboundp symbol)
(if (macro-function symbol)
"macro" "function")
"variable"))))
(doc (if (clon-prototype-p symbol)
(field-value :documentation (symbol-value symbol))
(documentation symbol type)))
(name (if (clon-prototype-p symbol)
(remove-delimiters symbol)
(if (clon-method-p symbol)
(multiple-value-bind (method-name prototype-name) (clon-method-p symbol)
(format nil "~A [~A]" method-name prototype-name))
(symbol-name symbol))))
(args (when (fboundp symbol) (sb-introspect:function-lambda-list (fdefinition symbol)))))
(format stream "** ~A (~A)" name type-name)
(fresh-line stream)
(when args
(format stream "*** Arguments")
(fresh-line stream)
(format stream "~A" (if (clon-method-p symbol)
(cdr args) args))
(fresh-line stream))
(when doc
(format stream "*** Documentation")
(fresh-line stream)
(format stream "~A" doc))
(fresh-line stream)))
(defun do-heading (name stream)
(fresh-line stream)
(format stream "* ~A" name)
(fresh-line stream))
(defun document-package (package-name stream &optional preamble-file)
(let (syms protos methods proto-hashes preamble-lines)
(when preamble-file
(setf preamble-lines (with-open-file (file preamble-file
:direction :input
:if-does-not-exist nil)
(loop for line = (read-line file nil)
while line collect line))))
(do-external-symbols (sym package-name)
(when (< 3 (length (symbol-name sym)))
(push sym syms)))
(setf syms (sort syms #'string<))
;; print preamble
(dolist (line preamble-lines)
(format stream "~A" line)
(fresh-line stream))
;; sort symbols
(setf syms (remove-if #'(lambda (s)
(when (clon-prototype-p s)
(push s protos)))
syms))
(setf syms (remove-if #'(lambda (s)
(when (clon-method-p s)
(push s methods)))
syms))
;; document prototypes
(setf protos (nreverse protos))
(dolist (p protos)
(let (pile
(field-descriptors (when (and (clon-prototype-p p) (boundp p))
(field-value :field-descriptors (symbol-value p))))
(parent-name (clon-parent-name p)))
(dolist (m methods)
(multiple-value-bind (method-name proto-name)
(clon-method-p m)
(fresh-line t)
(when (string= proto-name (remove-delimiters p))
(push m pile))))
(setf pile (sort pile #'(lambda (s z)
(multiple-value-bind (method-name1 proto-name1)
(clon-method-p s)
(multiple-value-bind (method-name2 proto-name2)
(clon-method-p z)
(string> method-name1 method-name2))))))
(when pile
(do-heading (format nil "~A (prototype)" (symbol-name p)) stream)
(when parent-name
(fresh-line stream)
(format stream "** Parent prototype")
(fresh-line stream)
(format stream ": ~A" parent-name)
(fresh-line stream))
(let ((doc (field-value :documentation (symbol-value p))))
(when (stringp doc)
(format stream "** Documentation")
(fresh-line stream)
(format stream "~A" doc)
(fresh-line stream)))
(when field-descriptors
(format stream "*** Fields")
(fresh-line stream)
(dolist (d field-descriptors)
(fresh-line stream)
(destructuring-bind (name (&key documentation initform &allow-other-keys)) d
(when name (format stream "**** ~A (field)" name))
(when documentation
(fresh-line stream)
(format stream "***** Documentation")
(fresh-line stream)
(format stream "~A" documentation)
(fresh-line stream)
(when initform
(format stream "***** Initialization form")
(fresh-line stream)
(format stream ": ~S" initform))))))
(fresh-line stream)
(dolist (proto (reverse pile))
(document-symbol proto stream)))))
;; document syms
(do-heading "Symbols" stream)
(dolist (sym syms)
(document-symbol sym stream))))
(defun document-package-to-file (package-name output-file &optional preamble-file)
(with-open-file (stream output-file :direction :output :if-exists :supersede)
(document-package package-name stream preamble-file)))
( document - package : )
( document - package - to - file : xe2 # P"/home / dto / notebook / xe2 - reference.org " # P"/home / dto / xe2 / doc - preamble.org " )
( document - package : xe2 t # P"/home / dto / xe2 / doc - preamble.org " )
ldoc.lisp ends here
| null | https://raw.githubusercontent.com/db48x/xe2/7896fcc69f5c6e28eaf6f6abb7966d6663370a66/ldoc.lisp | lisp | Keywords: lisp, tools
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
todo show parent name if any
print preamble
sort symbols
document prototypes
document syms | ldoc.lisp --- extract and format documentation from lisp files
Copyright ( C ) 2009
Author : < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :xe2)
(defun clon-prototype-p (form)
(when (symbolp form)
(let* ((name (symbol-name form))
(len (length name)))
(and (string= "=" (subseq name 0 1))
(string= "=" (subseq name (- len 1) len))))))
(defun clon-method-p (form)
(when (symbolp form)
(let* ((delimiter ">>")
(name (symbol-name form))
(len (length name))
(delimiter-pos (search delimiter name)))
(when (numberp delimiter-pos)
(values (subseq name 0 delimiter-pos)
(subseq name (+ 2 delimiter-pos)))))))
(defun clon-parent-name (form)
(when (and (symbolp form) (boundp form))
(assert (symbol-value form))
(let ((parent (object-parent (symbol-value form))))
(when parent
(object-name parent)))))
(defun remove-delimiters (form)
(let* ((name (symbol-name form))
(len (length name)))
(subseq name 1 (- len 1))))
(defun document-symbol (symbol stream)
"Documentation string."
(let* ((type (if (clon-prototype-p symbol)
'variable
(if (fboundp symbol)
(if (macro-function symbol)
'function
'function)
'variable)))
(type-name (if (clon-method-p symbol)
"method" (if (clon-prototype-p symbol)
"prototype"
(if (fboundp symbol)
(if (macro-function symbol)
"macro" "function")
"variable"))))
(doc (if (clon-prototype-p symbol)
(field-value :documentation (symbol-value symbol))
(documentation symbol type)))
(name (if (clon-prototype-p symbol)
(remove-delimiters symbol)
(if (clon-method-p symbol)
(multiple-value-bind (method-name prototype-name) (clon-method-p symbol)
(format nil "~A [~A]" method-name prototype-name))
(symbol-name symbol))))
(args (when (fboundp symbol) (sb-introspect:function-lambda-list (fdefinition symbol)))))
(format stream "** ~A (~A)" name type-name)
(fresh-line stream)
(when args
(format stream "*** Arguments")
(fresh-line stream)
(format stream "~A" (if (clon-method-p symbol)
(cdr args) args))
(fresh-line stream))
(when doc
(format stream "*** Documentation")
(fresh-line stream)
(format stream "~A" doc))
(fresh-line stream)))
(defun do-heading (name stream)
(fresh-line stream)
(format stream "* ~A" name)
(fresh-line stream))
(defun document-package (package-name stream &optional preamble-file)
(let (syms protos methods proto-hashes preamble-lines)
(when preamble-file
(setf preamble-lines (with-open-file (file preamble-file
:direction :input
:if-does-not-exist nil)
(loop for line = (read-line file nil)
while line collect line))))
(do-external-symbols (sym package-name)
(when (< 3 (length (symbol-name sym)))
(push sym syms)))
(setf syms (sort syms #'string<))
(dolist (line preamble-lines)
(format stream "~A" line)
(fresh-line stream))
(setf syms (remove-if #'(lambda (s)
(when (clon-prototype-p s)
(push s protos)))
syms))
(setf syms (remove-if #'(lambda (s)
(when (clon-method-p s)
(push s methods)))
syms))
(setf protos (nreverse protos))
(dolist (p protos)
(let (pile
(field-descriptors (when (and (clon-prototype-p p) (boundp p))
(field-value :field-descriptors (symbol-value p))))
(parent-name (clon-parent-name p)))
(dolist (m methods)
(multiple-value-bind (method-name proto-name)
(clon-method-p m)
(fresh-line t)
(when (string= proto-name (remove-delimiters p))
(push m pile))))
(setf pile (sort pile #'(lambda (s z)
(multiple-value-bind (method-name1 proto-name1)
(clon-method-p s)
(multiple-value-bind (method-name2 proto-name2)
(clon-method-p z)
(string> method-name1 method-name2))))))
(when pile
(do-heading (format nil "~A (prototype)" (symbol-name p)) stream)
(when parent-name
(fresh-line stream)
(format stream "** Parent prototype")
(fresh-line stream)
(format stream ": ~A" parent-name)
(fresh-line stream))
(let ((doc (field-value :documentation (symbol-value p))))
(when (stringp doc)
(format stream "** Documentation")
(fresh-line stream)
(format stream "~A" doc)
(fresh-line stream)))
(when field-descriptors
(format stream "*** Fields")
(fresh-line stream)
(dolist (d field-descriptors)
(fresh-line stream)
(destructuring-bind (name (&key documentation initform &allow-other-keys)) d
(when name (format stream "**** ~A (field)" name))
(when documentation
(fresh-line stream)
(format stream "***** Documentation")
(fresh-line stream)
(format stream "~A" documentation)
(fresh-line stream)
(when initform
(format stream "***** Initialization form")
(fresh-line stream)
(format stream ": ~S" initform))))))
(fresh-line stream)
(dolist (proto (reverse pile))
(document-symbol proto stream)))))
(do-heading "Symbols" stream)
(dolist (sym syms)
(document-symbol sym stream))))
(defun document-package-to-file (package-name output-file &optional preamble-file)
(with-open-file (stream output-file :direction :output :if-exists :supersede)
(document-package package-name stream preamble-file)))
( document - package : )
( document - package - to - file : xe2 # P"/home / dto / notebook / xe2 - reference.org " # P"/home / dto / xe2 / doc - preamble.org " )
( document - package : xe2 t # P"/home / dto / xe2 / doc - preamble.org " )
ldoc.lisp ends here
|
e71164437a07e571f648fb30f9341fefd2608a44078d5b18c3b2876efa518ef1 | exercism/clojurescript | example.cljs | (ns rna-transcription)
(def ^:private
dna->rna {\G \C
\C \G
\A \U
\T \A})
(defn- translate [c]
{:post [%]}
(dna->rna c))
(defn to-rna [dna]
(apply str (map translate dna)))
| null | https://raw.githubusercontent.com/exercism/clojurescript/7700a33e17a798f6320aad01fb59a637bd21e12b/exercises/practice/rna-transcription/.meta/src/example.cljs | clojure | (ns rna-transcription)
(def ^:private
dna->rna {\G \C
\C \G
\A \U
\T \A})
(defn- translate [c]
{:post [%]}
(dna->rna c))
(defn to-rna [dna]
(apply str (map translate dna)))
|
|
40919f3dc0d35c2edabe13c4326d82c6ffda47216177e5bbccfa74330ae10062 | chef/stats_hero | capture_udp.erl | Copyright 2014 - 2016 Chef Software , Inc. 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(capture_udp).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-define(to_int(Value), list_to_integer(binary_to_list(Value))).
-export([peek/0,
read/0,
read_at_least/1,
start_link/1,
stop/0,
what_port/0]).
%% ------------------------------------------------------------------
gen_server Function Exports
%% ------------------------------------------------------------------
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {port :: non_neg_integer(),
socket :: inet:socket(),
msg_count = 0 :: non_neg_integer(),
buffer = [] :: iolist()
}).
%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------
-spec start_link(non_neg_integer()) -> {ok, pid()} | {error, any()}.
@doc Start a UDP capture server listening on ` Port ' . If ` Port ' is
%% `0', the system will assign a usable port which you can later
discover using { @link capture_udp : what_port/0 } .
start_link(Port) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, Port, []).
stop() ->
gen_server:call(?SERVER, stop).
-spec what_port() -> {ok, non_neg_integer()}.
%% @doc Return the port this server is listening on.
what_port() ->
gen_server:call(?SERVER, what_port).
-spec peek() -> {non_neg_integer(), iolist()}.
%% @doc Return the count and collected message iolist for the server.
%% The server state is not modified.
%% @see capture_udp:read/0
peek() ->
gen_server:call(?SERVER, peek).
-spec read() -> {non_neg_integer(), iolist()}.
%% @doc Return the message count and collected message iolist for the server.
%% Calling this function resets the message buffer and message counter.
%% @see capture_udp:peek/0
read() ->
gen_server:call(?SERVER, read).
-spec read_at_least(non_neg_integer()) -> {non_neg_integer(), iolist()}.
read_at_least(Num) ->
read_at_least(Num, {0, []}).
read_at_least(N, {Count, List}) when N =< 0 ->
{Count, lists:flatten(List)};
read_at_least(N, {Count, List}) ->
{NCount, NList} = read(),
read_at_least(N - NCount, {Count + NCount, [List|NList]}).
%% ------------------------------------------------------------------
gen_server Function Definitions
%% ------------------------------------------------------------------
init(Port) ->
RecBuf = 524288,
error_logger:info_msg("echo_udp listening on ~p with recbuf ~p~n", [Port, RecBuf]),
{ok, Socket} = gen_udp:open(Port, [binary, {active, once},
{recbuf, RecBuf}]),
{ok, #state{port = Port, socket = Socket}}.
handle_call(peek, _From, #state{msg_count = Count, buffer = Buffer}=State) ->
{reply, {Count, lists:reverse(Buffer)}, State};
handle_call(read, _From, #state{msg_count = Count, buffer = Buffer}=State) ->
{reply, {Count, lists:reverse(Buffer)}, State#state{msg_count = 0, buffer = []}};
handle_call(what_port, _From, #state{socket = Sock}=State) ->
{reply, inet:port(Sock), State};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Request, _From, State) ->
{noreply, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({udp, Socket, _Host, _Port, Bin},
#state{buffer = Buffer, msg_count = Count}=State) ->
inet:setopts(Socket, [{active, once}]),
{noreply, State#state{msg_count = Count + 1, buffer = [Bin|Buffer]}};
handle_info(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/chef/stats_hero/0811d3045874f6c16b76c04ac9358322e029c4b7/test/capture_udp.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 Function Definitions
------------------------------------------------------------------
`0', the system will assign a usable port which you can later
@doc Return the port this server is listening on.
@doc Return the count and collected message iolist for the server.
The server state is not modified.
@see capture_udp:read/0
@doc Return the message count and collected message iolist for the server.
Calling this function resets the message buffer and message counter.
@see capture_udp:peek/0
------------------------------------------------------------------
------------------------------------------------------------------ | Copyright 2014 - 2016 Chef Software , Inc. 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(capture_udp).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-define(to_int(Value), list_to_integer(binary_to_list(Value))).
-export([peek/0,
read/0,
read_at_least/1,
start_link/1,
stop/0,
what_port/0]).
gen_server Function Exports
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {port :: non_neg_integer(),
socket :: inet:socket(),
msg_count = 0 :: non_neg_integer(),
buffer = [] :: iolist()
}).
-spec start_link(non_neg_integer()) -> {ok, pid()} | {error, any()}.
@doc Start a UDP capture server listening on ` Port ' . If ` Port ' is
discover using { @link capture_udp : what_port/0 } .
start_link(Port) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, Port, []).
stop() ->
gen_server:call(?SERVER, stop).
-spec what_port() -> {ok, non_neg_integer()}.
what_port() ->
gen_server:call(?SERVER, what_port).
-spec peek() -> {non_neg_integer(), iolist()}.
peek() ->
gen_server:call(?SERVER, peek).
-spec read() -> {non_neg_integer(), iolist()}.
read() ->
gen_server:call(?SERVER, read).
-spec read_at_least(non_neg_integer()) -> {non_neg_integer(), iolist()}.
read_at_least(Num) ->
read_at_least(Num, {0, []}).
read_at_least(N, {Count, List}) when N =< 0 ->
{Count, lists:flatten(List)};
read_at_least(N, {Count, List}) ->
{NCount, NList} = read(),
read_at_least(N - NCount, {Count + NCount, [List|NList]}).
gen_server Function Definitions
init(Port) ->
RecBuf = 524288,
error_logger:info_msg("echo_udp listening on ~p with recbuf ~p~n", [Port, RecBuf]),
{ok, Socket} = gen_udp:open(Port, [binary, {active, once},
{recbuf, RecBuf}]),
{ok, #state{port = Port, socket = Socket}}.
handle_call(peek, _From, #state{msg_count = Count, buffer = Buffer}=State) ->
{reply, {Count, lists:reverse(Buffer)}, State};
handle_call(read, _From, #state{msg_count = Count, buffer = Buffer}=State) ->
{reply, {Count, lists:reverse(Buffer)}, State#state{msg_count = 0, buffer = []}};
handle_call(what_port, _From, #state{socket = Sock}=State) ->
{reply, inet:port(Sock), State};
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
handle_call(_Request, _From, State) ->
{noreply, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({udp, Socket, _Host, _Port, Bin},
#state{buffer = Buffer, msg_count = Count}=State) ->
inet:setopts(Socket, [{active, once}]),
{noreply, State#state{msg_count = Count + 1, buffer = [Bin|Buffer]}};
handle_info(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
4c7befa529ff3f1ec946e08dfa49f2a743593e32e2be23e74afc904ff7872726 | elaforge/karya | Browser.hs | Copyright 2013
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
| The instrument browser is a standalone program to browse the instrument
database .
Instruments are in the left pane , and the right pane has information on the
selected instrument . A search box above the instrument list accepts
a simple query language , documneted at ' Search . Query ' .
If you double click on an instrument name , ' choose_instrument ' is called on
the instrument .
The instrument info is basically just a pretty - printed version of the
contents of ' Patch . Patch ' .
Some parts of the instrument db may be generated offline , by
" Instrument . MakeDb " .
database.
Instruments are in the left pane, and the right pane has information on the
selected instrument. A search box above the instrument list accepts
a simple query language, documneted at 'Search.Query'.
If you double click on an instrument name, 'choose_instrument' is called on
the instrument.
The instrument info is basically just a pretty-printed version of the
contents of 'Patch.Patch'.
Some parts of the instrument db may be generated offline, by
"Instrument.MakeDb".
-}
module Instrument.Browser where
import qualified Control.Concurrent as Concurrent
import qualified Control.Concurrent.STM as STM
import qualified Control.Exception as Exception
import qualified Control.Monad.State as State
import qualified Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import qualified Data.Text.Lazy as Lazy
import qualified System.Console.GetOpt as GetOpt
import qualified System.Environment
import qualified System.Exit
import qualified Text.Printf as Printf
import qualified Util.Doc as Doc
import qualified Util.Fltk as Fltk
import qualified Util.FltkUtil as FltkUtil
import qualified Util.Format as Format
import qualified Util.Network as Network
import qualified Util.Seq as Seq
import qualified App.Config as Config
import qualified App.LoadInstruments as LoadInstruments
import qualified App.Path as Path
import qualified App.ReplProtocol as ReplProtocol
import qualified Cmd.CallDoc as CallDoc
import qualified Cmd.Cmd as Cmd
import qualified Derive.Derive as Derive
import qualified Derive.ScoreT as ScoreT
import qualified Instrument.BrowserC as BrowserC
import qualified Instrument.Common as Common
import qualified Instrument.Inst as Inst
import qualified Instrument.InstT as InstT
import qualified Instrument.Search as Search
import qualified Instrument.Tag as Tag
import qualified Perform.Im.Patch as Im.Patch
import qualified Perform.Midi.Control as Control
import qualified Perform.Midi.Patch as Patch
import qualified Perform.Sc.Patch as Sc.Patch
import Global
-- | Send this to the REPL when on a double-click on an instrument.
select_command :: Text
select_command = "LInst.set_instrument"
data Flag = Help | Geometry FltkUtil.Geometry
deriving (Eq, Show)
options :: [GetOpt.OptDescr Flag]
options =
[ GetOpt.Option [] ["help"] (GetOpt.NoArg Help) "display usage"
, FltkUtil.option Geometry
]
default_geometry :: Maybe FltkUtil.Geometry -> (Int, Int, Int, Int)
default_geometry = FltkUtil.xywh 50 50 550 600
main :: IO ()
main = ReplProtocol.initialize $ do
args <- System.Environment.getArgs
(flags, args) <- case GetOpt.getOpt GetOpt.Permute options args of
(flags, args, []) -> return (flags, args)
(_, _, errs) -> usage $ "flag errors:\n" ++ Seq.join ", " errs
unless (null args) $
usage ("unparsed args: " ++ show args)
when (Help `elem` flags) (usage "usage:")
db <- LoadInstruments.load =<< Path.get_app_dir
putStrLn $ "Loaded " ++ show (Inst.size db) ++ " instruments."
let geometry = Seq.head [g | Geometry g <- flags]
(x, y, w, h) = default_geometry geometry
win <- Fltk.run_action $ BrowserC.create x y w h
let index_db = Db db (Search.make_index db)
chan <- Fltk.new_channel
Concurrent.forkFinally (handle_msgs chan win index_db) $ \result -> do
putStrLn $ "handler thread died: "
++ either show (const "no exception")
(result :: Either Exception.SomeException ())
Fltk.quit chan
Fltk.event_loop chan
usage :: String -> IO a
usage msg = do
putStrLn $ "ERROR: " ++ msg
putStrLn "usage: browser [ flags ]"
putStr (GetOpt.usageInfo "" options)
System.Exit.exitFailure
| Bundle a Db along with its search index .
data Db = Db {
db_db :: Cmd.InstrumentDb
, db_index :: Search.Index
}
data State = State {
state_displayed :: [InstT.Qualified]
} deriving (Show)
handle_msgs :: Fltk.Channel -> BrowserC.Window -> Db -> IO ()
handle_msgs chan win db = do
displayed <- liftIO $ process_query chan win db [] ""
flip State.evalStateT (State displayed) $ forever $ do
Fltk.Msg typ text <- liftIO $ STM.atomically $ Fltk.read_msg win
let qualified = InstT.parse_qualified text
case typ of
BrowserC.Select -> liftIO $ show_info chan win db qualified
BrowserC.Choose -> liftIO $ choose_instrument qualified
BrowserC.Query -> do
state <- State.get
displayed <- liftIO $
process_query chan win db (state_displayed state) text
State.put (state { state_displayed = displayed })
BrowserC.Unknown c -> liftIO $
putStrLn $ "unknown msg type: " ++ show c
-- | Look up the instrument, generate a info sheet on it, and send to the UI.
show_info :: Fltk.Channel -> BrowserC.Window -> Db -> InstT.Qualified
-> IO ()
show_info chan win db qualified = Fltk.action chan $ BrowserC.set_info win info
where
info = fromMaybe ("not found: " <> InstT.show_qualified qualified) $ do
let InstT.Qualified synth_name inst_name = qualified
synth <- Inst.lookup_synth synth_name (db_db db)
inst <- Map.lookup inst_name (Inst.synth_insts synth)
let synth_doc = Inst.synth_doc synth <> " -- "
<> Inst.backend_name (Inst.inst_backend inst)
return $ info_of synth_name inst_name synth_doc inst tags
tags = fromMaybe [] $ Search.tags_of (db_index db) qualified
info_of :: InstT.SynthName -> InstT.Name -> Text -> Cmd.Inst
-> [Tag.Tag] -> Text
info_of synth_name name synth_doc (Inst.Inst backend common) tags =
synth_name <> " -- " <> (if Text.null name then "*" else name) <> " -- "
<> synth_doc <> "\n\n" <> body
where
body = format_fields $ common_fields tags common ++ backend_fields
backend_fields = case backend of
Inst.Dummy msg -> [("dummy msg", msg)]
Inst.Midi inst -> midi_fields name inst
Inst.Im patch -> im_patch_fields patch
Inst.Sc patch -> sc_patch_fields patch
common_fields :: [Tag.Tag] -> Common.Common Cmd.InstrumentCode -> [(Text, Text)]
common_fields tags common =
[ ("Environ", if env == mempty then "" else pretty env)
, ("Flags", Text.intercalate ", " $ map showt $ Set.toList flags)
, ("Call map", if Map.null call_map then "" else pretty call_map)
-- code
, ("Cmds", show_cmds code)
, ("Note generators",
show_calls CallDoc.GeneratorCall Derive.extract_doc gen)
, ("Note transformers",
show_calls CallDoc.TransformerCall Derive.extract_doc trans)
, ("Track calls",
show_calls CallDoc.TrackCall Derive.extract_track_doc track)
, ("Val calls", show_calls CallDoc.ValCall Derive.extract_val_doc val)
-- info
, ("Doc", doc)
, ("Tags", show_tags tags)
TODO lost the patch_file field
]
where
Derive.Scopes gen trans track val = Cmd.inst_calls code
show_calls ctype extract_doc =
show_call_bindings . CallDoc.entries ctype . CallDoc.call_map_to_entries
. CallDoc.call_map_doc extract_doc
Common.Common
{ common_code = code
, common_environ = env
, common_doc = Doc.Doc doc
, common_flags = flags
, common_call_map = call_map
} = common
midi_fields :: InstT.Name -> Patch.Patch -> [(Text, Text)]
midi_fields name patch =
-- important properties
[ ("Flags", Text.intercalate ", " $ map showt $ Set.toList $
fromMaybe mempty flags)
, ("Controls", show_control_map control_map)
, ("Control defaults", pretty control_defaults)
-- implementation details
, ("Attribute map", show_attribute_map attr_map)
, ("Mode map", show_mode_map mode_map)
, ("Pitchbend range", pretty pb_range)
, ("Decay", if decay == Nothing then "" else pretty decay)
, ("Scale", maybe "" pretty scale)
, ("Initialization", show_initialize initialize)
, ("Original name", if name == orig_name then "" else showt orig_name)
]
where
Patch.Patch
{ patch_name = orig_name
, patch_control_map = control_map
, patch_initialize = initialize
, patch_attribute_map = attr_map
, patch_mode_map = mode_map
, patch_defaults = settings
} = patch
Patch.Settings flags scale decay pb_range control_defaults = settings
im_patch_fields :: Im.Patch.Patch -> [(Text, Text)]
im_patch_fields (Im.Patch.Patch controls attr_map elements) =
[ ("Attributes", Text.intercalate ", " $ map pretty $
Common.mapped_attributes attr_map)
, ("Controls", Text.unlines
[ pretty control <> "\t" <> doc
| (control, doc) <- Map.toAscList controls
])
, ("Elements", Text.unwords (Set.toList elements))
]
sc_patch_fields :: Sc.Patch.Patch -> [(Text, Text)]
sc_patch_fields (Sc.Patch.Patch _name _filename controls) =
[ ("Controls", Text.unlines
[ pretty control <> "\t" <> showt id
| (control, id) <- Map.toAscList controls
])
]
format_fields :: [(Text, Text)] -> Text
format_fields = Text.unlines . filter (not . Text.null) . map field
field :: (Text, Text) -> Text
field (title, raw_text)
| Text.null text = ""
| Text.length text < 40 && not ("\n" `Text.isInfixOf` text) =
title <> ": " <> text <> "\n"
| otherwise = "\t" <> title <> ":\n" <> text <> "\n"
where text = Text.strip raw_text
show_attribute_map :: Patch.AttributeMap -> Text
show_attribute_map (Common.AttributeMap table) =
Text.unlines $ map fmt (Seq.sort_on (low_key . snd) table)
where
attrs = map (prettys . fst) table
longest = fromMaybe 0 $ Seq.maximum (map length attrs)
-- If this instrument uses a keymap, it's easier to read the attribute map
-- if I put it in keymap order.
low_key (_, Just (Patch.UnpitchedKeymap k)) = Just k
low_key (_, Just (Patch.PitchedKeymap k _ _)) = Just k
low_key (_, Nothing) = Nothing
fmt (attrs, (keyswitches, maybe_keymap)) =
-- Still not quite right for lining up columns.
txt (Printf.printf "%-*s\t" longest (prettys attrs))
<> pretty keyswitches <> maybe "" ((" "<>) . pretty) maybe_keymap
show_mode_map :: Patch.ModeMap -> Text
show_mode_map (Patch.ModeMap table) = Text.unlines
[ key <> ": " <> Text.intercalate ", "
[ pretty val <> "=" <> pretty ks
| (val, ks) <- Map.toList modes
] <> " [default: " <> pretty deflt <> "]"
| (key, (deflt, modes)) <- Map.toAscList table
]
show_control_map :: Control.ControlMap -> Text
show_control_map cmap =
Text.intercalate ", " [ScoreT.control_name cont <> " (" <> showt num <> ")"
| (cont, num) <- Map.toList cmap]
show_cmds :: Cmd.InstrumentCode -> Text
show_cmds code = Text.unlines $ concat
[ map show_handler (Cmd.inst_cmds code)
, maybe [] (const ["[custom thru]"]) $ Cmd.inst_thru code
]
show_handler :: Cmd.Handler m -> Text
show_handler = \case
Cmd.Handler (Just note_entry) cmd ->
Cmd.cmd_name cmd <> ": " <> case note_entry of
Cmd.WithoutOctave m -> list $ Map.elems m
Cmd.WithOctave m -> list $ concatMap Map.elems $ Map.elems m
where
list xs = "["
<> Text.unwords (Seq.unique (filter (not . Text.null) xs))
<> "]"
Cmd.Handler Nothing cmd -> Cmd.cmd_name cmd
Cmd.Keymap keymap -> pretty $ map Cmd.cmd_name $ Map.elems keymap
show_call_bindings :: [CallDoc.CallBindings] -> Text
show_call_bindings = Lazy.toStrict . Format.render "\t" 10000
. Format.paragraphs . map (CallDoc.call_bindings_text False)
Let fltk do the wrapping . Of course it does n't know how the indentation
-- works, so wrapped lines don't get indented, but it doesn't look that
-- bad.
show_tags :: [(Text, Text)] -> Text
show_tags tags =
Text.unwords [quote k <> "=" <> quote v | (k, v) <- Seq.sort_on fst tags]
show_initialize :: Patch.InitializePatch -> Text
show_initialize = \case
Patch.NoInitialization -> ""
Patch.InitializeMessage msg -> "Message: " <> msg
Patch.InitializeMidi msgs -> Text.unlines (map pretty msgs)
quote :: Text -> Text
quote s
| Text.any Char.isSpace s = "\"" <> s <> "\""
| otherwise = s
-- | Send the chosen instrument to the sequencer. This will send
-- @change_instrument \"synth/inst\"@ to the REPL port.
choose_instrument :: InstT.Qualified -> IO ()
choose_instrument qualified = do
let cmd = select_command <> " "
<> showt (InstT.show_qualified qualified)
Text.IO.putStrLn $ "send: " <> cmd
response <- query cmd
unless (Text.null response) $
Text.IO.putStrLn $ "response: " <> response
query :: Text -> IO Text
query = fmap ReplProtocol.format_result
. ReplProtocol.query_cmd (Network.Unix Config.repl_socket_name)
-- | Find instruments that match the query, and update the UI incrementally.
process_query :: Fltk.Channel -> BrowserC.Window -> Db -> [InstT.Qualified]
-> Text -> IO [InstT.Qualified]
process_query chan win db displayed query = do
let matches = Search.search (db_index db) (Search.parse query)
diff = Seq.diff_index (==) displayed matches
forM_ diff $ \(i, paired) -> case paired of
Seq.Second inst -> Fltk.action chan $
BrowserC.insert_line win (i+1) (InstT.show_qualified inst)
Seq.First _inst -> Fltk.action chan $
BrowserC.remove_line win (i+1)
_ -> return ()
return matches
| null | https://raw.githubusercontent.com/elaforge/karya/89d1651424c35e564138d93424a157ff87457245/Instrument/Browser.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
| Send this to the REPL when on a double-click on an instrument.
| Look up the instrument, generate a info sheet on it, and send to the UI.
code
info
important properties
implementation details
If this instrument uses a keymap, it's easier to read the attribute map
if I put it in keymap order.
Still not quite right for lining up columns.
works, so wrapped lines don't get indented, but it doesn't look that
bad.
| Send the chosen instrument to the sequencer. This will send
@change_instrument \"synth/inst\"@ to the REPL port.
| Find instruments that match the query, and update the UI incrementally. | Copyright 2013
| The instrument browser is a standalone program to browse the instrument
database .
Instruments are in the left pane , and the right pane has information on the
selected instrument . A search box above the instrument list accepts
a simple query language , documneted at ' Search . Query ' .
If you double click on an instrument name , ' choose_instrument ' is called on
the instrument .
The instrument info is basically just a pretty - printed version of the
contents of ' Patch . Patch ' .
Some parts of the instrument db may be generated offline , by
" Instrument . MakeDb " .
database.
Instruments are in the left pane, and the right pane has information on the
selected instrument. A search box above the instrument list accepts
a simple query language, documneted at 'Search.Query'.
If you double click on an instrument name, 'choose_instrument' is called on
the instrument.
The instrument info is basically just a pretty-printed version of the
contents of 'Patch.Patch'.
Some parts of the instrument db may be generated offline, by
"Instrument.MakeDb".
-}
module Instrument.Browser where
import qualified Control.Concurrent as Concurrent
import qualified Control.Concurrent.STM as STM
import qualified Control.Exception as Exception
import qualified Control.Monad.State as State
import qualified Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Data.Text.IO as Text.IO
import qualified Data.Text.Lazy as Lazy
import qualified System.Console.GetOpt as GetOpt
import qualified System.Environment
import qualified System.Exit
import qualified Text.Printf as Printf
import qualified Util.Doc as Doc
import qualified Util.Fltk as Fltk
import qualified Util.FltkUtil as FltkUtil
import qualified Util.Format as Format
import qualified Util.Network as Network
import qualified Util.Seq as Seq
import qualified App.Config as Config
import qualified App.LoadInstruments as LoadInstruments
import qualified App.Path as Path
import qualified App.ReplProtocol as ReplProtocol
import qualified Cmd.CallDoc as CallDoc
import qualified Cmd.Cmd as Cmd
import qualified Derive.Derive as Derive
import qualified Derive.ScoreT as ScoreT
import qualified Instrument.BrowserC as BrowserC
import qualified Instrument.Common as Common
import qualified Instrument.Inst as Inst
import qualified Instrument.InstT as InstT
import qualified Instrument.Search as Search
import qualified Instrument.Tag as Tag
import qualified Perform.Im.Patch as Im.Patch
import qualified Perform.Midi.Control as Control
import qualified Perform.Midi.Patch as Patch
import qualified Perform.Sc.Patch as Sc.Patch
import Global
select_command :: Text
select_command = "LInst.set_instrument"
data Flag = Help | Geometry FltkUtil.Geometry
deriving (Eq, Show)
options :: [GetOpt.OptDescr Flag]
options =
[ GetOpt.Option [] ["help"] (GetOpt.NoArg Help) "display usage"
, FltkUtil.option Geometry
]
default_geometry :: Maybe FltkUtil.Geometry -> (Int, Int, Int, Int)
default_geometry = FltkUtil.xywh 50 50 550 600
main :: IO ()
main = ReplProtocol.initialize $ do
args <- System.Environment.getArgs
(flags, args) <- case GetOpt.getOpt GetOpt.Permute options args of
(flags, args, []) -> return (flags, args)
(_, _, errs) -> usage $ "flag errors:\n" ++ Seq.join ", " errs
unless (null args) $
usage ("unparsed args: " ++ show args)
when (Help `elem` flags) (usage "usage:")
db <- LoadInstruments.load =<< Path.get_app_dir
putStrLn $ "Loaded " ++ show (Inst.size db) ++ " instruments."
let geometry = Seq.head [g | Geometry g <- flags]
(x, y, w, h) = default_geometry geometry
win <- Fltk.run_action $ BrowserC.create x y w h
let index_db = Db db (Search.make_index db)
chan <- Fltk.new_channel
Concurrent.forkFinally (handle_msgs chan win index_db) $ \result -> do
putStrLn $ "handler thread died: "
++ either show (const "no exception")
(result :: Either Exception.SomeException ())
Fltk.quit chan
Fltk.event_loop chan
usage :: String -> IO a
usage msg = do
putStrLn $ "ERROR: " ++ msg
putStrLn "usage: browser [ flags ]"
putStr (GetOpt.usageInfo "" options)
System.Exit.exitFailure
| Bundle a Db along with its search index .
data Db = Db {
db_db :: Cmd.InstrumentDb
, db_index :: Search.Index
}
data State = State {
state_displayed :: [InstT.Qualified]
} deriving (Show)
handle_msgs :: Fltk.Channel -> BrowserC.Window -> Db -> IO ()
handle_msgs chan win db = do
displayed <- liftIO $ process_query chan win db [] ""
flip State.evalStateT (State displayed) $ forever $ do
Fltk.Msg typ text <- liftIO $ STM.atomically $ Fltk.read_msg win
let qualified = InstT.parse_qualified text
case typ of
BrowserC.Select -> liftIO $ show_info chan win db qualified
BrowserC.Choose -> liftIO $ choose_instrument qualified
BrowserC.Query -> do
state <- State.get
displayed <- liftIO $
process_query chan win db (state_displayed state) text
State.put (state { state_displayed = displayed })
BrowserC.Unknown c -> liftIO $
putStrLn $ "unknown msg type: " ++ show c
show_info :: Fltk.Channel -> BrowserC.Window -> Db -> InstT.Qualified
-> IO ()
show_info chan win db qualified = Fltk.action chan $ BrowserC.set_info win info
where
info = fromMaybe ("not found: " <> InstT.show_qualified qualified) $ do
let InstT.Qualified synth_name inst_name = qualified
synth <- Inst.lookup_synth synth_name (db_db db)
inst <- Map.lookup inst_name (Inst.synth_insts synth)
let synth_doc = Inst.synth_doc synth <> " -- "
<> Inst.backend_name (Inst.inst_backend inst)
return $ info_of synth_name inst_name synth_doc inst tags
tags = fromMaybe [] $ Search.tags_of (db_index db) qualified
info_of :: InstT.SynthName -> InstT.Name -> Text -> Cmd.Inst
-> [Tag.Tag] -> Text
info_of synth_name name synth_doc (Inst.Inst backend common) tags =
synth_name <> " -- " <> (if Text.null name then "*" else name) <> " -- "
<> synth_doc <> "\n\n" <> body
where
body = format_fields $ common_fields tags common ++ backend_fields
backend_fields = case backend of
Inst.Dummy msg -> [("dummy msg", msg)]
Inst.Midi inst -> midi_fields name inst
Inst.Im patch -> im_patch_fields patch
Inst.Sc patch -> sc_patch_fields patch
common_fields :: [Tag.Tag] -> Common.Common Cmd.InstrumentCode -> [(Text, Text)]
common_fields tags common =
[ ("Environ", if env == mempty then "" else pretty env)
, ("Flags", Text.intercalate ", " $ map showt $ Set.toList flags)
, ("Call map", if Map.null call_map then "" else pretty call_map)
, ("Cmds", show_cmds code)
, ("Note generators",
show_calls CallDoc.GeneratorCall Derive.extract_doc gen)
, ("Note transformers",
show_calls CallDoc.TransformerCall Derive.extract_doc trans)
, ("Track calls",
show_calls CallDoc.TrackCall Derive.extract_track_doc track)
, ("Val calls", show_calls CallDoc.ValCall Derive.extract_val_doc val)
, ("Doc", doc)
, ("Tags", show_tags tags)
TODO lost the patch_file field
]
where
Derive.Scopes gen trans track val = Cmd.inst_calls code
show_calls ctype extract_doc =
show_call_bindings . CallDoc.entries ctype . CallDoc.call_map_to_entries
. CallDoc.call_map_doc extract_doc
Common.Common
{ common_code = code
, common_environ = env
, common_doc = Doc.Doc doc
, common_flags = flags
, common_call_map = call_map
} = common
midi_fields :: InstT.Name -> Patch.Patch -> [(Text, Text)]
midi_fields name patch =
[ ("Flags", Text.intercalate ", " $ map showt $ Set.toList $
fromMaybe mempty flags)
, ("Controls", show_control_map control_map)
, ("Control defaults", pretty control_defaults)
, ("Attribute map", show_attribute_map attr_map)
, ("Mode map", show_mode_map mode_map)
, ("Pitchbend range", pretty pb_range)
, ("Decay", if decay == Nothing then "" else pretty decay)
, ("Scale", maybe "" pretty scale)
, ("Initialization", show_initialize initialize)
, ("Original name", if name == orig_name then "" else showt orig_name)
]
where
Patch.Patch
{ patch_name = orig_name
, patch_control_map = control_map
, patch_initialize = initialize
, patch_attribute_map = attr_map
, patch_mode_map = mode_map
, patch_defaults = settings
} = patch
Patch.Settings flags scale decay pb_range control_defaults = settings
im_patch_fields :: Im.Patch.Patch -> [(Text, Text)]
im_patch_fields (Im.Patch.Patch controls attr_map elements) =
[ ("Attributes", Text.intercalate ", " $ map pretty $
Common.mapped_attributes attr_map)
, ("Controls", Text.unlines
[ pretty control <> "\t" <> doc
| (control, doc) <- Map.toAscList controls
])
, ("Elements", Text.unwords (Set.toList elements))
]
sc_patch_fields :: Sc.Patch.Patch -> [(Text, Text)]
sc_patch_fields (Sc.Patch.Patch _name _filename controls) =
[ ("Controls", Text.unlines
[ pretty control <> "\t" <> showt id
| (control, id) <- Map.toAscList controls
])
]
format_fields :: [(Text, Text)] -> Text
format_fields = Text.unlines . filter (not . Text.null) . map field
field :: (Text, Text) -> Text
field (title, raw_text)
| Text.null text = ""
| Text.length text < 40 && not ("\n" `Text.isInfixOf` text) =
title <> ": " <> text <> "\n"
| otherwise = "\t" <> title <> ":\n" <> text <> "\n"
where text = Text.strip raw_text
show_attribute_map :: Patch.AttributeMap -> Text
show_attribute_map (Common.AttributeMap table) =
Text.unlines $ map fmt (Seq.sort_on (low_key . snd) table)
where
attrs = map (prettys . fst) table
longest = fromMaybe 0 $ Seq.maximum (map length attrs)
low_key (_, Just (Patch.UnpitchedKeymap k)) = Just k
low_key (_, Just (Patch.PitchedKeymap k _ _)) = Just k
low_key (_, Nothing) = Nothing
fmt (attrs, (keyswitches, maybe_keymap)) =
txt (Printf.printf "%-*s\t" longest (prettys attrs))
<> pretty keyswitches <> maybe "" ((" "<>) . pretty) maybe_keymap
show_mode_map :: Patch.ModeMap -> Text
show_mode_map (Patch.ModeMap table) = Text.unlines
[ key <> ": " <> Text.intercalate ", "
[ pretty val <> "=" <> pretty ks
| (val, ks) <- Map.toList modes
] <> " [default: " <> pretty deflt <> "]"
| (key, (deflt, modes)) <- Map.toAscList table
]
show_control_map :: Control.ControlMap -> Text
show_control_map cmap =
Text.intercalate ", " [ScoreT.control_name cont <> " (" <> showt num <> ")"
| (cont, num) <- Map.toList cmap]
show_cmds :: Cmd.InstrumentCode -> Text
show_cmds code = Text.unlines $ concat
[ map show_handler (Cmd.inst_cmds code)
, maybe [] (const ["[custom thru]"]) $ Cmd.inst_thru code
]
show_handler :: Cmd.Handler m -> Text
show_handler = \case
Cmd.Handler (Just note_entry) cmd ->
Cmd.cmd_name cmd <> ": " <> case note_entry of
Cmd.WithoutOctave m -> list $ Map.elems m
Cmd.WithOctave m -> list $ concatMap Map.elems $ Map.elems m
where
list xs = "["
<> Text.unwords (Seq.unique (filter (not . Text.null) xs))
<> "]"
Cmd.Handler Nothing cmd -> Cmd.cmd_name cmd
Cmd.Keymap keymap -> pretty $ map Cmd.cmd_name $ Map.elems keymap
show_call_bindings :: [CallDoc.CallBindings] -> Text
show_call_bindings = Lazy.toStrict . Format.render "\t" 10000
. Format.paragraphs . map (CallDoc.call_bindings_text False)
Let fltk do the wrapping . Of course it does n't know how the indentation
show_tags :: [(Text, Text)] -> Text
show_tags tags =
Text.unwords [quote k <> "=" <> quote v | (k, v) <- Seq.sort_on fst tags]
show_initialize :: Patch.InitializePatch -> Text
show_initialize = \case
Patch.NoInitialization -> ""
Patch.InitializeMessage msg -> "Message: " <> msg
Patch.InitializeMidi msgs -> Text.unlines (map pretty msgs)
quote :: Text -> Text
quote s
| Text.any Char.isSpace s = "\"" <> s <> "\""
| otherwise = s
choose_instrument :: InstT.Qualified -> IO ()
choose_instrument qualified = do
let cmd = select_command <> " "
<> showt (InstT.show_qualified qualified)
Text.IO.putStrLn $ "send: " <> cmd
response <- query cmd
unless (Text.null response) $
Text.IO.putStrLn $ "response: " <> response
query :: Text -> IO Text
query = fmap ReplProtocol.format_result
. ReplProtocol.query_cmd (Network.Unix Config.repl_socket_name)
process_query :: Fltk.Channel -> BrowserC.Window -> Db -> [InstT.Qualified]
-> Text -> IO [InstT.Qualified]
process_query chan win db displayed query = do
let matches = Search.search (db_index db) (Search.parse query)
diff = Seq.diff_index (==) displayed matches
forM_ diff $ \(i, paired) -> case paired of
Seq.Second inst -> Fltk.action chan $
BrowserC.insert_line win (i+1) (InstT.show_qualified inst)
Seq.First _inst -> Fltk.action chan $
BrowserC.remove_line win (i+1)
_ -> return ()
return matches
|
4b82c2158ddd54c91a4f0378ad8fb26d7734dd0aa93ba6335eef56033091b958 | vbmithr/ocaml-thrift-lib | test_types.mli |
Autogenerated by Thrift Compiler ( 0.16.0 )
DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING
Autogenerated by Thrift Compiler (0.16.0)
DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING
*)
open Thrift
class nestedStruct :
object ('a)
method get_message : string option
method grab_message : string
method set_message : string -> unit
method unset_message : unit
method reset_message : unit
method copy : 'a
method write : Protocol.t -> unit
end
val read_nestedStruct : Protocol.t -> nestedStruct
class testStruct :
object ('a)
method get_int32 : Int32.t option
method grab_int32 : Int32.t
method set_int32 : Int32.t -> unit
method unset_int32 : unit
method reset_int32 : unit
method get_long : Int64.t option
method grab_long : Int64.t
method set_long : Int64.t -> unit
method unset_long : unit
method reset_long : unit
method get_trueVal : bool option
method grab_trueVal : bool
method set_trueVal : bool -> unit
method reset_trueVal : unit
method get_falseVal : bool option
method grab_falseVal : bool
method set_falseVal : bool -> unit
method unset_falseVal : unit
method reset_falseVal : unit
method get_decimal : float option
method grab_decimal : float
method set_decimal : float -> unit
method unset_decimal : unit
method reset_decimal : unit
method get_comment : string option
method grab_comment : string
method set_comment : string -> unit
method unset_comment : unit
method reset_comment : unit
method get_nested : nestedStruct option
method grab_nested : nestedStruct
method set_nested : nestedStruct -> unit
method unset_nested : unit
method reset_nested : unit
method get_bools : bool list option
method grab_bools : bool list
method set_bools : bool list -> unit
method unset_bools : unit
method reset_bools : unit
method copy : 'a
method write : Protocol.t -> unit
end
val read_testStruct : Protocol.t -> testStruct
| null | https://raw.githubusercontent.com/vbmithr/ocaml-thrift-lib/1e5b7924636d8926114cbd34398a0848cd472e83/test/gen-ocaml/test_types.mli | ocaml |
Autogenerated by Thrift Compiler ( 0.16.0 )
DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING
Autogenerated by Thrift Compiler (0.16.0)
DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING
*)
open Thrift
class nestedStruct :
object ('a)
method get_message : string option
method grab_message : string
method set_message : string -> unit
method unset_message : unit
method reset_message : unit
method copy : 'a
method write : Protocol.t -> unit
end
val read_nestedStruct : Protocol.t -> nestedStruct
class testStruct :
object ('a)
method get_int32 : Int32.t option
method grab_int32 : Int32.t
method set_int32 : Int32.t -> unit
method unset_int32 : unit
method reset_int32 : unit
method get_long : Int64.t option
method grab_long : Int64.t
method set_long : Int64.t -> unit
method unset_long : unit
method reset_long : unit
method get_trueVal : bool option
method grab_trueVal : bool
method set_trueVal : bool -> unit
method reset_trueVal : unit
method get_falseVal : bool option
method grab_falseVal : bool
method set_falseVal : bool -> unit
method unset_falseVal : unit
method reset_falseVal : unit
method get_decimal : float option
method grab_decimal : float
method set_decimal : float -> unit
method unset_decimal : unit
method reset_decimal : unit
method get_comment : string option
method grab_comment : string
method set_comment : string -> unit
method unset_comment : unit
method reset_comment : unit
method get_nested : nestedStruct option
method grab_nested : nestedStruct
method set_nested : nestedStruct -> unit
method unset_nested : unit
method reset_nested : unit
method get_bools : bool list option
method grab_bools : bool list
method set_bools : bool list -> unit
method unset_bools : unit
method reset_bools : unit
method copy : 'a
method write : Protocol.t -> unit
end
val read_testStruct : Protocol.t -> testStruct
|
|
def3049eddb8a0cd5c135a567a44edc315ca57013ade2e228298b5df3c194776 | haskell/ghcide | HieUtils.hs | module Compat.HieUtils
( module HieUtils ) where
import HieUtils
| null | https://raw.githubusercontent.com/haskell/ghcide/3ef4ef99c4b9cde867d29180c32586947df64b9e/hie-compat/src-reexport/Compat/HieUtils.hs | haskell | module Compat.HieUtils
( module HieUtils ) where
import HieUtils
|
|
8647851e3055710fe90455e91c1e40732860fe510c154ce21b7dafb845300c1c | yashrk/raylib-scm | 3d_camera_first_person.scm | (include "raylib-definitions.scm")
(import defstruct
raylib-scm
srfi-1)
(use format raylib-scm srfi-1)
(define max-columns 20)
(define screen-width 800)
(define screen-height 450)
(define camera (make-camera (make-vector-3 4.0 2.0 4.0)
(make-vector-3 0.0 1.8 0.0)
(make-vector-3 0.0 1.0 0.0)
60.0
camera-type/perspective))
(defstruct column
height position color)
(define columns
(map (lambda (i)
(let ((height (get-random-value 1 12)))
(make-column height: height
position: (make-vector-3 (get-random-value -15 15)
(/ height 2)
(get-random-value -15 15))
color: (make-color (get-random-value 20 255)
(get-random-value 20 255)
30
255))))
(iota max-columns)))
(define cube-position (make-vector-3 0.0 0.0 0.0))
(define (main-loop)
(if (not (window-should-close?))
(begin
(update-camera camera)
(begin-drawing)
(clear-background RAYWHITE)
(begin-mode-3d camera)
(draw-plane (make-vector-3 0.0 0.0 0.0) ; Draw ground
(make-vector-2 32.0 32.0)
LIGHTGRAY)
(draw-cube (make-vector-3 -16.0 2.5 0.0) ; Draw a blue wall
1.0
5.0
32.0
BLUE)
(draw-cube (make-vector-3 16.0 2.5 0.0) ; Draw a green wall
1.0
5.0
32.0
LIME)
(draw-cube (make-vector-3 0.0 2.5 16.0) ; Draw a yellow wall
32.0
5.0
1.0
GOLD)
(for-each (lambda (c)
(draw-cube (column-position c)
2.0
(column-height c)
2.0
(column-color c))
(draw-cube-wires (column-position c)
2.0
(column-height c)
2.0
MAROON))
columns)
(end-mode-3d)
(draw-rectangle 10 10 220 70 (fade SKYBLUE 0.5))
(draw-rectangle-lines 10 10 220 70 BLUE)
(draw-text "First person camera default controls:" 20 20 10 BLACK)
(draw-text "- Move with keys: W, A, S, D" 40 40 10 DARKGRAY)
(draw-text "- Mouse move to look around" 40 60 10 DARKGRAY)
(end-drawing)
(main-loop))
(close-window)))
(init-window screen-width screen-height "raylib [core] example - 3d camera first person")
(set-camera-mode camera camera-mode/camera-first-person)
(set-target-fps 60)
(main-loop)
| null | https://raw.githubusercontent.com/yashrk/raylib-scm/b4c6fe17374ce4ddd4162fda37f4691b1e35b5f2/examples/core/3d_camera_first_person/3d_camera_first_person.scm | scheme | Draw ground
Draw a blue wall
Draw a green wall
Draw a yellow wall | (include "raylib-definitions.scm")
(import defstruct
raylib-scm
srfi-1)
(use format raylib-scm srfi-1)
(define max-columns 20)
(define screen-width 800)
(define screen-height 450)
(define camera (make-camera (make-vector-3 4.0 2.0 4.0)
(make-vector-3 0.0 1.8 0.0)
(make-vector-3 0.0 1.0 0.0)
60.0
camera-type/perspective))
(defstruct column
height position color)
(define columns
(map (lambda (i)
(let ((height (get-random-value 1 12)))
(make-column height: height
position: (make-vector-3 (get-random-value -15 15)
(/ height 2)
(get-random-value -15 15))
color: (make-color (get-random-value 20 255)
(get-random-value 20 255)
30
255))))
(iota max-columns)))
(define cube-position (make-vector-3 0.0 0.0 0.0))
(define (main-loop)
(if (not (window-should-close?))
(begin
(update-camera camera)
(begin-drawing)
(clear-background RAYWHITE)
(begin-mode-3d camera)
(make-vector-2 32.0 32.0)
LIGHTGRAY)
1.0
5.0
32.0
BLUE)
1.0
5.0
32.0
LIME)
32.0
5.0
1.0
GOLD)
(for-each (lambda (c)
(draw-cube (column-position c)
2.0
(column-height c)
2.0
(column-color c))
(draw-cube-wires (column-position c)
2.0
(column-height c)
2.0
MAROON))
columns)
(end-mode-3d)
(draw-rectangle 10 10 220 70 (fade SKYBLUE 0.5))
(draw-rectangle-lines 10 10 220 70 BLUE)
(draw-text "First person camera default controls:" 20 20 10 BLACK)
(draw-text "- Move with keys: W, A, S, D" 40 40 10 DARKGRAY)
(draw-text "- Mouse move to look around" 40 60 10 DARKGRAY)
(end-drawing)
(main-loop))
(close-window)))
(init-window screen-width screen-height "raylib [core] example - 3d camera first person")
(set-camera-mode camera camera-mode/camera-first-person)
(set-target-fps 60)
(main-loop)
|
bd44b7859c2e18521129b7e876bb1eb4cecb689a4d01bb85e413b85450b5dc95 | unfoldr/Salsa | Core.hs | # LANGUAGE GADTs , TypeFamilies , MultiParamTypeClasses , EmptyDataDecls #
# LANGUAGE ExistentialQuantification , FlexibleContexts , TypeOperators #
# LANGUAGE ScopedTypeVariables , TypeSynonymInstances , FlexibleInstances #
# LANGUAGE UndecidableInstances #
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Salsa.Core
Copyright : ( c ) 2007 - 2008
-- Licence : BSD-style (see LICENSE)
--
-----------------------------------------------------------------------------
module Foreign.Salsa.Core where
import Unsafe.Coerce (unsafeCoerce)
import System.IO.Unsafe ( unsafePerformIO )
import Foreign.C.String
import System.Win32
import Foreign hiding (new, newForeignPtr, unsafePerformIO)
import Foreign.Concurrent (newForeignPtr)
import Foreign.Salsa.Common
import Foreign.Salsa.TypePrelude
import Foreign.Salsa.Resolver
import Foreign.Salsa.CLR
-- Reverse function application
x # f = f x
-- Binding to the target of a method invocation
t >>=# m = t >>= ( # m )
null_ :: Obj Null
null_ = ObjNull
isNull :: Obj a -> Bool
isNull ObjNull = True
isNull _ = False
--
-- Method invocation
--
-- | @'Candidates' t m@ is a type-level list of the members of a particular
-- method group, given the type @t@ and method name @m@. The overload
-- resolution algorithm chooses the appropriate member of the method group
-- (from this list) according to the argument types.
type family Candidates t m
-- Calls 'ResolveMember', converting argument tuples to/from type-level lists,
-- and passing it the appropriate list of candidate signatures.
type family Resolve t m args
type instance Resolve t m args = ListToTuple (ResolveMember (TupleToList args) (Candidates t m))
| ' ' provides type - based dispatch to method implementations , and
-- a constrainted result type for method invocations.
class Invoker t m args where
type Result t m args
rawInvoke :: t -> m -> args -> Result t m args
| @'invoke ' t m invokes the appropriate method @m@ in type @t@ given
-- the tuple of arguments @args@.
invoke :: forall t m args args'.
(Resolve t m args ~ args',
Coercible args args',
Invoker t m args') =>
t -> m -> args -> Result t m args'
invoke t m args = rawInvoke t m (coerce args :: args')
--
-- Constructor invocation
--
data Ctor = Ctor deriving (Show, Eq)
| @'new ' t invokes the appropriate constructor for the type @t@
-- given the tuple of arguments @args@, and returns an instance of the
-- constructed type.
new t args = invoke t Ctor args
--
-- Delegate support
--
class Delegate dt where
type DelegateT dt -- ^ High-level function type for the delegate implementation
-- | @'delegate' dt h@ calls the constructor for the delegate of type @t@, returning
a .NET delegate object of the same type whose implementation is the Haskell
function , @h@.
delegate :: dt -> (DelegateT dt) -> IO (Obj dt)
--
-- Attribute system for .NET properties and events
--
| @Prop t represents a .NET property with name @pn@ , on the target object / class
class Prop t pn where
type PropGT t pn -- ^ type of property when retrieved; () if write-only
type PropST t pn -- ^ type of property when set; () if read-only
setProp :: t -> pn -> PropST t pn -> IO ()
getProp :: t -> pn -> IO (PropGT t pn)
| @Event t en@ represents a .NET event with name @pn@ , on the target object / class
class Event t en where
type EventT t en -- ^ type of the event delegate
addEvent, removeEvent :: t -> en -> EventT t en -> IO ()
infix 0 :==, :=, :=>, :~, :+, :-, :+>, :->
-- | @AttrOp t@ represents a get/set operation on a .NET property, or an
add / remove operation on a .NET event , on a object / class of type
data AttrOp t
= forall p. (Prop t p) => p :== (PropST t p) -- assign value to property (monotyped)
| forall p v. (Prop t p,
ConvertsTo v (PropST t p) ~ TTrue,
Coercible v (PropST t p)) =>
p := v -- assign value to property (w/ implicit conversion)
| forall p v. (Prop t p,
ConvertsTo v (PropST t p) ~ TTrue,
Coercible v (PropST t p)) =>
assign result of IO action to property
| forall p. (Prop t p) => p :~ (PropGT t p -> PropST t p) -- update property
| forall e. (Event t e) => e :+ (EventT t e) -- add event listener
| forall e. (Event t e) => e :- (EventT t e) -- remove event listener
add result of IO action to event listeners
remove result of IO action from event listeners
| @'get ' t p@ retrieves the value of property @p@ on the target object / class
get :: Prop t p => t -> p -> IO (PropGT t p)
get = getProp
| @'set ' t ops@ applies the operations @ops@ to the object / class
set :: forall t. {-Target t =>-} t -> [AttrOp t] -> IO ()
set t ops = mapM_ applyOp ops
where applyOp :: AttrOp t -> IO ()
applyOp (p :== v) = setProp t p v
applyOp (p := v) = setProp t p (coerce v)
applyOp (p :=> v) = v >>= (\v -> setProp t p (coerce v))
applyOp (p :~ f) = getProp t p >>= setProp t p . f
applyOp (e :+ h) = h # addEvent t e
applyOp (e :- h) = h # removeEvent t e
applyOp (e :+> h) = h >>= addEvent t e
applyOp (e :-> h) = h >>= removeEvent t e
--
-- Note: a lexically scoped type variable is required in the definition of this
-- function. Both the 'forall t.' in the type signature for 'set' and the the
-- type signature for 'applyOp' are required to ensure that the 't' variable
-- used in 'set' is the same 't' as that used in 'applyOp'. Without the scoped
type variable , GHC is unable to deduce the desired Prop instance for the call
-- to 'setProp'.
--
-- | 'TupleToList t' is the type-level list representation of the tuple @t@
-- containing marshalable types. This allows arguments to .NET members to
-- be passed as tuples, which have a much neater syntax than lists.
type family TupleToList t
type instance TupleToList () = TNil
type instance TupleToList (Obj x) = Obj x ::: TNil
type instance TupleToList String = String ::: TNil
type instance TupleToList Int32 = Int32 ::: TNil
type instance TupleToList Bool = Bool ::: TNil
type instance TupleToList Double = Double ::: TNil
type instance TupleToList (a,b) = a ::: b ::: TNil
type instance TupleToList (a,b,c) = a ::: b ::: c ::: TNil
type instance TupleToList (a,b,c,d) = a ::: b ::: c ::: d ::: TNil
type instance TupleToList (a,b,c,d,e) = a ::: b ::: c ::: d ::: e ::: TNil
-- ...
-- | 'ListToTuple l' is the tuple type associated with the type-level list @l@.
type family ListToTuple t
type instance ListToTuple (Error x) = Error x -- propagate errors
type instance ListToTuple TNil = ()
type instance ListToTuple (a ::: TNil) = a
type instance ListToTuple (a ::: b ::: TNil) = (a,b)
type instance ListToTuple (a ::: b ::: c ::: TNil) = (a,b,c)
type instance ListToTuple (a ::: b ::: c ::: d ::: TNil) = (a,b,c,d)
type instance ListToTuple (a ::: b ::: c ::: d ::: e ::: TNil) = (a,b,c,d,e)
-- ...
--
Type reflection ( connects types to .NET types )
--
| The class ' ' provides access to the underlying .NET type that is
associated with a given type .
class Typeable t where
-- | Returns the .NET System.Type instance for values of type 't'.
-- The value of 't' is not evaluated by the function.
typeOf :: t -> Obj Type_
TODO : Perhaps rename to Type or SalsaType or Target ?
--
-- Value coercion
--
| @'Coercible ' from to@ provides a function ' coerce ' for implicitly converting
values of type @from@ to @to@. It applies only to high - level bridge types
-- (low-level conversions are handled by the marshaling system). It always
-- succeeds.
class Coercible from to where
| @'coerce ' v@ returns the value @v@ implicitly converted to the desired type .
coerce :: from -> to
instance Coercible Int32 Int32 where coerce = id
instance Coercible String String where coerce = id
instance Coercible Bool Bool where coerce = id
instance Coercible Double Double where coerce = id
instance Coercible Int32 Double where coerce = fromIntegral
instance Coercible (Obj f) (Obj t) where coerce = unsafeCoerce
instance Coercible String (Obj t) where
coerce s = unsafePerformIO (boxString s >>= unmarshal) -- boxing conversion
-- TODO: Ensure that this is sufficiently referentially transparent.
instance Coercible Int32 (Obj t) where
coerce i = unsafePerformIO (boxInt32 i >>= unmarshal) -- boxing conversion
-- TODO: Ensure that this is sufficiently referentially transparent.
-- Coercible tuples:
instance Coercible () () where coerce = id
instance (Coercible f0 t0, Coercible f1 t1) =>
Coercible (f0,f1) (t0,t1) where
coerce (f0,f1) = (coerce f0, coerce f1)
instance (Coercible f0 t0, Coercible f1 t1, Coercible f2 t2) =>
Coercible (f0,f1,f2) (t0,t1,t2) where
coerce (f0,f1,f2) = (coerce f0, coerce f1, coerce f2)
-- ...
Lift coerce into the IO monad
instance (Coercible f t) => Coercible f (IO t) where
coerce = return . coerce
cast v = coerce v
-- Checked implicit conversion:
convert :: (Coercible from to, ConvertsTo from to ~ TTrue) => from -> to
convert v = coerce v
-- TODO: Fix up the whole: coerce vs. cast vs. convert thing.
-- Work out what's required (i.e. implicit/explicit conversions,
-- checked or unchecked, etc.)
--
-- Marshaling support
--
For converting between types and the proxy types used for
-- communicating with .NET.
| The class ' Marshal ' allows high - level types to be converted into
low - level types when calling into FFI functions .
class Marshal from to where
marshal :: from -> (to -> IO a) -> IO a
instance Marshal String CWString where
marshal s = withCWString s
instance Marshal (Obj a) ObjectId where
| @'marshal ' o k@ provides access to the object identifier in @o@ within
the IO action @k@ , ensuring that the .NET object instance is kept alive
-- during the action (like 'withForeignPtr' except for .NET objects).
marshal (Obj oId fp) k = withForeignPtr fp (\_ -> k oId)
marshal ObjNull k = k 0
instance Marshal Int Int32 where
marshal v f = f (toEnum v)
instance Marshal () () where marshal = ( # )
instance Marshal String String where marshal = ( # )
instance Marshal Int32 Int32 where marshal = ( # )
instance Marshal Bool Bool where marshal = ( # )
instance Marshal Double Double where marshal = ( # )
-- Special case for Nullable<Boolean>
instance Marshal (Maybe Bool) ObjectId where
marshal Nothing k = k 0
marshal (Just True) k = k 1
marshal (Just False) k = k 2
| The class ' Unmarshal ' allows low - level types returned by FFI functions to
to be converted into high - level types .
class Unmarshal from to where
unmarshal :: from -> IO to
instance Unmarshal a () where
unmarshal _ = return ()
instance Unmarshal ObjectId (Obj a) where
| @'unmarshal ' o@ wraps the .NET object identified by @o@ as an Obj value .
-- 'releaseObject' is called with the object identifier when the Obj is
-- garbage collected.
unmarshal 0 = return ObjNull
unmarshal oId = newForeignPtr nullPtr (releaseObject oId) >>= return . Obj oId
instance Unmarshal CWString String where
unmarshal s = do
s' <- peekCWString s
localFree s -- Free the string allocated by the .NET marshaler (use
LocalFree for LPWSTRs and SysFreeString for BSTRs )
return s'
instance Unmarshal String String where unmarshal = return
instance Unmarshal Int32 Int32 where unmarshal = return
instance Unmarshal Bool Bool where unmarshal = return
instance Unmarshal Double Double where unmarshal = return
-- Special case for Nullable<Boolean>
instance Unmarshal ObjectId (Maybe Bool) where
unmarshal id | id == 1 = return $ Just True
| id == 2 = return $ Just False
| id == 0 = return $ Nothing
| otherwise = error "unmarshal: unexpected ObjectId for Maybe Bool"
TODO : Generate the functions below using ( this code is hideous ) .
Generic marshaling functions for instance methods
-- (marshal the target object and the tuple of arguments then call the given
-- function and unmarshal the result)
marshalMethod0i f o _ () = marshal o (\o' -> f o') >>= unmarshal
marshalMethod1i f o _ (a) = marshal o (\o' -> marshal a (\a' -> f o' a')) >>= unmarshal
marshalMethod2i f o _ (a,b) = marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> f o' a' b'))) >>= unmarshal
marshalMethod3i f o _ (a,b,c) = marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> f o' a' b' c')))) >>= unmarshal
marshalMethod4i f o _ (a,b,c,d) =
marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> marshal c (\c' ->
marshal d (\d' -> f o' a' b' c' d'))))) >>= unmarshal
marshalMethod5i f o _ (a1,a2,a3,a4,a5) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> f o' a1' a2' a3' a4' a5')))))) >>= unmarshal
marshalMethod6i f o _ (a1,a2,a3,a4,a5,a6) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' ->
f o' a1' a2' a3' a4' a5' a6'))))))) >>= unmarshal
marshalMethod7i f o _ (a1,a2,a3,a4,a5,a6,a7) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
f o' a1' a2' a3' a4' a5' a6' a7')))))))) >>= unmarshal
marshalMethod8i f o _ (a1,a2,a3,a4,a5,a6,a7,a8) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8'))))))))) >>= unmarshal
marshalMethod9i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9')))))))))) >>= unmarshal
marshalMethod10i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' -> marshal a10 (\a10' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9' a10'))))))))))) >>= unmarshal
marshalMethod11i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' -> marshal a10 (\a10' -> marshal a11 (\a11' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9' a10' a11')))))))))))) >>= unmarshal
-- ...
Generic marshaling functions for static methods
-- (marshal the tuple of arguments then call the given function and unmarshal
-- the result)
marshalMethod0s f _ _ () = f >>= unmarshal
marshalMethod1s f _ _ (a) = marshal a (\a' -> f a') >>= unmarshal
marshalMethod2s f _ _ (a,b) = marshal a (\a' -> marshal b (\b' -> f a' b')) >>= unmarshal
marshalMethod3s f _ _ (a,b,c) = marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> f a' b' c'))) >>= unmarshal
marshalMethod4s f _ _ (a,b,c,d) =
marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> marshal d (\d' ->
f a' b' c' d')))) >>= unmarshal
marshalMethod5s f _ _ (a,b,c,d,e) =
marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> marshal d (\d' ->
marshal e (\e' -> f a' b' c' d' e'))))) >>= unmarshal
marshalMethod6s f _ _ (a1,a2,a3,a4,a5,a6) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> f a1' a2' a3' a4' a5' a6')))))) >>= unmarshal
marshalMethod7s f _ _ (a1,a2,a3,a4,a5,a6,a7) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
f a1' a2' a3' a4' a5' a6' a7'))))))) >>= unmarshal
marshalMethod8s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
f a1' a2' a3' a4' a5' a6' a7' a8')))))))) >>= unmarshal
marshalMethod9s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9'))))))))) >>= unmarshal
marshalMethod10s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' -> marshal a10 (\a10' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9' a10')))))))))) >>= unmarshal
marshalMethod11s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' -> marshal a10 (\a10' -> marshal a11 (\a11' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9' a10' a11'))))))))))) >>= unmarshal
-- ...
-- Converts a function accepting and returning high-level types, to a function
-- that takes and returns low-level (base) types.
marshalFn0 f = do
o <- f
oId <- marshal o return
return oId
marshalFn1 f = \a1' -> unmarshal a1' >>= (\a1 -> f a1 >>= flip marshal return)
marshalFn2 f = \f1 f2 -> do
t1 <- unmarshal f1
t2 <- unmarshal f2
r <- f t1 t2
--
-- FIXME: We might have an issue here when 'r' is an object (Obj). After
-- marshal returns, it is possible that no references to 'r' remain in
-- Haskell. If the finalizer for the object is called before the
-- identifier is returned to .NET and looked up in the in-table, then
-- the lookup will fail. The following code forces this error:
--
-- marshal r return >>= (\rId -> performGC >> yield >> return rId)
--
marshal r return
marshalFn3 f = \a1' a2' a3' ->
unmarshal a1' >>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
(f a1 a2 a3 >>= flip marshal return))))
marshalFn4 f = \a1' a2' a3' a4' ->
unmarshal a1' >>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
unmarshal a4' >>= (\a4 -> (f a1 a2 a3 a4 >>= flip marshal return)))))
marshalFn5 f = \a1' a2' a3' a4' a5' -> do
a1 <- unmarshal a1'
a2 <- unmarshal a2'
a3 <- unmarshal a3'
a4 <- unmarshal a4'
a5 <- unmarshal a5'
v <- f a1 a2 a3 a4 a5
return $ marshal v
{-
>>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
unmarshal a4' >>= (\a4 -> unmarshal a5' >>= (\a5 ->
(f a1 a2 a3 a5 a5 >>= flip marshal return))))))
-}
-- ...
-- vim:set sw=4 ts=4 expandtab:
| null | https://raw.githubusercontent.com/unfoldr/Salsa/c28c54139353a22346c3e6b963e714e0ac4e398e/Foreign/Salsa/Core.hs | haskell | ---------------------------------------------------------------------------
|
Module : Foreign.Salsa.Core
Licence : BSD-style (see LICENSE)
---------------------------------------------------------------------------
Reverse function application
Binding to the target of a method invocation
Method invocation
| @'Candidates' t m@ is a type-level list of the members of a particular
method group, given the type @t@ and method name @m@. The overload
resolution algorithm chooses the appropriate member of the method group
(from this list) according to the argument types.
Calls 'ResolveMember', converting argument tuples to/from type-level lists,
and passing it the appropriate list of candidate signatures.
a constrainted result type for method invocations.
the tuple of arguments @args@.
Constructor invocation
given the tuple of arguments @args@, and returns an instance of the
constructed type.
Delegate support
^ High-level function type for the delegate implementation
| @'delegate' dt h@ calls the constructor for the delegate of type @t@, returning
Attribute system for .NET properties and events
^ type of property when retrieved; () if write-only
^ type of property when set; () if read-only
^ type of the event delegate
| @AttrOp t@ represents a get/set operation on a .NET property, or an
assign value to property (monotyped)
assign value to property (w/ implicit conversion)
update property
add event listener
remove event listener
Target t =>
Note: a lexically scoped type variable is required in the definition of this
function. Both the 'forall t.' in the type signature for 'set' and the the
type signature for 'applyOp' are required to ensure that the 't' variable
used in 'set' is the same 't' as that used in 'applyOp'. Without the scoped
to 'setProp'.
| 'TupleToList t' is the type-level list representation of the tuple @t@
containing marshalable types. This allows arguments to .NET members to
be passed as tuples, which have a much neater syntax than lists.
...
| 'ListToTuple l' is the tuple type associated with the type-level list @l@.
propagate errors
...
| Returns the .NET System.Type instance for values of type 't'.
The value of 't' is not evaluated by the function.
Value coercion
(low-level conversions are handled by the marshaling system). It always
succeeds.
boxing conversion
TODO: Ensure that this is sufficiently referentially transparent.
boxing conversion
TODO: Ensure that this is sufficiently referentially transparent.
Coercible tuples:
...
Checked implicit conversion:
TODO: Fix up the whole: coerce vs. cast vs. convert thing.
Work out what's required (i.e. implicit/explicit conversions,
checked or unchecked, etc.)
Marshaling support
communicating with .NET.
during the action (like 'withForeignPtr' except for .NET objects).
Special case for Nullable<Boolean>
'releaseObject' is called with the object identifier when the Obj is
garbage collected.
Free the string allocated by the .NET marshaler (use
Special case for Nullable<Boolean>
(marshal the target object and the tuple of arguments then call the given
function and unmarshal the result)
...
(marshal the tuple of arguments then call the given function and unmarshal
the result)
...
Converts a function accepting and returning high-level types, to a function
that takes and returns low-level (base) types.
FIXME: We might have an issue here when 'r' is an object (Obj). After
marshal returns, it is possible that no references to 'r' remain in
Haskell. If the finalizer for the object is called before the
identifier is returned to .NET and looked up in the in-table, then
the lookup will fail. The following code forces this error:
marshal r return >>= (\rId -> performGC >> yield >> return rId)
>>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
unmarshal a4' >>= (\a4 -> unmarshal a5' >>= (\a5 ->
(f a1 a2 a3 a5 a5 >>= flip marshal return))))))
...
vim:set sw=4 ts=4 expandtab: | # LANGUAGE GADTs , TypeFamilies , MultiParamTypeClasses , EmptyDataDecls #
# LANGUAGE ExistentialQuantification , FlexibleContexts , TypeOperators #
# LANGUAGE ScopedTypeVariables , TypeSynonymInstances , FlexibleInstances #
# LANGUAGE UndecidableInstances #
Copyright : ( c ) 2007 - 2008
module Foreign.Salsa.Core where
import Unsafe.Coerce (unsafeCoerce)
import System.IO.Unsafe ( unsafePerformIO )
import Foreign.C.String
import System.Win32
import Foreign hiding (new, newForeignPtr, unsafePerformIO)
import Foreign.Concurrent (newForeignPtr)
import Foreign.Salsa.Common
import Foreign.Salsa.TypePrelude
import Foreign.Salsa.Resolver
import Foreign.Salsa.CLR
x # f = f x
t >>=# m = t >>= ( # m )
null_ :: Obj Null
null_ = ObjNull
isNull :: Obj a -> Bool
isNull ObjNull = True
isNull _ = False
type family Candidates t m
type family Resolve t m args
type instance Resolve t m args = ListToTuple (ResolveMember (TupleToList args) (Candidates t m))
| ' ' provides type - based dispatch to method implementations , and
class Invoker t m args where
type Result t m args
rawInvoke :: t -> m -> args -> Result t m args
| @'invoke ' t m invokes the appropriate method @m@ in type @t@ given
invoke :: forall t m args args'.
(Resolve t m args ~ args',
Coercible args args',
Invoker t m args') =>
t -> m -> args -> Result t m args'
invoke t m args = rawInvoke t m (coerce args :: args')
data Ctor = Ctor deriving (Show, Eq)
| @'new ' t invokes the appropriate constructor for the type @t@
new t args = invoke t Ctor args
class Delegate dt where
a .NET delegate object of the same type whose implementation is the Haskell
function , @h@.
delegate :: dt -> (DelegateT dt) -> IO (Obj dt)
| @Prop t represents a .NET property with name @pn@ , on the target object / class
class Prop t pn where
setProp :: t -> pn -> PropST t pn -> IO ()
getProp :: t -> pn -> IO (PropGT t pn)
| @Event t en@ represents a .NET event with name @pn@ , on the target object / class
class Event t en where
addEvent, removeEvent :: t -> en -> EventT t en -> IO ()
infix 0 :==, :=, :=>, :~, :+, :-, :+>, :->
add / remove operation on a .NET event , on a object / class of type
data AttrOp t
| forall p v. (Prop t p,
ConvertsTo v (PropST t p) ~ TTrue,
Coercible v (PropST t p)) =>
| forall p v. (Prop t p,
ConvertsTo v (PropST t p) ~ TTrue,
Coercible v (PropST t p)) =>
assign result of IO action to property
add result of IO action to event listeners
remove result of IO action from event listeners
| @'get ' t p@ retrieves the value of property @p@ on the target object / class
get :: Prop t p => t -> p -> IO (PropGT t p)
get = getProp
| @'set ' t ops@ applies the operations @ops@ to the object / class
set t ops = mapM_ applyOp ops
where applyOp :: AttrOp t -> IO ()
applyOp (p :== v) = setProp t p v
applyOp (p := v) = setProp t p (coerce v)
applyOp (p :=> v) = v >>= (\v -> setProp t p (coerce v))
applyOp (p :~ f) = getProp t p >>= setProp t p . f
applyOp (e :+ h) = h # addEvent t e
applyOp (e :- h) = h # removeEvent t e
applyOp (e :+> h) = h >>= addEvent t e
applyOp (e :-> h) = h >>= removeEvent t e
type variable , GHC is unable to deduce the desired Prop instance for the call
type family TupleToList t
type instance TupleToList () = TNil
type instance TupleToList (Obj x) = Obj x ::: TNil
type instance TupleToList String = String ::: TNil
type instance TupleToList Int32 = Int32 ::: TNil
type instance TupleToList Bool = Bool ::: TNil
type instance TupleToList Double = Double ::: TNil
type instance TupleToList (a,b) = a ::: b ::: TNil
type instance TupleToList (a,b,c) = a ::: b ::: c ::: TNil
type instance TupleToList (a,b,c,d) = a ::: b ::: c ::: d ::: TNil
type instance TupleToList (a,b,c,d,e) = a ::: b ::: c ::: d ::: e ::: TNil
type family ListToTuple t
type instance ListToTuple TNil = ()
type instance ListToTuple (a ::: TNil) = a
type instance ListToTuple (a ::: b ::: TNil) = (a,b)
type instance ListToTuple (a ::: b ::: c ::: TNil) = (a,b,c)
type instance ListToTuple (a ::: b ::: c ::: d ::: TNil) = (a,b,c,d)
type instance ListToTuple (a ::: b ::: c ::: d ::: e ::: TNil) = (a,b,c,d,e)
Type reflection ( connects types to .NET types )
| The class ' ' provides access to the underlying .NET type that is
associated with a given type .
class Typeable t where
typeOf :: t -> Obj Type_
TODO : Perhaps rename to Type or SalsaType or Target ?
| @'Coercible ' from to@ provides a function ' coerce ' for implicitly converting
values of type @from@ to @to@. It applies only to high - level bridge types
class Coercible from to where
| @'coerce ' v@ returns the value @v@ implicitly converted to the desired type .
coerce :: from -> to
instance Coercible Int32 Int32 where coerce = id
instance Coercible String String where coerce = id
instance Coercible Bool Bool where coerce = id
instance Coercible Double Double where coerce = id
instance Coercible Int32 Double where coerce = fromIntegral
instance Coercible (Obj f) (Obj t) where coerce = unsafeCoerce
instance Coercible String (Obj t) where
instance Coercible Int32 (Obj t) where
instance Coercible () () where coerce = id
instance (Coercible f0 t0, Coercible f1 t1) =>
Coercible (f0,f1) (t0,t1) where
coerce (f0,f1) = (coerce f0, coerce f1)
instance (Coercible f0 t0, Coercible f1 t1, Coercible f2 t2) =>
Coercible (f0,f1,f2) (t0,t1,t2) where
coerce (f0,f1,f2) = (coerce f0, coerce f1, coerce f2)
Lift coerce into the IO monad
instance (Coercible f t) => Coercible f (IO t) where
coerce = return . coerce
cast v = coerce v
convert :: (Coercible from to, ConvertsTo from to ~ TTrue) => from -> to
convert v = coerce v
For converting between types and the proxy types used for
| The class ' Marshal ' allows high - level types to be converted into
low - level types when calling into FFI functions .
class Marshal from to where
marshal :: from -> (to -> IO a) -> IO a
instance Marshal String CWString where
marshal s = withCWString s
instance Marshal (Obj a) ObjectId where
| @'marshal ' o k@ provides access to the object identifier in @o@ within
the IO action @k@ , ensuring that the .NET object instance is kept alive
marshal (Obj oId fp) k = withForeignPtr fp (\_ -> k oId)
marshal ObjNull k = k 0
instance Marshal Int Int32 where
marshal v f = f (toEnum v)
instance Marshal () () where marshal = ( # )
instance Marshal String String where marshal = ( # )
instance Marshal Int32 Int32 where marshal = ( # )
instance Marshal Bool Bool where marshal = ( # )
instance Marshal Double Double where marshal = ( # )
instance Marshal (Maybe Bool) ObjectId where
marshal Nothing k = k 0
marshal (Just True) k = k 1
marshal (Just False) k = k 2
| The class ' Unmarshal ' allows low - level types returned by FFI functions to
to be converted into high - level types .
class Unmarshal from to where
unmarshal :: from -> IO to
instance Unmarshal a () where
unmarshal _ = return ()
instance Unmarshal ObjectId (Obj a) where
| @'unmarshal ' o@ wraps the .NET object identified by @o@ as an Obj value .
unmarshal 0 = return ObjNull
unmarshal oId = newForeignPtr nullPtr (releaseObject oId) >>= return . Obj oId
instance Unmarshal CWString String where
unmarshal s = do
s' <- peekCWString s
LocalFree for LPWSTRs and SysFreeString for BSTRs )
return s'
instance Unmarshal String String where unmarshal = return
instance Unmarshal Int32 Int32 where unmarshal = return
instance Unmarshal Bool Bool where unmarshal = return
instance Unmarshal Double Double where unmarshal = return
instance Unmarshal ObjectId (Maybe Bool) where
unmarshal id | id == 1 = return $ Just True
| id == 2 = return $ Just False
| id == 0 = return $ Nothing
| otherwise = error "unmarshal: unexpected ObjectId for Maybe Bool"
TODO : Generate the functions below using ( this code is hideous ) .
Generic marshaling functions for instance methods
marshalMethod0i f o _ () = marshal o (\o' -> f o') >>= unmarshal
marshalMethod1i f o _ (a) = marshal o (\o' -> marshal a (\a' -> f o' a')) >>= unmarshal
marshalMethod2i f o _ (a,b) = marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> f o' a' b'))) >>= unmarshal
marshalMethod3i f o _ (a,b,c) = marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> f o' a' b' c')))) >>= unmarshal
marshalMethod4i f o _ (a,b,c,d) =
marshal o (\o' -> marshal a (\a' -> marshal b (\b' -> marshal c (\c' ->
marshal d (\d' -> f o' a' b' c' d'))))) >>= unmarshal
marshalMethod5i f o _ (a1,a2,a3,a4,a5) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> f o' a1' a2' a3' a4' a5')))))) >>= unmarshal
marshalMethod6i f o _ (a1,a2,a3,a4,a5,a6) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' ->
f o' a1' a2' a3' a4' a5' a6'))))))) >>= unmarshal
marshalMethod7i f o _ (a1,a2,a3,a4,a5,a6,a7) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
f o' a1' a2' a3' a4' a5' a6' a7')))))))) >>= unmarshal
marshalMethod8i f o _ (a1,a2,a3,a4,a5,a6,a7,a8) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8'))))))))) >>= unmarshal
marshalMethod9i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9')))))))))) >>= unmarshal
marshalMethod10i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' -> marshal a10 (\a10' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9' a10'))))))))))) >>= unmarshal
marshalMethod11i f o _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) =
marshal o (\o' -> marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' ->
marshal a4 (\a4' -> marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
marshal a8 (\a8' -> marshal a9 (\a9' -> marshal a10 (\a10' -> marshal a11 (\a11' ->
f o' a1' a2' a3' a4' a5' a6' a7' a8' a9' a10' a11')))))))))))) >>= unmarshal
Generic marshaling functions for static methods
marshalMethod0s f _ _ () = f >>= unmarshal
marshalMethod1s f _ _ (a) = marshal a (\a' -> f a') >>= unmarshal
marshalMethod2s f _ _ (a,b) = marshal a (\a' -> marshal b (\b' -> f a' b')) >>= unmarshal
marshalMethod3s f _ _ (a,b,c) = marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> f a' b' c'))) >>= unmarshal
marshalMethod4s f _ _ (a,b,c,d) =
marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> marshal d (\d' ->
f a' b' c' d')))) >>= unmarshal
marshalMethod5s f _ _ (a,b,c,d,e) =
marshal a (\a' -> marshal b (\b' -> marshal c (\c' -> marshal d (\d' ->
marshal e (\e' -> f a' b' c' d' e'))))) >>= unmarshal
marshalMethod6s f _ _ (a1,a2,a3,a4,a5,a6) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> f a1' a2' a3' a4' a5' a6')))))) >>= unmarshal
marshalMethod7s f _ _ (a1,a2,a3,a4,a5,a6,a7) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' ->
f a1' a2' a3' a4' a5' a6' a7'))))))) >>= unmarshal
marshalMethod8s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
f a1' a2' a3' a4' a5' a6' a7' a8')))))))) >>= unmarshal
marshalMethod9s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9'))))))))) >>= unmarshal
marshalMethod10s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' -> marshal a10 (\a10' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9' a10')))))))))) >>= unmarshal
marshalMethod11s f _ _ (a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11) =
marshal a1 (\a1' -> marshal a2 (\a2' -> marshal a3 (\a3' -> marshal a4 (\a4' ->
marshal a5 (\a5' -> marshal a6 (\a6' -> marshal a7 (\a7' -> marshal a8 (\a8' ->
marshal a9 (\a9' -> marshal a10 (\a10' -> marshal a11 (\a11' ->
f a1' a2' a3' a4' a5' a6' a7' a8' a9' a10' a11'))))))))))) >>= unmarshal
marshalFn0 f = do
o <- f
oId <- marshal o return
return oId
marshalFn1 f = \a1' -> unmarshal a1' >>= (\a1 -> f a1 >>= flip marshal return)
marshalFn2 f = \f1 f2 -> do
t1 <- unmarshal f1
t2 <- unmarshal f2
r <- f t1 t2
marshal r return
marshalFn3 f = \a1' a2' a3' ->
unmarshal a1' >>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
(f a1 a2 a3 >>= flip marshal return))))
marshalFn4 f = \a1' a2' a3' a4' ->
unmarshal a1' >>= (\a1 -> unmarshal a2' >>= (\a2 -> unmarshal a3' >>= (\a3 ->
unmarshal a4' >>= (\a4 -> (f a1 a2 a3 a4 >>= flip marshal return)))))
marshalFn5 f = \a1' a2' a3' a4' a5' -> do
a1 <- unmarshal a1'
a2 <- unmarshal a2'
a3 <- unmarshal a3'
a4 <- unmarshal a4'
a5 <- unmarshal a5'
v <- f a1 a2 a3 a4 a5
return $ marshal v
|
9bb0d702ef379a1a88d821026c8f57f0a36e1f41fe6da3ad84c5e28a80ff49ea | ciderpunx/57-exercises-for-programmers | P25PwStrengthSpec.hs | module P25PwStrengthSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck ((==>))
import P25PwStrength hiding (main)
import Data.List (sort)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "passwordStrength" $ do
it "identifies a very weak password" $ do
passwordStrength "12345" `shouldBe` VeryWeak
it "identifies a weak password" $ do
passwordStrength "cats" `shouldBe` Weak
it "identifies an average password" $ do
passwordStrength "123cat" `shouldBe` Average
it "identifies a strong password with 1 number" $ do
passwordStrength "1ttffsse" `shouldBe` Strong
it "identifies a strong password with 2 numbers" $ do
passwordStrength "1ttf4fsse" `shouldBe` Strong
it "identifies a very strong password" $ do
passwordStrength "12ed12ed$$21" `shouldBe` VeryStrong
describe "hasLetters" $ do
it "is true when string contains letters" $ do
hasLetters "yes12" `shouldBe` True
it "is false when string does not contain letters" $ do
hasLetters "5612" `shouldBe` False
it "is false when string is empty" $ do
hasLetters "" `shouldBe` False
describe "manyLetters" $ do
it "is true when string contains > 1 letters" $ do
manyLetters "yes12" `shouldBe` True
it "is false when string contains 1 letter" $ do
manyLetters "56a12" `shouldBe` False
it "is false when string contains no letters" $ do
manyLetters "5612" `shouldBe` False
it "is false when string is empty" $ do
manyLetters "" `shouldBe` False
describe "allLetters" $ do
it "is true when string contains only letters" $ do
allLetters "yesItDoes" `shouldBe` True
it "is false when string contains no letters" $ do
allLetters "5612" `shouldBe` False
it "is false when string contains letters and non-letters" $ do
allLetters "ee5612" `shouldBe` False
it "is true when string is empty" $ do
allLetters "" `shouldBe` True
describe "hasNumbers" $ do
it "is true when string contains numbers" $ do
hasNumbers "yes12" `shouldBe` True
it "is false when string does not contain numbers" $ do
hasNumbers "piss" `shouldBe` False
it "is false when string is empty" $ do
hasNumbers "" `shouldBe` False
describe "manyNumbers" $ do
it "is true when string contains > 1 numbers" $ do
manyNumbers "yes12" `shouldBe` True
it "is false when string contains 1 number" $ do
manyNumbers "erk2q" `shouldBe` False
it "is false when string contains no numbers" $ do
manyNumbers "pokey" `shouldBe` False
it "is false when string is empty" $ do
manyNumbers "" `shouldBe` False
describe "allNumbers" $ do
it "is true when string contains only numbers" $ do
allNumbers "19898298" `shouldBe` True
it "is false when string contains no numbers" $ do
allNumbers "raga" `shouldBe` False
it "is false when string contains numbers and non-numbers" $ do
allNumbers "ee5612" `shouldBe` False
it "is true when string is empty" $ do
allNumbers "" `shouldBe` True
describe "hasSpecials" $ do
it "is true when string contains punctuation" $ do
hasSpecials "yes12'" `shouldBe` True
it "is true when string contains a symbol" $ do
hasSpecials "yes12♥" `shouldBe` True
it "is false when string does not contain punctuation" $ do
hasSpecials "piss" `shouldBe` False
it "is false when string is empty" $ do
hasSpecials "" `shouldBe` False
describe "manySpecials" $ do
it "is true when string contains > 1 punctiuation chars" $ do
manySpecials "yes12?'" `shouldBe` True
it "is false when string contains 1 punctuation char" $ do
manySpecials "erk-2q" `shouldBe` False
it "is true when string contains > 1 symbol" $ do
manySpecials "yes12♥♻" `shouldBe` True
it "is false when string contains 1 symbol" $ do
manySpecials "erk♥2q" `shouldBe` False
it "is false when string contains no punctuation chars or symbols" $ do
manySpecials "pokey" `shouldBe` False
it "is false when string is empty" $ do
manySpecials "" `shouldBe` False
describe "strongPasswordMinLength" $ do
it "should be equal to 8" $ do
strongPasswordMinLength `shouldBe` 8
| null | https://raw.githubusercontent.com/ciderpunx/57-exercises-for-programmers/25958ab80cc3edc29756d3bddd2d89815fd390bf/test/P25PwStrengthSpec.hs | haskell | module P25PwStrengthSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck ((==>))
import P25PwStrength hiding (main)
import Data.List (sort)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "passwordStrength" $ do
it "identifies a very weak password" $ do
passwordStrength "12345" `shouldBe` VeryWeak
it "identifies a weak password" $ do
passwordStrength "cats" `shouldBe` Weak
it "identifies an average password" $ do
passwordStrength "123cat" `shouldBe` Average
it "identifies a strong password with 1 number" $ do
passwordStrength "1ttffsse" `shouldBe` Strong
it "identifies a strong password with 2 numbers" $ do
passwordStrength "1ttf4fsse" `shouldBe` Strong
it "identifies a very strong password" $ do
passwordStrength "12ed12ed$$21" `shouldBe` VeryStrong
describe "hasLetters" $ do
it "is true when string contains letters" $ do
hasLetters "yes12" `shouldBe` True
it "is false when string does not contain letters" $ do
hasLetters "5612" `shouldBe` False
it "is false when string is empty" $ do
hasLetters "" `shouldBe` False
describe "manyLetters" $ do
it "is true when string contains > 1 letters" $ do
manyLetters "yes12" `shouldBe` True
it "is false when string contains 1 letter" $ do
manyLetters "56a12" `shouldBe` False
it "is false when string contains no letters" $ do
manyLetters "5612" `shouldBe` False
it "is false when string is empty" $ do
manyLetters "" `shouldBe` False
describe "allLetters" $ do
it "is true when string contains only letters" $ do
allLetters "yesItDoes" `shouldBe` True
it "is false when string contains no letters" $ do
allLetters "5612" `shouldBe` False
it "is false when string contains letters and non-letters" $ do
allLetters "ee5612" `shouldBe` False
it "is true when string is empty" $ do
allLetters "" `shouldBe` True
describe "hasNumbers" $ do
it "is true when string contains numbers" $ do
hasNumbers "yes12" `shouldBe` True
it "is false when string does not contain numbers" $ do
hasNumbers "piss" `shouldBe` False
it "is false when string is empty" $ do
hasNumbers "" `shouldBe` False
describe "manyNumbers" $ do
it "is true when string contains > 1 numbers" $ do
manyNumbers "yes12" `shouldBe` True
it "is false when string contains 1 number" $ do
manyNumbers "erk2q" `shouldBe` False
it "is false when string contains no numbers" $ do
manyNumbers "pokey" `shouldBe` False
it "is false when string is empty" $ do
manyNumbers "" `shouldBe` False
describe "allNumbers" $ do
it "is true when string contains only numbers" $ do
allNumbers "19898298" `shouldBe` True
it "is false when string contains no numbers" $ do
allNumbers "raga" `shouldBe` False
it "is false when string contains numbers and non-numbers" $ do
allNumbers "ee5612" `shouldBe` False
it "is true when string is empty" $ do
allNumbers "" `shouldBe` True
describe "hasSpecials" $ do
it "is true when string contains punctuation" $ do
hasSpecials "yes12'" `shouldBe` True
it "is true when string contains a symbol" $ do
hasSpecials "yes12♥" `shouldBe` True
it "is false when string does not contain punctuation" $ do
hasSpecials "piss" `shouldBe` False
it "is false when string is empty" $ do
hasSpecials "" `shouldBe` False
describe "manySpecials" $ do
it "is true when string contains > 1 punctiuation chars" $ do
manySpecials "yes12?'" `shouldBe` True
it "is false when string contains 1 punctuation char" $ do
manySpecials "erk-2q" `shouldBe` False
it "is true when string contains > 1 symbol" $ do
manySpecials "yes12♥♻" `shouldBe` True
it "is false when string contains 1 symbol" $ do
manySpecials "erk♥2q" `shouldBe` False
it "is false when string contains no punctuation chars or symbols" $ do
manySpecials "pokey" `shouldBe` False
it "is false when string is empty" $ do
manySpecials "" `shouldBe` False
describe "strongPasswordMinLength" $ do
it "should be equal to 8" $ do
strongPasswordMinLength `shouldBe` 8
|
|
ea74be674a55ba710d98b5aebe1e084ec492c43dc6409f3abb419c28668856f0 | outlyerapp/erl-vent | vent_app.erl | %%%-------------------------------------------------------------------
%% @doc vent public API
%% @end
%%%-------------------------------------------------------------------
-module(vent_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%%====================================================================
%% API
%%====================================================================
-spec start(application:start_type(), term()) -> {ok, pid()}.
start(_StartType, _StartArgs) ->
vent_sup:start_link().
-spec stop(term()) -> ok.
stop(_State) ->
ok.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/outlyerapp/erl-vent/9fd0d1352cccb4e525fbc3293f35806b3cf724d4/src/vent_app.erl | erlang | -------------------------------------------------------------------
@doc vent public API
@end
-------------------------------------------------------------------
Application callbacks
====================================================================
API
====================================================================
====================================================================
==================================================================== |
-module(vent_app).
-behaviour(application).
-export([start/2, stop/1]).
-spec start(application:start_type(), term()) -> {ok, pid()}.
start(_StartType, _StartArgs) ->
vent_sup:start_link().
-spec stop(term()) -> ok.
stop(_State) ->
ok.
Internal functions
|
1660f661a920f1be3c9c4ab011d7b3d3d416d4522894604723be3c0d9bde401b | bytekid/mkbtt | odg.ml | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 is free software : you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version .
*
* TTT2 is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* TTT2 is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with TTT2. If not, see </>.
*)
(*** OPENS ********************************************************************)
open Util;;
open Rewritingx;;
(*** MODULES ******************************************************************)
module C = Complexity;;
module F = Format;;
module G = Graph;;
module L = List;;
module M = Monad;;
module Map = Map.Partial (Term);;
module P = Problem;;
module R = Rule;;
module S = Substitution;;
(*** TYPES ********************************************************************)
type flags = {help : bool ref};;
type t = P.t * P.t;;
(*** GLOBALS ******************************************************************)
let code = "odg";;
let name = "ODG Processor";;
let keywords = ["dependency graph";"approximation";"termination"];;
let flags = {help = ref false};;
let comment =
"Remove all edges from l->r to l'->r' where ren(cap(r)) is not unifiable \
with l' (previous edg implementation)."
;;
let spec =
let spec = [
("--help",Arg.Set flags.help,"Prints information about flags.");
("-help",Arg.Set flags.help,"Prints information about flags.");
("-h",Arg.Set flags.help,"Prints information about flags.")]
in
Arg.alignx 80 spec
;;
let help = (comment,keywords,L.map Triple.drop_snd spec);;
(*** FUNCTIONS ****************************************************************)
let (>>=) = M.(>>=);;
let init _ = flags.help := false;;
(* Destructors *)
let get_idp = fst;;
let get_odp = snd;;
(* Processor *)
let is_arc trs ml mr (x,y) =
let s = R.lhs x and t = R.rhs x and u = R.lhs y and v = R.rhs y in
M.return (R.of_terms s (Map.find t mr)) >>= fun x' ->
M.return (R.of_terms (Map.find u ml) v) >>= fun y' ->
let s' = R.lhs x' and t' = R.rhs x' and u' = R.lhs y' in
let root = Option.the <.> Term.root <?> "left-hand side is a variable" in
if root t = root u then M.return (Elogic.are_unifiable t' u')
else M.return false
;;
let generate trs ml mr ns =
M.foldl (fun g n -> M.foldl (fun ms m ->
M.lift (fun c -> if c then m::ms else ms) (is_arc trs ml mr (n,m))) [] ns >>=
(M.return <.> flip (G.add n) g)) G.empty ns
;;
let filter_edges trs ml mr g =
G.fold (fun n ms m -> m >>= fun g ->
let add m ms c = M.return (if c then m::ms else ms) in
M.foldl (fun ms m -> is_arc trs ml mr (n,m) >>= add m ms) [] ms >>=
(M.return <.> flip (G.add n) g)) g (M.return G.empty)
;;
let solve fs p =
let configurate s = F.printf "%s@\n%!" s; flags.help := true in
(try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s);
if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0);
if P.is_dp p then
let trs = P.get_trs p and dps = P.get_dps p and g = P.get_dg p in
let (ls,rs) = match g with
| P.Complete -> (Trs.lhs dps,Trs.rhs dps)
| P.Partial g -> (L.map R.lhs (G.in_nodes g),L.map R.rhs (G.out_nodes g))
in
let ls = L.unique_hash ls and rs = L.unique_hash rs in
(* configurate computation *)
let modify_lhs = fun l _ -> M.return l in
let modify_rhs = Trs.tcap in
let add f m t = f t >>= (M.return <.> flip (Map.add t) m) in
M.foldl (add (flip modify_rhs trs)) Map.empty rs >>= fun mr ->
M.foldl (add (flip modify_lhs (Trs.invert trs))) Map.empty ls >>= fun ml ->
(* compute arcs *)
match g with
| P.Complete ->
generate trs ml mr (Trs.to_list dps) >>= fun g ->
let n = Int.square (Trs.size dps) and m = G.size_edges g in
M.return (if m < n then Some (p,P.set_dg (P.Partial g) p) else None)
| P.Partial g ->
let g = G.restrict (Trs.to_list dps) g in
filter_edges trs ml mr g >>= fun h ->
let n = G.size_edges g and m = G.size_edges h in
M.return (if m < n then Some (p,P.set_dg (P.Partial h) p) else None)
else M.return None
;;
(* Complexity Bounds *)
let complexity c _ = C.mul c C.other;;
(* Compare Functions *)
let equal p q = P.equal (get_idp p) (get_idp q);;
(* Printers *)
let fprintf fs fmt p =
F.fprintf fmt "@[<1>%s:@\n" name;
P.fprintfm ~g:true fmt (get_odp p) >>= fun _ ->
F.fprintf fmt "@\n"; L.hd fs fmt >>= fun _ ->
M.return (F.fprintf fmt "@]")
;;
let fprintfx fs fmt p =
F.fprintf fmt "@{<dependencyGraph>";
P.fprintfx ~g:true fmt (get_odp p) >>= fun _ ->
L.hd fs fmt >>= fun _ -> M.return (F.fprintf fmt "@}")
;;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/processors/src/termination/dg/odg.ml | ocaml | ** OPENS *******************************************************************
** MODULES *****************************************************************
** TYPES *******************************************************************
** GLOBALS *****************************************************************
** FUNCTIONS ***************************************************************
Destructors
Processor
configurate computation
compute arcs
Complexity Bounds
Compare Functions
Printers | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 is free software : you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version .
*
* TTT2 is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* TTT2 is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with TTT2. If not, see </>.
*)
open Util;;
open Rewritingx;;
module C = Complexity;;
module F = Format;;
module G = Graph;;
module L = List;;
module M = Monad;;
module Map = Map.Partial (Term);;
module P = Problem;;
module R = Rule;;
module S = Substitution;;
type flags = {help : bool ref};;
type t = P.t * P.t;;
let code = "odg";;
let name = "ODG Processor";;
let keywords = ["dependency graph";"approximation";"termination"];;
let flags = {help = ref false};;
let comment =
"Remove all edges from l->r to l'->r' where ren(cap(r)) is not unifiable \
with l' (previous edg implementation)."
;;
let spec =
let spec = [
("--help",Arg.Set flags.help,"Prints information about flags.");
("-help",Arg.Set flags.help,"Prints information about flags.");
("-h",Arg.Set flags.help,"Prints information about flags.")]
in
Arg.alignx 80 spec
;;
let help = (comment,keywords,L.map Triple.drop_snd spec);;
let (>>=) = M.(>>=);;
let init _ = flags.help := false;;
let get_idp = fst;;
let get_odp = snd;;
let is_arc trs ml mr (x,y) =
let s = R.lhs x and t = R.rhs x and u = R.lhs y and v = R.rhs y in
M.return (R.of_terms s (Map.find t mr)) >>= fun x' ->
M.return (R.of_terms (Map.find u ml) v) >>= fun y' ->
let s' = R.lhs x' and t' = R.rhs x' and u' = R.lhs y' in
let root = Option.the <.> Term.root <?> "left-hand side is a variable" in
if root t = root u then M.return (Elogic.are_unifiable t' u')
else M.return false
;;
let generate trs ml mr ns =
M.foldl (fun g n -> M.foldl (fun ms m ->
M.lift (fun c -> if c then m::ms else ms) (is_arc trs ml mr (n,m))) [] ns >>=
(M.return <.> flip (G.add n) g)) G.empty ns
;;
let filter_edges trs ml mr g =
G.fold (fun n ms m -> m >>= fun g ->
let add m ms c = M.return (if c then m::ms else ms) in
M.foldl (fun ms m -> is_arc trs ml mr (n,m) >>= add m ms) [] ms >>=
(M.return <.> flip (G.add n) g)) g (M.return G.empty)
;;
let solve fs p =
let configurate s = F.printf "%s@\n%!" s; flags.help := true in
(try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s);
if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0);
if P.is_dp p then
let trs = P.get_trs p and dps = P.get_dps p and g = P.get_dg p in
let (ls,rs) = match g with
| P.Complete -> (Trs.lhs dps,Trs.rhs dps)
| P.Partial g -> (L.map R.lhs (G.in_nodes g),L.map R.rhs (G.out_nodes g))
in
let ls = L.unique_hash ls and rs = L.unique_hash rs in
let modify_lhs = fun l _ -> M.return l in
let modify_rhs = Trs.tcap in
let add f m t = f t >>= (M.return <.> flip (Map.add t) m) in
M.foldl (add (flip modify_rhs trs)) Map.empty rs >>= fun mr ->
M.foldl (add (flip modify_lhs (Trs.invert trs))) Map.empty ls >>= fun ml ->
match g with
| P.Complete ->
generate trs ml mr (Trs.to_list dps) >>= fun g ->
let n = Int.square (Trs.size dps) and m = G.size_edges g in
M.return (if m < n then Some (p,P.set_dg (P.Partial g) p) else None)
| P.Partial g ->
let g = G.restrict (Trs.to_list dps) g in
filter_edges trs ml mr g >>= fun h ->
let n = G.size_edges g and m = G.size_edges h in
M.return (if m < n then Some (p,P.set_dg (P.Partial h) p) else None)
else M.return None
;;
let complexity c _ = C.mul c C.other;;
let equal p q = P.equal (get_idp p) (get_idp q);;
let fprintf fs fmt p =
F.fprintf fmt "@[<1>%s:@\n" name;
P.fprintfm ~g:true fmt (get_odp p) >>= fun _ ->
F.fprintf fmt "@\n"; L.hd fs fmt >>= fun _ ->
M.return (F.fprintf fmt "@]")
;;
let fprintfx fs fmt p =
F.fprintf fmt "@{<dependencyGraph>";
P.fprintfx ~g:true fmt (get_odp p) >>= fun _ ->
L.hd fs fmt >>= fun _ -> M.return (F.fprintf fmt "@}")
;;
|
42a2831bc4eee454b47fb80f8d2597e51a4ad3bdc7bda93593cfa028faea4567 | TrustInSoft/tis-kernel | cil.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(****************************************************************************)
(* *)
Copyright ( C ) 2001 - 2003
< >
(* Scott McPeak <> *)
< >
< >
(* All rights reserved. *)
(* *)
(* Redistribution and use in source and binary forms, with or without *)
(* modification, are permitted provided that the following conditions *)
(* are met: *)
(* *)
1 . Redistributions of source code must retain the above copyright
(* notice, this list of conditions and the following disclaimer. *)
(* *)
2 . Redistributions in binary form must reproduce the above copyright
(* notice, this list of conditions and the following disclaimer in the *)
(* documentation and/or other materials provided with the distribution. *)
(* *)
3 . The names of the contributors may not be used to endorse or
(* promote products derived from this software without specific prior *)
(* written permission. *)
(* *)
(* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *)
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
(* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *)
(* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *)
COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
(* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *)
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN *)
(* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *)
(* POSSIBILITY OF SUCH DAMAGE. *)
(* *)
File modified by CEA ( Commissariat à l'énergie atomique et aux
(* énergies alternatives) *)
and INRIA ( Institut National de Recherche en Informatique
(* et Automatique). *)
(****************************************************************************)
(** CIL main API.
CIL original API documentation is available as
an html version at .
@plugin development guide *)
open Cil_types
open Cil_datatype
(* ************************************************************************* *)
* { 2 Builtins management }
(* ************************************************************************* *)
(** This module associates the name of a built-in function that might be used
during elaboration with the corresponding varinfo. This is done when
parsing ${TIS_KERNEL_SHARE}/libc/__fc_builtins.h, which is always performed
before processing the actual list of files provided on the command line (see
{!File.init_from_c_files}). Actual list of such built-ins is managed in
{!Cabs2cil}. *)
module Frama_c_builtins:
State_builder.Hashtbl with type key = string and type data = Cil_types.varinfo
val is_builtin: Cil_types.varinfo -> bool
(** @return true if the given variable refers to a Frama-C builtin.
@since Fluorine-20130401 *)
val is_unused_builtin: Cil_types.varinfo -> bool
(** @return true if the given variable refers to a Frama-C builtin that
is not used in the current program. Plugins may (and in fact should)
hide this builtin from their outputs *)
val is_special_builtin: string -> bool
(** @return [true] if the given name refers to a special built-in function.
A special built-in function can have any number of arguments. It is up to
the plug-ins to know what to do with it.
@since Boron-20100401-dev *)
(** register a new special built-in function *)
val add_special_builtin: string -> unit
(** register a new family of special built-in functions.
@since Carbon-20101201
*)
val add_special_builtin_family: (string -> bool) -> unit
(** initialize the C built-ins. Should be called once per project, after the
machine has been set. *)
val init_builtins: unit -> unit
(** Call this function to perform some initialization, and only after you have
set [Cil.msvcMode]. [initLogicBuiltins] is the function to call to init
logic builtins. The [Machdeps] argument is a description of the hardware
platform and of the compiler used. *)
val initCIL: initLogicBuiltins:(unit -> unit) -> Cil_types.mach -> unit
(* ************************************************************************* *)
* { 2 Customization }
(* ************************************************************************* *)
type theMachine = private
{ mutable useLogicalOperators: bool;
* Whether to use the logical operands LAnd and LOr . By default , do not
use them because they are unlike other expressions and do not
evaluate both of their operands
use them because they are unlike other expressions and do not
evaluate both of their operands *)
mutable theMachine: mach;
mutable lowerConstants: bool; (** Do lower constants (default true) *)
mutable insertImplicitCasts: bool;
(** Do insert implicit casts (default true) *)
mutable stringLiteralType: typ;
mutable upointKind: ikind
(** An unsigned integer type that fits pointers. *);
mutable upointType: typ;
mutable wcharKind: ikind; (** An integer type that fits wchar_t. *)
mutable wcharType: typ;
mutable ptrdiffKind: ikind; (** An integer type that fits ptrdiff_t. *)
mutable ptrdiffType: typ;
mutable typeOfSizeOf: typ;
(** An integer type that is the type of sizeof. *)
mutable kindOfSizeOf: ikind;
* The integer kind of { ! } .
}
val theMachine : theMachine
(** Current machine description *)
val selfMachine: State.t
val selfMachine_is_computed: ?project:Project.project -> unit -> bool
(** whether current project has set its machine description. *)
val msvcMode: unit -> bool
val gccMode: unit -> bool
(* ************************************************************************* *)
* { 2 Values for manipulating globals }
(* ************************************************************************* *)
* Make an empty function from an existing global varinfo .
@since
@since Nitrogen-20111001 *)
val emptyFunctionFromVI: varinfo -> fundec
(** Make an empty function *)
val emptyFunction: string -> fundec
(** Update the formals of a [fundec] and make sure that the function type
has the same information. Will copy the name as well into the type. *)
val setFormals: fundec -> varinfo list -> unit
(** Takes as input a function type (or a typename on it) and return its
return type. *)
val getReturnType: typ -> typ
* Change the return type of the function passed as 1st argument to be
the type passed as 2nd argument .
the type passed as 2nd argument. *)
val setReturnTypeVI: varinfo -> typ -> unit
val setReturnType: fundec -> typ -> unit
* Set the types of arguments and results as given by the function type
* passed as the second argument . Will not copy the names from the function
* type to the formals
* passed as the second argument. Will not copy the names from the function
* type to the formals *)
val setFunctionType: fundec -> typ -> unit
(** Set the type of the function and make formal arguments for them *)
val setFunctionTypeMakeFormals: fundec -> typ -> unit
* Update the smaxid after you have populated with locals and formals
* ( unless you constructed those using { ! } or
* { ! } .
* (unless you constructed those using {!Cil.makeLocalVar} or
* {!Cil.makeTempVar}. *)
val setMaxId: fundec -> unit
* Strip const attribute from the type . This is useful for
any type used as the type of a local variable which may be assigned .
Note that the type attributes are mutated in place .
@since
any type used as the type of a local variable which may be assigned.
Note that the type attributes are mutated in place.
@since Nitrogen-20111001
*)
val stripConstLocalType : Cil_types.typ -> Cil_types.typ
val selfFormalsDecl: State.t
(** state of the table associating formals to each prototype. *)
val makeFormalsVarDecl: (string * typ * attributes) -> varinfo
(** creates a new varinfo for the parameter of a prototype. *)
* Update the formals of a function declaration from its identifier and its
type . For a function definition , use { ! } .
Do nothing if the type is not a function type or if the list of
argument is empty .
type. For a function definition, use {!Cil.setFormals}.
Do nothing if the type is not a function type or if the list of
argument is empty.
*)
val setFormalsDecl: varinfo -> typ -> unit
(** remove a binding from the table.
@since Oxygen-20120901 *)
val removeFormalsDecl: varinfo -> unit
* replace to formals of a function declaration with the given
list of varinfo .
list of varinfo.
*)
val unsafeSetFormalsDecl: varinfo -> varinfo list -> unit
(** iters the given function on declared prototypes.
@since Oxygen-20120901
*)
val iterFormalsDecl: (varinfo -> varinfo list -> unit) -> unit
(** Get the formals of a function declaration registered with
{!Cil.setFormalsDecl}.
@raise Not_found if the function is not registered (this is in particular
the case for prototypes with an empty list of arguments.
See {!Cil.setFormalsDecl})
*)
val getFormalsDecl: varinfo -> varinfo list
(** A dummy file *)
val dummyFile: file
* Get the global initializer and create one if it does not already exist .
When it creates a global initializer it attempts to place a call to it in
the main function named by the optional argument ( default " main " ) .
@deprecated using this function is incorrect since it modifies the
current AST ( see Plug - in Development Guide , Section " Using Projects " ) .
When it creates a global initializer it attempts to place a call to it in
the main function named by the optional argument (default "main").
@deprecated using this function is incorrect since it modifies the
current AST (see Plug-in Development Guide, Section "Using Projects"). *)
val getGlobInit: ?main_name:string -> file -> fundec
(** Iterate over all globals, including the global initializer *)
val iterGlobals: file -> (global -> unit) -> unit
(** Fold over all globals, including the global initializer *)
val foldGlobals: file -> ('a -> global -> 'a) -> 'a -> 'a
(** Map over all globals, including the global initializer and change things
in place *)
val mapGlobals: file -> (global -> global) -> unit
(** Find a function or function prototype with the given name in the file.
* If it does not exist, create a prototype with the given type, and return
* the new varinfo. This is useful when you need to call a libc function
* whose prototype may or may not already exist in the file.
*
* Because the new prototype is added to the start of the file, you shouldn't
* refer to any struct or union types in the function type.*)
val findOrCreateFunc: file -> string -> typ -> varinfo
module Sid: sig
val next: unit -> int
end
module Eid: sig
val next: unit -> int
end
(** creates an expression with a fresh id *)
val new_exp: loc:location -> exp_node -> exp
* performs a deep copy of an expression ( especially , avoid eid sharing ) .
@since
@since Nitrogen-20111001
*)
val copy_exp: exp -> exp
* creates an expression with a dummy i d.
Use with caution , { i i.e. } not on expressions that may be put in the AST .
Use with caution, {i i.e.} not on expressions that may be put in the AST.
*)
val dummy_exp: exp_node -> exp
(** Return [true] on case and default labels, [false] otherwise. *)
val is_case_label: label -> bool
(** CIL keeps the types at the beginning of the file and the variables at the
* end of the file. This function will take a global and add it to the
* corresponding stack. Its operation is actually more complicated because if
* the global declares a type that contains references to variables (e.g. in
* sizeof in an array length) then it will also add declarations for the
* variables to the types stack *)
val pushGlobal: global -> types: global list ref
-> variables: global list ref -> unit
(** An empty statement. Used in pretty printing *)
val invalidStmt: stmt
* A list of the built - in functions for the current compiler ( GCC or
* MSVC , depending on [ ! msvcMode ] ) . Maps the name to the
* result and argument types , and whether it is vararg .
* Initialized by { ! Cil.initCIL }
*
* This map replaces [ gccBuiltins ] and [ msvcBuiltins ] in previous
* versions of CIL .
* MSVC, depending on [!msvcMode]). Maps the name to the
* result and argument types, and whether it is vararg.
* Initialized by {!Cil.initCIL}
*
* This map replaces [gccBuiltins] and [msvcBuiltins] in previous
* versions of CIL.*)
module Builtin_functions :
State_builder.Hashtbl with type key = string
and type data = typ * typ list * bool
(** This is used as the location of the prototypes of builtin functions. *)
val builtinLoc: location
* Returns a location that ranges over the two locations in arguments .
val range_loc: location -> location -> location
(* ************************************************************************* *)
* { 2 Values for manipulating initializers }
(* ************************************************************************* *)
* Make a initializer for zero - ing a data type
val makeZeroInit: loc:location -> typ -> init
* Fold over the list of initializers in a Compound ( not also the nested
* ones ) . [ doinit ] is called on every present initializer , even if it is of
* compound type . The parameters of [ doinit ] are : the offset in the compound
* ( this is [ Field(f , ) ] or [ Index(i , ) ] ) , the initializer
* value , expected type of the initializer value , accumulator . In the case of
* arrays there might be missing zero - initializers at the end of the list .
* These are scanned only if [ implicit ] is true . This is much like
* [ List.fold_left ] except we also pass the type of the initializer .
* This is a good way to use it to scan even nested initializers :
{ v
let rec myInit ( lv : lval ) ( i : init ) ( acc : ' a ) : ' a =
match i with
SingleInit e - > ... do something with lv and e and acc ...
| CompoundInit ( ct , ) - >
foldLeftCompound ~implicit : false
~doinit:(fun off ' i ' t ' acc - >
myInit ( addOffsetLval lv off ' ) i ' acc )
~ct : ct
~initl : initl
~acc : acc
v }
* ones). [doinit] is called on every present initializer, even if it is of
* compound type. The parameters of [doinit] are: the offset in the compound
* (this is [Field(f,NoOffset)] or [Index(i,NoOffset)]), the initializer
* value, expected type of the initializer value, accumulator. In the case of
* arrays there might be missing zero-initializers at the end of the list.
* These are scanned only if [implicit] is true. This is much like
* [List.fold_left] except we also pass the type of the initializer.
* This is a good way to use it to scan even nested initializers :
{v
let rec myInit (lv: lval) (i: init) (acc: 'a) : 'a =
match i with
SingleInit e -> ... do something with lv and e and acc ...
| CompoundInit (ct, initl) ->
foldLeftCompound ~implicit:false
~doinit:(fun off' i' t' acc ->
myInit (addOffsetLval lv off') i' acc)
~ct:ct
~initl:initl
~acc:acc
v}
*)
val foldLeftCompound:
implicit:bool ->
doinit: (offset -> init -> typ -> 'a -> 'a) ->
ct: typ ->
initl: (offset * init) list ->
acc: 'a -> 'a
(* ************************************************************************* *)
* { 2 Values for manipulating types }
(* ************************************************************************* *)
(** void *)
val voidType: typ
(** is the given type "void"? *)
val isVoidType: typ -> bool
(** is the given type "void *"? *)
val isVoidPtrType: typ -> bool
(** int *)
val intType: typ
(** unsigned int *)
val uintType: typ
(** long *)
val longType: typ
(** long long *)
val longLongType: typ
(** unsigned long *)
val ulongType: typ
(** unsigned long long *)
val ulongLongType: typ
* Any unsigned integer type of size 16 bits .
It is equivalent to the ISO C uint16_t type but without using the
corresponding header .
Shall not be called if not such type exists in the current architecture .
@since
It is equivalent to the ISO C uint16_t type but without using the
corresponding header.
Shall not be called if not such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint16_t: unit -> typ
* Any unsigned integer type of size 32 bits .
It is equivalent to the ISO C uint32_t type but without using the
corresponding header .
Shall not be called if not such type exists in the current architecture .
@since
It is equivalent to the ISO C uint32_t type but without using the
corresponding header.
Shall not be called if not such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint32_t: unit -> typ
* Any unsigned integer type of size 64 bits .
It is equivalent to the ISO C uint64_t type but without using the
corresponding header .
Shall not be called if no such type exists in the current architecture .
@since
It is equivalent to the ISO C uint64_t type but without using the
corresponding header.
Shall not be called if no such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint64_t: unit -> typ
* Any signed integer type of size 128 bits .
It is equivalent to the GCC _ _ int128 type .
Shall not be called if no such type exists in the current architecture .
@since TIS - Kernel 1.30
It is equivalent to the GCC __int128 type.
Shall not be called if no such type exists in the current architecture.
@since TIS-Kernel 1.30
*)
val int128_t: unit -> typ
(** char *)
val charType: typ
val scharType: typ
val ucharType: typ
(** char * *)
val charPtrType: typ
val scharPtrType: typ
val ucharPtrType: typ
(** char const * *)
val charConstPtrType: typ
(** void * *)
val voidPtrType: typ
(** void const * *)
val voidConstPtrType: typ
(** int * *)
val intPtrType: typ
(** unsigned int * *)
val uintPtrType: typ
(** float *)
val floatType: typ
(** double *)
val doubleType: typ
(** long double *)
val longDoubleType: typ
(** @return true if and only if the given type is a signed integer type. *)
val isSignedInteger: typ -> bool
(** @return true if and only if the given type is an unsigned integer type.
@since Oxygen-20120901 *)
val isUnsignedInteger: typ -> bool
* Creates a ( potentially recursive ) composite type . The arguments are :
* ( 1 ) a boolean indicating whether it is a struct or a union , ( 2 ) the name
* ( always non - empty ) , ( 3 ) a function that when given a representation of the
* structure type constructs the type of the fields recursive type ( the first
* argument is only useful when some fields need to refer to the type of the
* structure itself ) , and ( 4 ) a list of attributes to be associated with the
* composite type . The resulting compinfo has the field " cdefined " only if
* the list of fields is non - empty .
* (1) a boolean indicating whether it is a struct or a union, (2) the name
* (always non-empty), (3) a function that when given a representation of the
* structure type constructs the type of the fields recursive type (the first
* argument is only useful when some fields need to refer to the type of the
* structure itself), and (4) a list of attributes to be associated with the
* composite type. The resulting compinfo has the field "cdefined" only if
* the list of fields is non-empty. *)
val mkCompInfo: bool -> (* whether it is a struct or a union *)
string -> (* name of the composite type; cannot be empty *)
?norig:string -> (* original name of the composite type, empty when anonymous *)
(compinfo ->
(string * typ * int option * attributes * location) list) ->
(* a function that when given a forward
representation of the structure type constructs the type of
the fields. The function can ignore this argument if not
constructing a recursive type. *)
attributes -> compinfo
* Makes a shallow copy of a { ! Cil_types.compinfo } changing the name . It also
copies the fields , and makes sure that the copied field points back to the
copied .
If [ fresh ] is [ true ] ( the default ) , it will also give a fresh i d to the
copy .
copies the fields, and makes sure that the copied field points back to the
copied compinfo.
If [fresh] is [true] (the default), it will also give a fresh id to the
copy.
*)
val copyCompInfo: ?fresh:bool -> compinfo -> string -> compinfo
(** This is a constant used as the name of an unnamed bitfield. These fields
do not participate in initialization and their name is not printed. *)
val missingFieldName: string
(** Get the full name of a comp *)
val compFullName: compinfo -> string
(** Returns true if this is a complete type.
This means that sizeof(t) makes sense.
Incomplete types are not yet defined structures and empty arrays.
Expects a valid type as argument.
@param allowZeroSizeArrays defaults to [false]. When [true], arrays of
size 0 (a gcc extension) are considered as complete
*)
val isCompleteType: ?allowZeroSizeArrays:bool -> typ -> bool
(** Returns true iff this is a structure type with a flexible array member or a
union type containing, possibly recursively, a member of such a structure
type. *)
val isNestedStructWithFlexibleArrayMemberType : typ -> bool
(** Unroll a type until it exposes a non
* [TNamed]. Will collect all attributes appearing in [TNamed]!!! *)
val unrollType: typ -> typ
* Unroll all the TNamed in a type ( even under type constructors such as
* [ TPtr ] , [ TFun ] or [ TArray ] . Does not unroll the types of fields in [ TComp ]
* types . Will collect all attributes
* [TPtr], [TFun] or [TArray]. Does not unroll the types of fields in [TComp]
* types. Will collect all attributes *)
val unrollTypeDeep: typ -> typ
(** Separate out the storage-modifier name attributes *)
val separateStorageModifiers: attribute list -> attribute list * attribute list
* returns the type of the result of an arithmetic operator applied to
values of the corresponding input types .
@since ( moved from Cabs2cil )
values of the corresponding input types.
@since Nitrogen-20111001 (moved from Cabs2cil)
*)
val arithmeticConversion : Cil_types.typ -> Cil_types.typ -> Cil_types.typ
* performs the usual integral promotions mentioned in C reference manual .
@since ( moved from Cabs2cil )
@since Nitrogen-20111001 (moved from Cabs2cil)
*)
val integralPromotion : Cil_types.typ -> Cil_types.typ
(** True if the argument is a character type (i.e. plain, signed or unsigned) *)
val isCharType: typ -> bool
(** True if the argument is a short type (i.e. signed or unsigned) *)
val isShortType: typ -> bool
(** True if the argument is a pointer to a character type
(i.e. plain, signed or unsigned) *)
val isCharPtrType: typ -> bool
(** True if the argument is an array of a character type
(i.e. plain, signed or unsigned) *)
val isCharArrayType: typ -> bool
(** True if the argument is an integral type (i.e. integer or enum) *)
val isIntegralType: typ -> bool
(** True if the argument is an integral or pointer type. *)
val isIntegralOrPointerType: typ -> bool
* True if the argument is an integral type ( i.e. integer or enum ) , either
C or mathematical one
C or mathematical one *)
val isLogicIntegralType: logic_type -> bool
(** True if the argument is a floating point type *)
val isFloatingType: typ -> bool
(** True if the argument is a floating point type *)
val isLogicFloatType: logic_type -> bool
(** True if the argument is a C floating point type or logic 'real' type *)
val isLogicRealOrFloatType: logic_type -> bool
(** True if the argument is the logic 'real' type *)
val isLogicRealType: logic_type -> bool
(** True if the argument is an arithmetic type (i.e. integer, enum or
floating point *)
val isArithmeticType: typ -> bool
(** True if the argument is an arithmetic or pointer type (i.e. integer, enum,
floating point or pointer *)
val isArithmeticOrPointerType: typ -> bool
* True if the argument is a logic arithmetic type ( i.e. integer , enum or
floating point , either C or mathematical one
floating point, either C or mathematical one *)
val isLogicArithmeticType: logic_type -> bool
(** True if the argument is a pointer type *)
val isPointerType: typ -> bool
(** True if the argument is the type for reified C types *)
val isTypeTagType: logic_type -> bool
(** True if the argument is a function type. *)
val isFunctionType: typ -> bool
* True if the argument denotes the type of ... in a variadic function .
@since moved from cabs2cil
@since Nitrogen-20111001 moved from cabs2cil *)
val isVariadicListType: typ -> bool
(** Obtain the argument list ([] if None) *)
val argsToList:
(string * typ * attributes) list option -> (string * typ * attributes) list
(** True if the argument is an array type *)
val isArrayType: typ -> bool
(** True if the argument is an array type of known size. *)
val isKnownSizeArrayType: typ -> bool
(** True if the argument is an array type of unknown size. *)
val isUnspecifiedSizeArrayType: typ -> bool
(** True if the argument is a struct or union type *)
val isStructOrUnionType: typ -> bool
(** Raised when {!Cil.lenOfArray} fails either because the length is [None]
* or because it is a non-constant expression *)
exception LenOfArray
* Call to compute the array length as present in the array type , to an
* integer . Raises { ! . LenOfArray } if not able to compute the length , such
* as when there is no length or the length is not a constant .
* integer. Raises {!Cil.LenOfArray} if not able to compute the length, such
* as when there is no length or the length is not a constant. *)
val lenOfArray: exp option -> int
val lenOfArray64: exp option -> Integer.t
* Return a named fieldinfo in , or raise Not_found
val getCompField: compinfo -> string -> fieldinfo
(** A datatype to be used in conjunction with [existsType] *)
type existsAction =
ExistsTrue (** We have found it *)
| ExistsFalse (** Stop processing this branch *)
| ExistsMaybe (** This node is not what we are
* looking for but maybe its
* successors are *)
* Scans a type by applying the function on all elements .
When the function returns ExistsTrue , the scan stops with
true . When the function returns ExistsFalse then the current branch is not
scanned anymore . Care is taken to
apply the function only once on each composite type , thus avoiding
circularity . When the function returns ExistsMaybe then the types that
construct the current type are scanned ( e.g. the base type for TPtr and
TArray , the type of fields for a TComp , etc ) .
When the function returns ExistsTrue, the scan stops with
true. When the function returns ExistsFalse then the current branch is not
scanned anymore. Care is taken to
apply the function only once on each composite type, thus avoiding
circularity. When the function returns ExistsMaybe then the types that
construct the current type are scanned (e.g. the base type for TPtr and
TArray, the type of fields for a TComp, etc). *)
val existsType: (typ -> existsAction) -> typ -> bool
(** Given a function type split it into return type,
* arguments, is_vararg and attributes. An error is raised if the type is not
* a function type *)
val splitFunctionType:
typ -> typ * (string * typ * attributes) list option * bool * attributes
(** Same as {!Cil.splitFunctionType} but takes a varinfo. Prints a nicer
* error message if the varinfo is not for a function *)
val splitFunctionTypeVI:
varinfo ->
typ * (string * typ * attributes) list option * bool * attributes
* Return a call instruction corresponding to the the function call related
to the GCC cleanup attribute .
The semantics is : this instruction has to be executed as soon as the
variable escapes its block scope . This semantics is desugared
during Oneret .
If there is no such attribute or a non GCC machdep is selected ,
it returns None .
The returned statement is not is the AST .
For any given varinfo the same physical statement will
be returned . It needs to be copied before it is inserted in
the AST .
to the GCC cleanup attribute.
The semantics is: this instruction has to be executed as soon as the
variable escapes its block scope. This semantics is desugared
during Oneret.
If there is no such attribute or a non GCC machdep is selected,
it returns None.
The returned statement is not is the AST.
For any given varinfo the same physical statement will
be returned. It needs to be copied before it is inserted in
the AST.
*)
val get_cleanup_stmt: varinfo -> stmt option
(*********************************************************)
* LVALUES
* Make a varinfo . Use this ( rarely ) to make a raw varinfo . Use other
functions to make locals ( { ! } or { ! Cil.makeFormalVar } or
{ ! } ) and globals ( { ! Cil.makeGlobalVar } ) . Note that this
function will assign a new identifier .
The [ temp ] argument defaults to [ false ] , and corresponds to the
[ vtemp ] field in type { ! Cil_types.varinfo } .
The [ source ] argument defaults to [ true ] , and corresponds to the field
[ vsource ] .
The first unnmamed argument specifies whether the varinfo is for a global and
the second is for formals .
functions to make locals ({!Cil.makeLocalVar} or {!Cil.makeFormalVar} or
{!Cil.makeTempVar}) and globals ({!Cil.makeGlobalVar}). Note that this
function will assign a new identifier.
The [temp] argument defaults to [false], and corresponds to the
[vtemp] field in type {!Cil_types.varinfo}.
The [source] argument defaults to [true], and corresponds to the field
[vsource] .
The first unnmamed argument specifies whether the varinfo is for a global and
the second is for formals. *)
val makeVarinfo:
?source:bool -> ?temp:bool -> bool -> bool -> string -> typ -> varinfo
* Make a formal variable for a function declaration . Insert it in both the
sformals and the type of the function . You can optionally specify where to
insert this one . If where = " ^ " then it is inserted first . If where = " $ "
then it is inserted last . Otherwise where must be the name of a formal
after which to insert this . By default it is inserted at the end .
sformals and the type of the function. You can optionally specify where to
insert this one. If where = "^" then it is inserted first. If where = "$"
then it is inserted last. Otherwise where must be the name of a formal
after which to insert this. By default it is inserted at the end.
*)
val makeFormalVar: fundec -> ?where:string -> string -> typ -> varinfo
* Make a local variable and add it to a function 's slocals and to the given
block ( only if insert = true , which is the default ) .
Make sure you know what you are doing if you set [ insert = false ] .
[ temp ] is passed to { ! Cil.makeVarinfo } .
The variable is attached to the toplevel block if [ scope ] is not specified .
@since This function will strip const attributes
of its type in place in order for local variable to be assignable at
least once .
block (only if insert = true, which is the default).
Make sure you know what you are doing if you set [insert=false].
[temp] is passed to {!Cil.makeVarinfo}.
The variable is attached to the toplevel block if [scope] is not specified.
@since Nitrogen-20111001 This function will strip const attributes
of its type in place in order for local variable to be assignable at
least once.
*)
val makeLocalVar:
fundec -> ?scope:block -> ?temp:bool -> ?insert:bool
-> string -> typ -> varinfo
(** Make a temporary variable and add it to a function's slocals. The name of
the temporary variable will be generated based on the given name hint so
that to avoid conflicts with other locals.
Optionally, you can give the variable a description of its contents.
Temporary variables are always considered as generated variables.
If [insert] is true (the default), the variable will be inserted
among other locals of the function. The value for [insert] should
only be changed if you are completely sure this is not useful.
*)
val makeTempVar: fundec -> ?insert:bool -> ?name:string -> ?descr:string ->
?descrpure:bool -> typ -> varinfo
(** Make a global variable. Your responsibility to make sure that the name
is unique. [source] defaults to [true]. [temp] defaults to [false].*)
val makeGlobalVar: ?source:bool -> ?temp:bool -> string -> typ -> varinfo
(** Make a shallow copy of a [varinfo] and assign a new identifier.
If the original varinfo has an associated logic var, it is copied too and
associated to the copied varinfo
*)
val copyVarinfo: varinfo -> string -> varinfo
(** Changes the type of a varinfo and of its associated logic var if any.
@since Neon-20140301 *)
val update_var_type: varinfo -> typ -> unit
* Is an lvalue a bitfield ?
val isBitfield: lval -> bool
(** Returns the last offset in the chain. *)
val lastOffset: offset -> offset
(** Add an offset at the end of an lvalue. Make sure the type of the lvalue
* and the offset are compatible. *)
val addOffsetLval: offset -> lval -> lval
(** [addOffset o1 o2] adds [o1] to the end of [o2]. *)
val addOffset: offset -> offset -> offset
* Remove ONE offset from the end of an lvalue . Returns the lvalue with the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffsetLval: lval -> lval * offset
* Remove ONE offset from the end of an offset sequence . Returns the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffset: offset -> offset * offset
(** Compute the type of an lvalue *)
val typeOfLval: lval -> typ
(** Compute the type of an lhost (with no offset) *)
val typeOfLhost: lhost -> typ
(** Equivalent to [typeOfLval] for terms. *)
val typeOfTermLval: term_lval -> logic_type
(** Compute the type of an offset from a base type *)
val typeOffset: typ -> offset -> typ
(** Equivalent to [typeOffset] for terms. *)
val typeTermOffset: logic_type -> term_offset -> logic_type
(** Compute the type of an initializer *)
val typeOfInit: init -> typ
(* ************************************************************************* *)
* { 2 Values for manipulating expressions }
(* ************************************************************************* *)
Construct integer constants
* 0
val zero: loc:Location.t -> exp
* 1
val one: loc:Location.t -> exp
(** -1 *)
val mone: loc:Location.t -> exp
(** Construct an integer of a given kind without literal representation.
Truncate the integer if [kind] is given, and the integer does not fit
inside the type. The integer can have an optional literal representation
[repr].
@raise Not_representable if no ikind is provided and the integer is not
representable. *)
val kinteger64: loc:location -> ?repr:string -> ?kind:ikind -> Integer.t -> exp
* Construct an integer of a given kind . Converts the integer to int64 and
* then uses kinteger64 . This might truncate the value if you use a kind
* that can not represent the given integer . This can only happen for one of
* the or Short kinds
* then uses kinteger64. This might truncate the value if you use a kind
* that cannot represent the given integer. This can only happen for one of
* the Char or Short kinds *)
val kinteger: loc:location -> ikind -> int -> exp
* Construct an integer of kind IInt . You can use this always since the
OCaml integers are 31 bits and are guaranteed to fit in an IInt
OCaml integers are 31 bits and are guaranteed to fit in an IInt *)
val integer: loc:location -> int -> exp
(** Constructs a floating point constant.
@since Oxygen-20120901
*)
val kfloat: loc:location -> fkind -> float -> exp
(** True if the given expression is a (possibly cast'ed)
character or an integer constant *)
val isInteger: exp -> Integer.t option
(** True if the expression is a compile-time constant *)
val isConstant: exp -> bool
(** True if the expression is a compile-time integer constant *)
val isIntegerConstant: exp -> bool
(** True if the given offset contains only field nanmes or constant indices. *)
val isConstantOffset: offset -> bool
* True if the given expression is a ( possibly cast'ed ) integer or character
constant with value zero
constant with value zero *)
val isZero: exp -> bool
(** True if the term is the constant 0 *)
val isLogicZero: term -> bool
(** True if the given term is [\null] or a constant null pointer*)
val isLogicNull: term -> bool
(** gives the value of a wide char literal. *)
val reduce_multichar: Cil_types.typ -> int64 list -> int64
(** gives the value of a char literal. *)
val interpret_character_constant:
int64 list -> Cil_types.constant * Cil_types.typ
* Given the character c in a ( CChr c ) , sign - extend it to 32 bits .
( This is the official way of interpreting character constants , according to
ISO C 6.4.4.4.10 , which says that character constants are chars cast to ints )
Returns CInt64(sign - extened c , IInt , None )
(This is the official way of interpreting character constants, according to
ISO C 6.4.4.4.10, which says that character constants are chars cast to ints)
Returns CInt64(sign-extened c, IInt, None) *)
val charConstToInt: char -> Integer.t
val charConstToIntConstant: char -> constant
* Do constant folding on an expression . If the first argument is [ true ] then
will also compute compiler - dependent expressions such as sizeof .
See also { ! Cil.constFoldVisitor } , which will run constFold on all
expressions in a given AST node .
will also compute compiler-dependent expressions such as sizeof.
See also {!Cil.constFoldVisitor}, which will run constFold on all
expressions in a given AST node. *)
val constFold: bool -> exp -> exp
(** Do constant folding on the given expression, just as [constFold] would. The
resulting integer value, if the const-folding was complete, is returned.
The [machdep] optional parameter, which is set to [true] by default,
forces the simplification of architecture-dependent expressions. *)
val constFoldToInt: ?machdep:bool -> exp -> Integer.t option
(** Do constant folding on an term at toplevel only.
This uses compiler-dependent informations and will
remove all sizeof and alignof. *)
val constFoldTermNodeAtTop: term_node -> term_node
* Do constant folding on an term .
If the first argument is true then
will also compute compiler - dependent expressions such as [ sizeof ]
and [ alignof ] .
If the first argument is true then
will also compute compiler-dependent expressions such as [sizeof]
and [alignof]. *)
val constFoldTerm: bool -> term -> term
* Do constant folding on a binary operation . The bulk of the work done by
[ constFold ] is done here . If the second argument is true then
will also compute compiler - dependent expressions such as [ sizeof ] .
[constFold] is done here. If the second argument is true then
will also compute compiler-dependent expressions such as [sizeof]. *)
val constFoldBinOp: loc:location -> bool -> binop -> exp -> exp -> typ -> exp
* [ true ] if the two constant are equal .
@since
@since Nitrogen-20111001
*)
val compareConstant: constant -> constant -> bool
(** Increment an expression. Can be arithmetic or pointer type *)
val increm: exp -> int -> exp
(** Increment an expression. Can be arithmetic or pointer type *)
val increm64: exp -> Integer.t -> exp
(** Makes an lvalue out of a given variable *)
val var: varinfo -> lval
* Creates an expr representing the variable .
@since
@since Nitrogen-20111001
*)
val evar: ?loc:location -> varinfo -> exp
* Make an . Given an lvalue of type T will give back an expression of
type ptr(T ) . It optimizes somewhat expressions like " & v " and " & v[0 ] "
type ptr(T). It optimizes somewhat expressions like "& v" and "& v[0]" *)
val mkAddrOf: loc:location -> lval -> exp
(** Creates an expression corresponding to "&v".
@since Oxygen-20120901 *)
val mkAddrOfVi: varinfo -> exp
(** Like mkAddrOf except if the type of lval is an array then it uses
StartOf. This is the right operation for getting a pointer to the start
of the storage denoted by lval. *)
val mkAddrOrStartOf: loc:location -> lval -> exp
* Make a Mem , while optimizing . The type of the addr must be
TPtr(t ) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply . You must do the conversion yourself using
StartOf
TPtr(t) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply. You must do the conversion yourself using
StartOf *)
val mkMem: addr:exp -> off:offset -> lval
* makes a binary operation and performs const folding . Inserts
casts between arithmetic types as needed , or between pointer
types , but do not attempt to cast pointer to int or
vice - versa . Use appropriate binop ( PlusPI & friends ) for that .
casts between arithmetic types as needed, or between pointer
types, but do not attempt to cast pointer to int or
vice-versa. Use appropriate binop (PlusPI & friends) for that. *)
val mkBinOp: loc:location -> binop -> exp -> exp -> exp
(** Equivalent to [mkMem] for terms. *)
val mkTermMem: addr:term -> off:term_offset -> term_lval
(** Make an expression that is a string constant (of pointer type) *)
val mkString: loc:location -> string -> exp
* [ true ] if both types are not equivalent .
if [ force ] is [ true ] , returns [ true ] whenever both types are not equal
( modulo typedefs ) . If [ force ] is [ false ] ( the default ) , other equivalences
are considered , in particular between an enum and its representative
integer type .
added [ force ] argument
if [force] is [true], returns [true] whenever both types are not equal
(modulo typedefs). If [force] is [false] (the default), other equivalences
are considered, in particular between an enum and its representative
integer type.
@modify Fluorine-20130401 added [force] argument
*)
val need_cast: ?force:bool -> typ -> typ -> bool
(** Construct a cast when having the old type of the expression. If the new
type is the same as the old type, then no cast is added, unless [force]
is [true] (default is [false])
@modify Fluorine-20130401 add [force] argument
*)
val mkCastT: ?force:bool -> e:exp -> oldt:typ -> newt:typ -> exp
* Like { ! Cil.mkCastT } but uses to get [ oldt ]
val mkCast: ?force:bool -> e:exp -> newt:typ -> exp
(** Equivalent to [stripCasts] for terms. *)
val stripTermCasts: term -> term
* Removes casts from this expression , but ignores casts within
other expression constructs . So we delete the ( A ) and ( B ) casts from
" ( A)(B)(x + ( C)y ) " , but leave the ( C ) cast .
other expression constructs. So we delete the (A) and (B) casts from
"(A)(B)(x + (C)y)", but leave the (C) cast. *)
val stripCasts: exp -> exp
* Same as stripCasts but only remove casts to void and stop at the first
non - void cast .
non-void cast. *)
val stripCastsToVoid: exp -> exp
(** Removes info wrappers and return underlying expression *)
val stripInfo: exp -> exp
(** Removes casts and info wrappers and return underlying expression *)
val stripCastsAndInfo: exp -> exp
(** Removes casts and info wrappers,except last info wrapper, and return
underlying expression *)
val stripCastsButLastInfo: exp -> exp
(** Extracts term information in an expression information *)
val exp_info_of_term: term -> exp_info
(** Constructs a term from a term node and an expression information *)
val term_of_exp_info: location -> term_node -> exp_info -> term
(** Map some function on underlying expression if Info or else on expression *)
val map_under_info: (exp -> exp) -> exp -> exp
(** Apply some function on underlying expression if Info or else on expression *)
val app_under_info: (exp -> unit) -> exp -> unit
val typeOf: exp -> typ
(** Compute the type of an expression. *)
val typeOf_pointed : typ -> typ
(** Returns the type pointed by the given type. Asserts it is a pointer type. *)
val typeOf_array_elem : typ -> typ
(** Returns the type of the array elements of the given type.
Asserts it is an array type. *)
val is_fully_arithmetic: typ -> bool
(** Returns [true] whenever the type contains only arithmetic types *)
* Convert a string representing a C integer literal to an expression .
Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL .
Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL.
*)
val parseInt: string -> Integer.t
val parseIntExp: loc:location -> string -> exp
val parseIntLogic: loc:location -> string -> term
* Convert a string representing a C integer literal to an expression .
Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL
Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL *)
val appears_in_expr: varinfo -> exp -> bool
(** @return true if the given variable appears in the expression. *)
(**********************************************)
* { 3 Values for manipulating statements }
(**********************************************)
* Construct a statement , given its kind . Initialize the [ sid ] field to -1
if [ valid_sid ] is false ( the default ) ,
or to a valid if [ valid_sid ] is true ,
and [ labels ] , [ succs ] and [ ] to the empty list
if [valid_sid] is false (the default),
or to a valid sid if [valid_sid] is true,
and [labels], [succs] and [preds] to the empty list *)
val mkStmt: ?ghost:bool -> ?valid_sid:bool -> stmtkind -> stmt
make the [ new_stmtkind ] changing the CFG relatively to [ ref_stmt ]
val mkStmtCfg: before:bool -> new_stmtkind:stmtkind -> ref_stmt:stmt -> stmt
(** Construct a block with no attributes, given a list of statements *)
val mkBlock: stmt list -> block
(** Construct a block with no attributes, given a list of statements and
wrap it into the Cfg. *)
val mkStmtCfgBlock: stmt list -> stmt
* Construct a statement consisting of just one instruction
See { ! Cil.mkStmt } for the signification of the optional args .
See {!Cil.mkStmt} for the signification of the optional args.
*)
val mkStmtOneInstr: ?ghost:bool -> ?valid_sid:bool -> instr -> stmt
* Try to compress statements so as to get maximal basic blocks .
* use this instead of List.@ because you get fewer basic blocks
* use this instead of List.@ because you get fewer basic blocks *)
: stmt list - > stmt list
* Returns an empty statement ( of kind [ Instr ] ) . See [ mkStmt ] for [ ghost ] and
[ valid_sid ] arguments .
adds the [ valid_sid ] optional argument .
[valid_sid] arguments.
@modify Neon-20130301 adds the [valid_sid] optional argument. *)
val mkEmptyStmt: ?ghost:bool -> ?valid_sid:bool -> ?loc:location -> unit -> stmt
(** A instr to serve as a placeholder *)
val dummyInstr: instr
(** A statement consisting of just [dummyInstr].
@plugin development guide *)
val dummyStmt: stmt
(** Make a while loop. Can contain Break or Continue *)
val mkWhile: guard:exp -> body:stmt list -> stmt list
* Make a for loop for(i = start ; i < past ; i + = incr ) \ { ... \ } . The body
can contain Break but not Continue . Can be used with i a pointer
or an integer . Start and done must have the same type but incr
must be an integer
can contain Break but not Continue. Can be used with i a pointer
or an integer. Start and done must have the same type but incr
must be an integer *)
val mkForIncr: iter:varinfo -> first:exp -> stopat:exp -> incr:exp
-> body:stmt list -> stmt list
(** Make a for loop for(start; guard; next) \{ ... \}. The body can
contain Break but not Continue !!! *)
val mkFor: start:stmt list -> guard:exp -> next: stmt list ->
body: stmt list -> stmt list
(** creates a block with empty attributes from an unspecified sequence. *)
val block_from_unspecified_sequence:
(stmt * lval list * lval list * lval list * stmt ref list) list -> block
(** Create an expression equivalent to the condition to enter a case branch. *)
val mkCase_condition:
loc:Cil_types.location ->
case:Cil_types.case -> switch:Cil_types.exp -> Cil_types.exp
(* ************************************************************************* *)
* { 2 Values for manipulating attributes }
(* ************************************************************************* *)
(** Various classes of attributes *)
type attributeClass =
AttrName of bool
* Attribute of a name . If argument is true and we are on MSVC then
the attribute is printed using _ _ as part of the storage
specifier
the attribute is printed using __declspec as part of the storage
specifier *)
| AttrType (** Attribute of a type *)
val registerAttribute: string -> attributeClass -> unit
(** Add a new attribute with a specified class *)
val removeAttribute: string -> unit
(** Remove an attribute previously registered. *)
val attributeClass: string -> attributeClass
(** Return the class of an attribute. *)
(** Partition the attributes into classes:name attributes and type attributes *)
val partitionAttributes: default:attributeClass ->
AttrType
* Add an attribute . Maintains the attributes in sorted order of the second
argument
argument *)
val addAttribute: attribute -> attributes -> attributes
* Add a list of attributes . Maintains the attributes in sorted order . The
second argument must be sorted , but not necessarily the first
second argument must be sorted, but not necessarily the first *)
val addAttributes: attribute list -> attributes -> attributes
(** Remove all attributes with the given name. Maintains the attributes in
sorted order. *)
val dropAttribute: string -> attributes -> attributes
(** Remove all attributes with names appearing in the string list.
* Maintains the attributes in sorted order *)
val dropAttributes: string list -> attributes -> attributes
* Remove attributes whose name appears in the first argument that are
present anywhere in the fully expanded version of the type .
@since Oxygen-20120901
present anywhere in the fully expanded version of the type.
@since Oxygen-20120901
*)
val typeDeepDropAttributes: string list -> typ -> typ
(** Remove any attribute appearing somewhere in the fully expanded
version of the type.
@since Oxygen-20120901
*)
val typeDeepDropAllAttributes: typ -> typ
(** Retains attributes with the given name *)
val filterAttributes: string -> attributes -> attributes
(** True if the named attribute appears in the attribute list. The list of
attributes must be sorted. *)
val hasAttribute: string -> attributes -> bool
(** returns the complete name for an attribute annotation. *)
val mkAttrAnnot: string -> string
(** Returns the name of an attribute. *)
val attributeName: attribute -> string
(** Returns the list of parameters associated to an attribute. The list is empty if there
is no such attribute or it has no parameters at all. *)
val findAttribute: string -> attribute list -> attrparam list list
(** Returns all the attributes contained in a type. This requires a traversal
of the type structure, in case of composite, enumeration and named types *)
val typeAttrs: typ -> attribute list
(** Returns the attributes of a type. *)
val typeAttr: typ -> attribute list
(** Sets the attributes of the type to the given list. Previous attributes
are discarded. *)
val setTypeAttrs: typ -> attributes -> typ
(** Add some attributes to a type *)
val typeAddAttributes: attribute list -> typ -> typ
(** Remove all attributes with the given names from a type. Note that this
does not remove attributes from typedef and tag definitions, just from
their uses (unfolding the type definition when needed).
It only removes attributes of topmost type, i.e. does not
recurse under pointers, arrays, ...
*)
val typeRemoveAttributes: string list -> typ -> typ
(** same as above, but remove any existing attribute from the type.
@since Magnesium-20151001
*)
val typeRemoveAllAttributes: typ -> typ
val typeHasAttribute: string -> typ -> bool
* Does the type have the given attribute . Does
not recurse through pointer types , nor inside function prototypes .
@since Sodium-20150201
not recurse through pointer types, nor inside function prototypes.
@since Sodium-20150201 *)
val typeHasQualifier: string -> typ -> bool
* Does the type have the given qualifier . Handles the case of arrays , for
which the qualifiers are actually carried by the type of the elements .
It is always correct to call this function instead of { ! typeHasAttribute } .
For l - values , both functions return the same results , as l - values can not
have array type .
@since Sodium-20150201
which the qualifiers are actually carried by the type of the elements.
It is always correct to call this function instead of {!typeHasAttribute}.
For l-values, both functions return the same results, as l-values cannot
have array type.
@since Sodium-20150201 *)
val typeHasAttributeDeep: string -> typ -> bool
* Does the type or one of its subtypes have the given attribute . Does
not recurse through pointer types , nor inside function prototypes .
@since Oxygen-20120901
not recurse through pointer types, nor inside function prototypes.
@since Oxygen-20120901 *)
* Remove all attributes relative to const , volatile and restrict attributes
@since
@since Nitrogen-20111001
*)
val type_remove_qualifier_attributes: typ -> typ
*
remove also qualifiers under Ptr and Arrays
@since Sodium-20150201
remove also qualifiers under Ptr and Arrays
@since Sodium-20150201
*)
val type_remove_qualifier_attributes_deep: typ -> typ
(** Remove all attributes relative to const, volatile and restrict attributes
when building a C cast
@since Oxygen-20120901
*)
val type_remove_attributes_for_c_cast: typ -> typ
(** Remove all attributes relative to const, volatile and restrict attributes
when building a logic cast
@since Oxygen-20120901
*)
val type_remove_attributes_for_logic_type: typ -> typ
* retains attributes corresponding to type qualifiers ( 6.7.3 )
val filter_qualifier_attributes: attributes -> attributes
(** given some attributes on an array type, split them into those that belong
to the type of the elements of the array (currently, qualifiers such as
const and volatile), and those that must remain on the array, in that
order
@since Oxygen-20120901 *)
val splitArrayAttributes: attributes -> attributes * attributes
val bitfield_attribute_name: string
* Name of the attribute that is automatically inserted ( with an [ AINT size ]
argument when querying the type of a field that is a bitfield
argument when querying the type of a field that is a bitfield *)
(** Convert an expression into an attrparam, if possible. Otherwise raise
NotAnAttrParam with the offending subexpression *)
val expToAttrParam: exp -> attrparam
exception NotAnAttrParam of exp
(* ************************************************************************* *)
* { 2 The visitor }
(* ************************************************************************* *)
(** Different visiting actions. 'a will be instantiated with [exp], [instr],
etc.
@plugin development guide *)
type 'a visitAction =
| SkipChildren (** Do not visit the children. Return the node as it is.
@plugin development guide *)
| DoChildren (** Continue with the children of this node. Rebuild the node on
return if any of the children changes (use == test).
@plugin development guide *)
| DoChildrenPost of ('a -> 'a)
(** visit the children, and apply the given function to the result.
@plugin development guide *)
| JustCopy (** visit the children, but only to make the necessary copies
(only useful for copy visitor).
@plugin development guide *)
| JustCopyPost of ('a -> 'a)
(** same as JustCopy + applies the given function to the result.
@plugin development guide*)
| ChangeTo of 'a (** Replace the expression with the given one.
@plugin development guide *)
| ChangeToPost of 'a * ('a -> 'a)
(** applies the expression to the function and gives back the result.
Useful to insert some actions in an inheritance chain.
@plugin development guide *)
| ChangeDoChildrenPost of 'a * ('a -> 'a)
* First consider that the entire exp is replaced by the first parameter . Then
continue with the children . On return rebuild the node if any of the
children has changed and then apply the function on the node .
@plugin development guide
continue with the children. On return rebuild the node if any of the
children has changed and then apply the function on the node.
@plugin development guide *)
val mk_behavior :
?name:string ->
?assumes:('a list) ->
?requires:('a list) ->
?post_cond:((termination_kind * 'a) list) ->
?assigns:('b Cil_types.assigns ) ->
?allocation:('b Cil_types.allocation option) ->
?extended:((string * int * 'a list) list) ->
unit ->
('a, 'b) Cil_types.behavior
(** @since Carbon-20101201
returns a dummy behavior with the default name [Cil.default_behavior_name].
invariant: [b_assumes] must always be
empty for behavior named [Cil.default_behavior_name] *)
val default_behavior_name: string
(** @since Carbon-20101201 *)
val is_default_behavior: ('a,'b) behavior -> bool
val find_default_behavior: funspec -> funbehavior option
(** @since Carbon-20101201 *)
val find_default_requires: ('a, 'b) behavior list -> 'a list
(** @since Carbon-20101201 *)
(* ************************************************************************* *)
* { 2 Visitor mechanism }
(* ************************************************************************* *)
* { 3 Visitor behavior }
type visitor_behavior
* How the visitor should behave in front of mutable fields : in
place modification or copy of the structure . This type is abstract .
Use one of the two values below in your classes .
@plugin development guide
place modification or copy of the structure. This type is abstract.
Use one of the two values below in your classes.
@plugin development guide *)
val inplace_visit: unit -> visitor_behavior
* In - place modification . Behavior of the original cil visitor .
@plugin development guide
@plugin development guide *)
val copy_visit: Project.t -> visitor_behavior
* Makes fresh copies of the mutable structures .
- preserves sharing for varinfo .
- makes fresh copy of varinfo only for declarations . Variables that are
only used in the visited AST are thus still shared with the original
AST . This allows for instance to copy a function with its
formals and local variables , and to keep the references to other
globals in the function 's body .
@plugin development guide
- preserves sharing for varinfo.
- makes fresh copy of varinfo only for declarations. Variables that are
only used in the visited AST are thus still shared with the original
AST. This allows for instance to copy a function with its
formals and local variables, and to keep the references to other
globals in the function's body.
@plugin development guide *)
val refresh_visit: Project.t -> visitor_behavior
* Makes fresh copies of the mutable structures and provides fresh i d
for the structures that have ids . Note that as for { ! , only
varinfo that are declared in the scope of the visit will be copied and
provided with a new i d.
@since Sodium-20150201
for the structures that have ids. Note that as for {!copy_visit}, only
varinfo that are declared in the scope of the visit will be copied and
provided with a new id.
@since Sodium-20150201
*)
* true iff the behavior provides fresh i d for copied structs with i d.
Always [ false ] for an inplace visitor .
@since Sodium-20150201
Always [false] for an inplace visitor.
@since Sodium-20150201
*)
val is_fresh_behavior: visitor_behavior -> bool
(** true iff the behavior is a copy behavior. *)
val is_copy_behavior: visitor_behavior -> bool
val reset_behavior_varinfo: visitor_behavior -> unit
(** resets the internal tables used by the given visitor_behavior. If you use
fresh instances of visitor for each round of transformation, this should
not be needed. In place modifications do not need that at all. *)
val reset_behavior_compinfo: visitor_behavior -> unit
val reset_behavior_enuminfo: visitor_behavior -> unit
val reset_behavior_enumitem: visitor_behavior -> unit
val reset_behavior_typeinfo: visitor_behavior -> unit
val reset_behavior_stmt: visitor_behavior -> unit
val reset_behavior_logic_info: visitor_behavior -> unit
val reset_behavior_logic_type_info: visitor_behavior -> unit
val reset_behavior_fieldinfo: visitor_behavior -> unit
val reset_behavior_model_info: visitor_behavior -> unit
val reset_logic_var: visitor_behavior -> unit
val reset_behavior_kernel_function: visitor_behavior -> unit
val reset_behavior_fundec: visitor_behavior -> unit
val get_varinfo: visitor_behavior -> varinfo -> varinfo
(** retrieve the representative of a given varinfo in the current
state of the visitor *)
val get_compinfo: visitor_behavior -> compinfo -> compinfo
val get_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val get_enumitem: visitor_behavior -> enumitem -> enumitem
val get_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val get_stmt: visitor_behavior -> stmt -> stmt
(** @plugin development guide *)
val get_logic_info: visitor_behavior -> logic_info -> logic_info
val get_logic_type_info: visitor_behavior -> logic_type_info -> logic_type_info
val get_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val get_model_info: visitor_behavior -> model_info -> model_info
val get_logic_var: visitor_behavior -> logic_var -> logic_var
val get_kernel_function: visitor_behavior -> kernel_function -> kernel_function
(** @plugin development guide *)
val get_fundec: visitor_behavior -> fundec -> fundec
val get_original_varinfo: visitor_behavior -> varinfo -> varinfo
(** retrieve the original representative of a given copy of a varinfo
in the current state of the visitor. *)
val get_original_compinfo: visitor_behavior -> compinfo -> compinfo
val get_original_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val get_original_enumitem: visitor_behavior -> enumitem -> enumitem
val get_original_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val get_original_stmt: visitor_behavior -> stmt -> stmt
val get_original_logic_info: visitor_behavior -> logic_info -> logic_info
val get_original_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info
val get_original_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val get_original_model_info: visitor_behavior -> model_info -> model_info
val get_original_logic_var: visitor_behavior -> logic_var -> logic_var
val get_original_kernel_function:
visitor_behavior -> kernel_function -> kernel_function
val get_original_fundec: visitor_behavior -> fundec -> fundec
val set_varinfo: visitor_behavior -> varinfo -> varinfo -> unit
* change the representative of a given varinfo in the current
state of the visitor . Use with care ( i.e. makes sure that the old one
is not referenced anywhere in the AST , or sharing will be lost .
state of the visitor. Use with care (i.e. makes sure that the old one
is not referenced anywhere in the AST, or sharing will be lost.
*)
val set_compinfo: visitor_behavior -> compinfo -> compinfo -> unit
val set_enuminfo: visitor_behavior -> enuminfo -> enuminfo -> unit
val set_enumitem: visitor_behavior -> enumitem -> enumitem -> unit
val set_typeinfo: visitor_behavior -> typeinfo -> typeinfo -> unit
val set_stmt: visitor_behavior -> stmt -> stmt -> unit
val set_logic_info: visitor_behavior -> logic_info -> logic_info -> unit
val set_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info -> unit
val set_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo -> unit
val set_model_info: visitor_behavior -> model_info -> model_info -> unit
val set_logic_var: visitor_behavior -> logic_var -> logic_var -> unit
val set_kernel_function:
visitor_behavior -> kernel_function -> kernel_function -> unit
val set_fundec: visitor_behavior -> fundec -> fundec -> unit
val set_orig_varinfo: visitor_behavior -> varinfo -> varinfo -> unit
(** change the reference of a given new varinfo in the current
state of the visitor. Use with care
*)
val set_orig_compinfo: visitor_behavior -> compinfo -> compinfo -> unit
val set_orig_enuminfo: visitor_behavior -> enuminfo -> enuminfo -> unit
val set_orig_enumitem: visitor_behavior -> enumitem -> enumitem -> unit
val set_orig_typeinfo: visitor_behavior -> typeinfo -> typeinfo -> unit
val set_orig_stmt: visitor_behavior -> stmt -> stmt -> unit
val set_orig_logic_info: visitor_behavior -> logic_info -> logic_info -> unit
val set_orig_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info -> unit
val set_orig_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo -> unit
val set_orig_model_info: visitor_behavior -> model_info -> model_info -> unit
val set_orig_logic_var: visitor_behavior -> logic_var -> logic_var -> unit
val set_orig_kernel_function:
visitor_behavior -> kernel_function -> kernel_function -> unit
val set_orig_fundec: visitor_behavior -> fundec -> fundec -> unit
val memo_varinfo: visitor_behavior -> varinfo -> varinfo
(** finds a binding in new project for the given varinfo, creating one
if it does not already exists. *)
val memo_compinfo: visitor_behavior -> compinfo -> compinfo
val memo_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val memo_enumitem: visitor_behavior -> enumitem -> enumitem
val memo_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val memo_stmt: visitor_behavior -> stmt -> stmt
val memo_logic_info: visitor_behavior -> logic_info -> logic_info
val memo_logic_type_info: visitor_behavior -> logic_type_info -> logic_type_info
val memo_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val memo_model_info: visitor_behavior -> model_info -> model_info
val memo_logic_var: visitor_behavior -> logic_var -> logic_var
val memo_kernel_function:
visitor_behavior -> kernel_function -> kernel_function
val memo_fundec: visitor_behavior -> fundec -> fundec
* [ iter_visitor_varinfo vis f ] iterates [ f ] over each pair of
varinfo registered in [ vis ] . for the old AST is presented
to [ f ] first .
@since Oxygen-20120901
varinfo registered in [vis]. Varinfo for the old AST is presented
to [f] first.
@since Oxygen-20120901
*)
val iter_visitor_varinfo:
visitor_behavior -> (varinfo -> varinfo -> unit) -> unit
val iter_visitor_compinfo:
visitor_behavior -> (compinfo -> compinfo -> unit) -> unit
val iter_visitor_enuminfo:
visitor_behavior -> (enuminfo -> enuminfo -> unit) -> unit
val iter_visitor_enumitem:
visitor_behavior -> (enumitem -> enumitem -> unit) -> unit
val iter_visitor_typeinfo:
visitor_behavior -> (typeinfo -> typeinfo -> unit) -> unit
val iter_visitor_stmt:
visitor_behavior -> (stmt -> stmt -> unit) -> unit
val iter_visitor_logic_info:
visitor_behavior -> (logic_info -> logic_info -> unit) -> unit
val iter_visitor_logic_type_info:
visitor_behavior -> (logic_type_info -> logic_type_info -> unit) -> unit
val iter_visitor_fieldinfo:
visitor_behavior -> (fieldinfo -> fieldinfo -> unit) -> unit
val iter_visitor_model_info:
visitor_behavior -> (model_info -> model_info -> unit) -> unit
val iter_visitor_logic_var:
visitor_behavior -> (logic_var -> logic_var -> unit) -> unit
val iter_visitor_kernel_function:
visitor_behavior -> (kernel_function -> kernel_function -> unit) -> unit
val iter_visitor_fundec:
visitor_behavior -> (fundec -> fundec -> unit) -> unit
* [ fold_visitor_varinfo vis f ] folds [ f ] over each pair of varinfo registered
in [ vis ] . for the old AST is presented to [ f ] first .
@since Oxygen-20120901
in [vis]. Varinfo for the old AST is presented to [f] first.
@since Oxygen-20120901
*)
val fold_visitor_varinfo:
visitor_behavior -> (varinfo -> varinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_compinfo:
visitor_behavior -> (compinfo -> compinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_enuminfo:
visitor_behavior -> (enuminfo -> enuminfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_enumitem:
visitor_behavior -> (enumitem -> enumitem -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_typeinfo:
visitor_behavior -> (typeinfo -> typeinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_stmt:
visitor_behavior -> (stmt -> stmt -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_info:
visitor_behavior -> (logic_info -> logic_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_type_info:
visitor_behavior ->
(logic_type_info -> logic_type_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_fieldinfo:
visitor_behavior -> (fieldinfo -> fieldinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_model_info:
visitor_behavior -> (model_info -> model_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_var:
visitor_behavior -> (logic_var -> logic_var -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_kernel_function:
visitor_behavior ->
(kernel_function -> kernel_function -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_fundec:
visitor_behavior -> (fundec -> fundec -> 'a -> 'a) -> 'a -> 'a
* { 3 Visitor class }
* A visitor interface for traversing CIL trees . Create instantiations of
this type by specializing the class { ! nopCilVisitor } . Each of the
specialized visiting functions can also call the [ queueInstr ] to specify
that some instructions should be inserted before the current instruction
or statement . Use syntax like [ self#queueInstr ] to call a method
associated with the current object .
{ b Important Note for Frama - C Users :} Unless you really know what you are
doing , you should probably inherit from the
{ ! Visitor.generic_frama_c_visitor } instead of { ! genericCilVisitor } or
{ ! nopCilVisitor }
@plugin development guide
this type by specializing the class {!nopCilVisitor}. Each of the
specialized visiting functions can also call the [queueInstr] to specify
that some instructions should be inserted before the current instruction
or statement. Use syntax like [self#queueInstr] to call a method
associated with the current object.
{b Important Note for Frama-C Users:} Unless you really know what you are
doing, you should probably inherit from the
{!Visitor.generic_frama_c_visitor} instead of {!genericCilVisitor} or
{!nopCilVisitor}
@plugin development guide *)
class type cilVisitor = object
method behavior: visitor_behavior
(** the kind of behavior expected for the behavior.
@plugin development guide *)
method project: Project.t option
(** Project the visitor operates on. Non-nil for copy visitor.
@since Oxygen-20120901 *)
method plain_copy_visitor: cilVisitor
(** a visitor who only does copies of the nodes according to [behavior] *)
method vfile: file -> file visitAction
(** visit a whole file.
@plugin development guide *)
method vvdec: varinfo -> varinfo visitAction
* Invoked for each variable declaration . The children to be traversed
are those corresponding to the type and attributes of the variable .
Note that variable declarations are [ GVar ] , [ GVarDecl ] , [ GFun ] and
[ GFunDecl ] globals , the formals of functions prototypes , and the
formals and locals of function definitions . This means that the list
of formals of a function may be traversed multiple times if there exists
both a declaration and a definition , or multiple declarations .
@plugin development guide
are those corresponding to the type and attributes of the variable.
Note that variable declarations are [GVar], [GVarDecl], [GFun] and
[GFunDecl] globals, the formals of functions prototypes, and the
formals and locals of function definitions. This means that the list
of formals of a function may be traversed multiple times if there exists
both a declaration and a definition, or multiple declarations.
@plugin development guide *)
method vvrbl: varinfo -> varinfo visitAction
* Invoked on each variable use . Here only the [ SkipChildren ] and
[ ChangeTo ] actions make sense since there are no subtrees . Note that
the type and attributes of the variable are not traversed for a
variable use .
@plugin development guide
[ChangeTo] actions make sense since there are no subtrees. Note that
the type and attributes of the variable are not traversed for a
variable use.
@plugin development guide *)
method vexpr: exp -> exp visitAction
(** Invoked on each expression occurrence. The subtrees are the
subexpressions, the types (for a [Cast] or [SizeOf] expression) or the
variable use.
@plugin development guide *)
method vlval: lval -> lval visitAction
(** Invoked on each lvalue occurrence *)
method voffs: offset -> offset visitAction
(** Invoked on each offset occurrence that is *not* as part of an
initializer list specification, i.e. in an lval or recursively inside an
offset.
@plugin development guide *)
method vinitoffs: offset -> offset visitAction
* Invoked on each offset appearing in the list of a
CompoundInit initializer .
CompoundInit initializer. *)
method vinst: instr -> instr list visitAction
(** Invoked on each instruction occurrence. The [ChangeTo] action can
replace this instruction with a list of instructions *)
method vstmt: stmt -> stmt visitAction
* Control - flow statement . The default [ DoChildren ] action does not create a
new statement when the components change . Instead it updates the contents
of the original statement . This is done to preserve the sharing with
[ ] and [ Case ] statements that point to the original statement . If you
use the [ ChangeTo ] action then you should take care of preserving that
sharing yourself .
@plugin development guide
new statement when the components change. Instead it updates the contents
of the original statement. This is done to preserve the sharing with
[Goto] and [Case] statements that point to the original statement. If you
use the [ChangeTo] action then you should take care of preserving that
sharing yourself.
@plugin development guide *)
method vblock: block -> block visitAction
(** Block. *)
method vfunc: fundec -> fundec visitAction
(** Function definition. Replaced in place. *)
method vglob: global -> global list visitAction
(** Global (vars, types, etc.)
@plugin development guide *)
method vinit: varinfo -> offset -> init -> init visitAction
(** Initializers for globals, pass the global where this occurs, and the
offset *)
method vtype: typ -> typ visitAction
* Use of some type . For typedef , struct , union and enum , the visit is
done once at the global defining the type . Thus , children of
[ TComp ] , [ TEnum ] and [ TNamed ] are not visited again .
done once at the global defining the type. Thus, children of
[TComp], [TEnum] and [TNamed] are not visited again. *)
method vcompinfo: compinfo -> compinfo visitAction
(** declaration of a struct/union *)
method venuminfo: enuminfo -> enuminfo visitAction
(** declaration of an enumeration *)
method vfieldinfo: fieldinfo -> fieldinfo visitAction
(** visit the declaration of a field of a structure or union *)
method venumitem: enumitem -> enumitem visitAction
(** visit the declaration of an enumeration item *)
method vattr: attribute -> attribute list visitAction
(** Attribute. Each attribute can be replaced by a list *)
method vattrparam: attrparam -> attrparam visitAction
(** Attribute parameters. *)
method queueInstr: instr list -> unit
(** Add here instructions while visiting to queue them to preceede the
current statement or instruction being processed. Use this method only
when you are visiting an expression that is inside a function body, or a
statement, because otherwise there will no place for the visitor to place
your instructions. *)
(** Gets the queue of instructions and resets the queue. This is done
automatically for you when you visit statments. *)
method unqueueInstr: unit -> instr list
method current_stmt: stmt option
* link to the current statement being visited .
{ b NB :} for copy visitor , the stmt is the original one ( use
[ get_stmt ] to obtain the corresponding copy )
{b NB:} for copy visitor, the stmt is the original one (use
[get_stmt] to obtain the corresponding copy) *)
method current_kinstr: kinstr
* [ stmt ] when visiting statement stmt , [ Kglobal ] when called outside
of a statement .
@since Carbon-20101201
@plugin development guide
of a statement.
@since Carbon-20101201
@plugin development guide *)
method push_stmt : stmt -> unit
method pop_stmt : stmt -> unit
method current_func: fundec option
* link to the current function being visited .
{ b NB :} for copy visitors , the fundec is the original one .
{b NB:} for copy visitors, the fundec is the original one. *)
method set_current_func: fundec -> unit
method reset_current_func: unit -> unit
method vlogic_type: logic_type -> logic_type visitAction
method vmodel_info: model_info -> model_info visitAction
method videntified_term: identified_term -> identified_term visitAction
method vterm: term -> term visitAction
method vterm_node: term_node -> term_node visitAction
method vterm_lval: term_lval -> term_lval visitAction
method vterm_lhost: term_lhost -> term_lhost visitAction
method vterm_offset: term_offset -> term_offset visitAction
method vlogic_label: logic_label -> logic_label visitAction
method vlogic_info_decl: logic_info -> logic_info visitAction
(** @plugin development guide *)
method vlogic_info_use: logic_info -> logic_info visitAction
(** @plugin development guide *)
method vlogic_type_info_decl: logic_type_info -> logic_type_info visitAction
(** @plugin development guide *)
method vlogic_type_info_use: logic_type_info -> logic_type_info visitAction
(** @plugin development guide *)
method vlogic_type_def: logic_type_def -> logic_type_def visitAction
method vlogic_ctor_info_decl: logic_ctor_info -> logic_ctor_info visitAction
(** @plugin development guide *)
method vlogic_ctor_info_use: logic_ctor_info -> logic_ctor_info visitAction
(** @plugin development guide *)
method vlogic_var_decl: logic_var -> logic_var visitAction
(** @plugin development guide *)
method vlogic_var_use: logic_var -> logic_var visitAction
(** @plugin development guide *)
method vquantifiers: quantifiers -> quantifiers visitAction
method videntified_predicate:
identified_predicate -> identified_predicate visitAction
(**
@since Fluorine-20130401
the child of an identified predicate is treated as a predicate named:
if you wish to modify names, you only have to override vpredicate_named,
not both videntified_predicate and vpredicate_named.
*)
method vpredicate: predicate -> predicate visitAction
method vpredicate_named: predicate named -> predicate named visitAction
method vbehavior: funbehavior -> funbehavior visitAction
method vspec: funspec -> funspec visitAction
method vassigns:
identified_term assigns -> identified_term assigns visitAction
method vfrees:
identified_term list -> identified_term list visitAction
(**@since Oxygen-20120901 *)
method vallocates:
identified_term list -> identified_term list visitAction
(**@since Oxygen-20120901 *)
method vallocation:
identified_term allocation -> identified_term allocation visitAction
(**@since Oxygen-20120901 *)
method vloop_pragma: term loop_pragma -> term loop_pragma visitAction
method vslice_pragma: term slice_pragma -> term slice_pragma visitAction
method vimpact_pragma: term impact_pragma -> term impact_pragma visitAction
method vdeps: identified_term deps -> identified_term deps visitAction
method vfrom: identified_term from -> identified_term from visitAction
method vcode_annot: code_annotation -> code_annotation visitAction
method vannotation: global_annotation -> global_annotation visitAction
method fill_global_tables: unit
(** fill the global environment tables at the end of a full copy in a
new project.
@plugin development guide *)
method get_filling_actions: (unit -> unit) Queue.t
(** get the queue of actions to be performed at the end of a full copy.
@plugin development guide *)
end
* Indicates how an extended behavior clause is supposed to be visited .
The default behavior is [ DoChildren ] , which ends up visiting
each identified predicate in the list and leave the i d as is .
@plugin development guide
@since Sodium-20150201
The default behavior is [DoChildren], which ends up visiting
each identified predicate in the list and leave the id as is.
@plugin development guide
@since Sodium-20150201
*)
val register_behavior_extension:
string ->
(cilVisitor -> (int * identified_predicate list) ->
(int * identified_predicate list) visitAction) -> unit
(**/**)
class internal_genericCilVisitor:
fundec option ref -> visitor_behavior -> (unit->unit) Queue.t -> cilVisitor
(**/**)
(** generic visitor, parameterized by its copying behavior.
Traverses the CIL tree without modifying anything *)
class genericCilVisitor: visitor_behavior -> cilVisitor
(** Default in place visitor doing nothing and operating on current project. *)
class nopCilVisitor: cilVisitor
* { 3 Generic visit functions }
* [ doVisit vis deepCopyVisitor copy action children node ]
visits a [ node ]
( or its copy according to the result of [ copy ] ) and if needed
its [ children ] . { b Do not use it if you do n't understand Cil visitor
mechanism }
@param vis the visitor performing the needed transformations . The open
type allows for extensions to to be visited by the same mechanisms .
@param deepCopyVisitor a generator for a visitor of the same type
of the current one that performs a deep copy of the AST .
Needed when the visitAction is [ SkipChildren ] or [ ChangeTo ] and [ vis ]
is a copy visitor ( we need to finish the copy anyway )
@param copy function that may return a copy of the actual node .
@param action the visiting function for the current node
@param children what to do on the children of the current node
@param node the current node
visits a [node]
(or its copy according to the result of [copy]) and if needed
its [children]. {b Do not use it if you don't understand Cil visitor
mechanism}
@param vis the visitor performing the needed transformations. The open
type allows for extensions to Cil to be visited by the same mechanisms.
@param deepCopyVisitor a generator for a visitor of the same type
of the current one that performs a deep copy of the AST.
Needed when the visitAction is [SkipChildren] or [ChangeTo] and [vis]
is a copy visitor (we need to finish the copy anyway)
@param copy function that may return a copy of the actual node.
@param action the visiting function for the current node
@param children what to do on the children of the current node
@param node the current node
*)
val doVisit:
'visitor -> 'visitor ->
('a -> 'a) ->
('a -> 'a visitAction) ->
('visitor -> 'a -> 'a) -> 'a -> 'a
(** same as above, but can return a list of nodes *)
val doVisitList:
'visitor -> 'visitor ->
('a -> 'a) ->
('a -> 'a list visitAction) ->
('visitor -> 'a -> 'a) -> 'a -> 'a list
other cil constructs
* { 3 Visitor 's entry points }
(** Visit a file. This will re-cons all globals TWICE (so that it is
* tail-recursive). Use {!Cil.visitCilFileSameGlobals} if your visitor will
* not change the list of globals.
@plugin development guide *)
val visitCilFileCopy: cilVisitor -> file -> file
(** Same thing, but the result is ignored. The given visitor must thus be
an inplace visitor. Nothing is done if the visitor is a copy visitor.
@plugin development guide *)
val visitCilFile: cilVisitor -> file -> unit
(** A visitor for the whole file that does not change the globals (but maybe
* changes things inside the globals). Use this function instead of
* {!Cil.visitCilFile} whenever appropriate because it is more efficient for
* long files.
@plugin development guide *)
val visitCilFileSameGlobals: cilVisitor -> file -> unit
(** Visit a global *)
val visitCilGlobal: cilVisitor -> global -> global list
(** Visit a function definition *)
val visitCilFunction: cilVisitor -> fundec -> fundec
(* Visit an expression *)
val visitCilExpr: cilVisitor -> exp -> exp
val visitCilEnumInfo: cilVisitor -> enuminfo -> enuminfo
(** Visit an lvalue *)
val visitCilLval: cilVisitor -> lval -> lval
(** Visit an lvalue or recursive offset *)
val visitCilOffset: cilVisitor -> offset -> offset
(** Visit an initializer offset *)
val visitCilInitOffset: cilVisitor -> offset -> offset
(** Visit an instruction *)
val visitCilInstr: cilVisitor -> instr -> instr list
(** Visit a statement *)
val visitCilStmt: cilVisitor -> stmt -> stmt
(** Visit a block *)
val visitCilBlock: cilVisitor -> block -> block
(** Visit a type *)
val visitCilType: cilVisitor -> typ -> typ
(** Visit a variable declaration *)
val visitCilVarDecl: cilVisitor -> varinfo -> varinfo
(** Visit an initializer, pass also the global to which this belongs and the
* offset. *)
val visitCilInit: cilVisitor -> varinfo -> offset -> init -> init
(** Visit a list of attributes *)
val visitCilAttributes: cilVisitor -> attribute list -> attribute list
val visitCilAnnotation: cilVisitor -> global_annotation -> global_annotation
val visitCilCodeAnnotation: cilVisitor -> code_annotation -> code_annotation
val visitCilDeps:
cilVisitor -> identified_term deps -> identified_term deps
val visitCilFrom:
cilVisitor -> identified_term from -> identified_term from
val visitCilAssigns:
cilVisitor -> identified_term assigns -> identified_term assigns
(** @since Oxygen-20120901
*)
val visitCilFrees:
cilVisitor -> identified_term list -> identified_term list
(** @since Oxygen-20120901
*)
val visitCilAllocates:
cilVisitor -> identified_term list -> identified_term list
(** @since Oxygen-20120901
*)
val visitCilAllocation:
cilVisitor -> identified_term allocation -> identified_term allocation
val visitCilFunspec: cilVisitor -> funspec -> funspec
val visitCilBehavior: cilVisitor -> funbehavior -> funbehavior
val visitCilBehaviors: cilVisitor -> funbehavior list -> funbehavior list
* visit an extended clause of a behavior .
@since
@since Nitrogen-20111001
*)
val visitCilExtended:
cilVisitor -> (string * int * identified_predicate list)
-> (string * int * identified_predicate list)
val visitCilModelInfo: cilVisitor -> model_info -> model_info
val visitCilLogicType: cilVisitor -> logic_type -> logic_type
val visitCilIdPredicate:
cilVisitor -> identified_predicate -> identified_predicate
val visitCilPredicate: cilVisitor -> predicate -> predicate
val visitCilPredicateNamed: cilVisitor -> predicate named -> predicate named
val visitCilPredicates:
cilVisitor -> identified_predicate list -> identified_predicate list
val visitCilTerm: cilVisitor -> term -> term
(** visit identified_term.
@since Oxygen-20120901
*)
val visitCilIdTerm: cilVisitor -> identified_term -> identified_term
* visit term_lval .
@since
@since Nitrogen-20111001
*)
val visitCilTermLval: cilVisitor -> term_lval -> term_lval
val visitCilTermLhost: cilVisitor -> term_lhost -> term_lhost
val visitCilTermOffset: cilVisitor -> term_offset -> term_offset
val visitCilLogicInfo: cilVisitor -> logic_info -> logic_info
val visitCilLogicVarUse: cilVisitor -> logic_var -> logic_var
val visitCilLogicVarDecl: cilVisitor -> logic_var -> logic_var
* { 3 Visiting children of a node }
val childrenBehavior: cilVisitor -> funbehavior -> funbehavior
(* And some generic visitors. The above are built with these *)
(* ************************************************************************* *)
* { 2 Utility functions }
(* ************************************************************************* *)
val is_skip: stmtkind -> bool
(** A visitor that does constant folding. Pass as argument whether you want
* machine specific simplifications to be done, or not. *)
val constFoldVisitor: bool -> cilVisitor
(* ************************************************************************* *)
* { 2 Debugging support }
(* ************************************************************************* *)
(** A reference to the current location. If you are careful to set this to
* the current location then you can use some built-in logging functions that
* will print the location. *)
module CurrentLoc: State_builder.Ref with type data = location
(** Pretty-print [(Cil.CurrentLoc.get ())] *)
val pp_thisloc: Format.formatter -> unit
(** @return a dummy specification *)
val empty_funspec : unit -> funspec
(** @return true if the given spec is empty. *)
val is_empty_funspec: funspec -> bool
(** @return true if the given behavior is empty. *)
val is_empty_behavior: funbehavior -> bool
(* ************************************************************************* *)
* { 2 ALPHA conversion } has been moved to the Alpha module .
(* ************************************************************************* *)
(** Assign unique names to local variables. This might be necessary after you
transformed the code and added or renamed some new variables. Names are not
used by CIL internally, but once you print the file out the compiler
downstream might be confused. You might have added a new global that happens
to have the same name as a local in some function. Rename the local to
ensure that there would never be confusion. Or, viceversa, you might have
added a local with a name that conflicts with a global *)
val uniqueVarNames: file -> unit
(* ************************************************************************* *)
* { 2 Optimization Passes }
(* ************************************************************************* *)
* A peephole optimizer that processes two adjacent statements and possibly
replaces them both . If some replacement happens and [ agressive ] is true ,
then the new statements are themselves subject to optimization . Each
statement in the list is optimized independently .
replaces them both. If some replacement happens and [agressive] is true,
then the new statements are themselves subject to optimization. Each
statement in the list is optimized independently. *)
val peepHole2:
agressive:bool -> (stmt * stmt -> stmt list option) -> stmt list -> stmt list
* Similar to [ peepHole2 ] except that the optimization window consists of
one statement , not two
one statement, not two *)
val peepHole1: (instr -> instr list option) -> stmt list -> unit
(* ************************************************************************* *)
* { 2 Machine dependency }
(* ************************************************************************* *)
* Raised when one of the SizeOf / AlignOf functions can not compute the size of a
type . This can happen because the type contains array - length expressions
that we do n't know how to compute or because it is a type whose size is not
defined ( e.g. TFun or an undefined ) . The string is an explanation
of the error
type. This can happen because the type contains array-length expressions
that we don't know how to compute or because it is a type whose size is not
defined (e.g. TFun or an undefined compinfo). The string is an explanation
of the error *)
exception SizeOfError of string * typ
(** Create a fresh size cache with [Not_Computed] *)
val empty_size_cache : unit -> bitsSizeofTypCache
(** Give the unsigned kind corresponding to any integer kind *)
val unsignedVersionOf : ikind -> ikind
(** Give the signed kind corresponding to any integer kind *)
val signedVersionOf : ikind -> ikind
* The signed integer kind for a given size in bytes ( unsigned if second
* argument is true ) . Raises Not_found if no such kind exists
* argument is true). Raises Not_found if no such kind exists *)
val intKindForSize : int -> bool -> ikind
* The signed integer kind for a given size in bits ( unsigned if second
* argument is true ) . Raises Not_found if no such kind exists
* argument is true). Raises Not_found if no such kind exists *)
val intKindForBits : int -> bool -> ikind
(** The float kind for a given size in bytes. Raises Not_found
* if no such kind exists *)
val floatKindForSize : int-> fkind
* The size of a type , in bits . Trailing padding is added for structs and
* arrays . Raises { ! . SizeOfError } when it can not compute the size . This
* function is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } . Remember that on GCC sizeof(void ) is 1 !
* arrays. Raises {!Cil.SizeOfError} when it cannot compute the size. This
* function is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. Remember that on GCC sizeof(void) is 1! *)
val bitsSizeOf: typ -> int
* The size of a type , in bytes . Raises { ! . SizeOfError } when it can not
compute the size .
compute the size. *)
val bytesSizeOf: typ -> int
(** Returns the number of bytes (resp. bits) to represent the given integer
kind depending on the current machdep. *)
val bytesSizeOfInt: ikind -> int
val bitsSizeOfInt: ikind -> int
(** Returns the signedness of the given integer kind depending
on the current machdep. *)
val isSigned: ikind -> bool
(** Returns a unique number representing the integer
conversion rank. *)
val rank: ikind -> int
* [ intTypeIncluded i1 i2 ] returns [ true ] iff the range of values
representable in [ i1 ] is included in the one of [ i2 ]
representable in [i1] is included in the one of [i2] *)
val intTypeIncluded: ikind -> ikind -> bool
(** Returns a unique number representing the floating-point conversion rank.
@since Oxygen-20120901 *)
val frank: fkind -> int
(** Represents an integer as for a given kind.
* Returns a flag saying whether the value was changed
* during truncation (because it was too large to fit in k). *)
val truncateInteger64: ikind -> Integer.t -> Integer.t * bool
(** Returns the maximal value representable in a signed integer type of the
given size (in bits)
*)
val max_signed_number: int -> Integer.t
(** Returns the smallest value representable in a signed integer type of the
given size (in bits)
*)
val min_signed_number: int -> Integer.t
(** Returns the maximal value representable in a unsigned integer type of the
given size (in bits)
*)
val max_unsigned_number: int -> Integer.t
(** True if the integer fits within the kind's range *)
val fitsInInt: ikind -> Integer.t -> bool
exception Not_representable
(** raised by {!intKindForValue}. *)
* @return the smallest kind that will hold the integer 's value .
The kind will be unsigned if the 2nd argument is true .
@raise if the bigint is not representable .
@modify Neon-20130301 may raise .
The kind will be unsigned if the 2nd argument is true.
@raise Not_representable if the bigint is not representable.
@modify Neon-20130301 may raise Not_representable. *)
val intKindForValue: Integer.t -> bool -> ikind
* The size of a type , in bytes . Returns a constant expression or a " sizeof "
* expression if it can not compute the size . This function is architecture
* dependent , so you should only call this after you call { ! Cil.initCIL } .
* expression if it cannot compute the size. This function is architecture
* dependent, so you should only call this after you call {!Cil.initCIL}. *)
val sizeOf: loc:location -> typ -> exp
* The minimum alignment ( in bytes ) for a type . This function is
* architecture dependent , so you should only call this after you call
* { ! Cil.initCIL } .
* architecture dependent, so you should only call this after you call
* {!Cil.initCIL}. *)
val bytesAlignOf: typ -> int
* Give a type of a base and an offset , returns the number of bits from the
* base address and the width ( also expressed in bits ) for the subobject
* denoted by the offset . Raises { ! . SizeOfError } when it can not compute
* the size . This function is architecture dependent , so you should only call
* this after you call { ! Cil.initCIL } .
* base address and the width (also expressed in bits) for the subobject
* denoted by the offset. Raises {!Cil.SizeOfError} when it cannot compute
* the size. This function is architecture dependent, so you should only call
* this after you call {!Cil.initCIL}. *)
val bitsOffset: typ -> offset -> int * int
(** Generate an {!Cil_types.exp} to be used in case of errors. *)
val dExp:string -> exp
(** Generate an {!Cil_types.instr} to be used in case of errors. *)
val dInstr: string -> location -> instr
(** Generate a {!Cil_types.global} to be used in case of errors. *)
val dGlobal: string -> location -> global
(** Like map but try not to make a copy of the list *)
val mapNoCopy: ('a -> 'a) -> 'a list -> 'a list
(** same as mapNoCopy for options*)
val optMapNoCopy: ('a -> 'a) -> 'a option -> 'a option
(** Like map but each call can return a list. Try not to make a copy of the
list *)
val mapNoCopyList: ('a -> 'a list) -> 'a list -> 'a list
* sm : return true if the first is a prefix of the second string
val startsWith: string -> string -> bool
(* ************************************************************************* *)
* { 2 An Interpreter for constructing CIL constructs }
(* ************************************************************************* *)
(** The type of argument for the interpreter *)
type formatArg =
Fe of exp
| Feo of exp option (** For array lengths *)
| Fu of unop
| Fb of binop
| Fk of ikind
| FE of exp list (** For arguments in a function call *)
| Ff of (string * typ * attributes) (** For a formal argument *)
| FF of (string * typ * attributes) list (** For formal argument lists *)
| Fva of bool (** For the ellipsis in a function type *)
| Fv of varinfo
| Fl of lval
| Flo of lval option
| Fo of offset
| Fc of compinfo
| Fi of instr
| FI of instr list
| Ft of typ
| Fd of int
| Fg of string
| Fs of stmt
| FS of stmt list
| FA of attributes
| Fp of attrparam
| FP of attrparam list
| FX of string
val d_formatarg : Format.formatter -> formatArg -> unit
(* ************************************************************************* *)
* { 2 Misc }
(* ************************************************************************* *)
val stmt_of_instr_list : ?loc:location -> instr list -> stmtkind
(** Convert a C variable into the corresponding logic variable.
The returned logic variable is unique for a given C variable. *)
val cvar_to_lvar : varinfo -> logic_var
(** Make a temporary variable to use in annotations *)
val make_temp_logic_var: logic_type -> logic_var
* The constant logic term zero .
@plugin development guide
@plugin development guide *)
val lzero : ?loc:location -> unit -> term
* The constant logic term 1 .
val lone : ?loc:location -> unit -> term
(** The constant logic term -1. *)
val lmone : ?loc:location -> unit -> term
(** The given constant logic term *)
val lconstant : ?loc:location -> Integer.t -> term
(** Bind all free variables with an universal quantifier *)
val close_predicate : predicate named -> predicate named
(** extract [varinfo] elements from an [exp] *)
val extract_varinfos_from_exp : exp -> Varinfo.Set.t
(** extract [varinfo] elements from an [lval] *)
val extract_varinfos_from_lval : lval -> Varinfo.Set.t
(** extract [logic_var] elements from a [term] *)
val extract_free_logicvars_from_term : term -> Logic_var.Set.t
(** extract [logic_var] elements from a [predicate] *)
val extract_free_logicvars_from_predicate :
predicate named -> Logic_var.Set.t
(** extract [logic_label] elements from a [code_annotation] *)
val extract_labels_from_annot:
code_annotation -> Cil_datatype.Logic_label.Set.t
(** extract [logic_label] elements from a [term] *)
val extract_labels_from_term: term -> Cil_datatype.Logic_label.Set.t
(** extract [logic_label] elements from a [pred] *)
val extract_labels_from_pred:
predicate named -> Cil_datatype.Logic_label.Set.t
* extract [ stmt ] elements from [ logic_label ] elements
val extract_stmts_from_labels:
Cil_datatype.Logic_label.Set.t -> Cil_datatype.Stmt.Set.t
* creates a visitor that will replace in place uses of var in the first
list by their counterpart in the second list .
@raise Invalid_argument if the lists have different lengths .
list by their counterpart in the second list.
@raise Invalid_argument if the lists have different lengths. *)
val create_alpha_renaming: varinfo list -> varinfo list -> cilVisitor
* Provided [ s ] is a switch , [ separate_switch_succs s ] returns the
subset of [ s.succs ] that correspond to the Case labels of [ s ] , and a
" default statement " that either corresponds to the label , or to the
syntactic successor of [ s ] if there is no default label . Note that this " default
statement " can thus appear in the returned list .
subset of [s.succs] that correspond to the Case labels of [s], and a
"default statement" that either corresponds to the Default label, or to the
syntactic successor of [s] if there is no default label. Note that this "default
statement" can thus appear in the returned list. *)
val separate_switch_succs: stmt -> stmt list * stmt
* Provided [ s ] is a if , [ separate_if_succs s ] splits the successors
of s according to the truth value of the condition . The first
element of the pair is the successor statement if the condition is
true , and the second if the condition is false .
of s according to the truth value of the condition. The first
element of the pair is the successor statement if the condition is
true, and the second if the condition is false. *)
val separate_if_succs: stmt -> stmt * stmt
(**/**)
val dependency_on_ast: State.t -> unit
* indicates that the given state depends on the AST and is monotonic .
val set_dependencies_of_ast : (State.t -> unit) -> State.t -> unit
* Makes all states that have been marked as depending on the AST by
{ ! dependency_on_ast } depend on the given state . Should only be used
once when creating the AST state .
The first argument is always bound to { Ast.add_monotonic_state }
and will be applied to each state declared by { dependency_on_ast } .
{!dependency_on_ast} depend on the given state. Should only be used
once when creating the AST state.
The first argument is always bound to {Ast.add_monotonic_state}
and will be applied to each state declared by {dependency_on_ast}.
*)
val pp_typ_ref: (Format.formatter -> typ -> unit) ref
val pp_global_ref: (Format.formatter -> global -> unit) ref
val pp_exp_ref: (Format.formatter -> exp -> unit) ref
val pp_lval_ref: (Format.formatter -> lval -> unit) ref
val pp_ikind_ref: (Format.formatter -> ikind -> unit) ref
val pp_attribute_ref: (Format.formatter -> attribute -> unit) ref
val pp_attributes_ref: (Format.formatter -> attribute list -> unit) ref
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_services/ast_queries/cil.mli | ocaml | ************************************************************************
************************************************************************
**************************************************************************
Scott McPeak <>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
énergies alternatives)
et Automatique).
**************************************************************************
* CIL main API.
CIL original API documentation is available as
an html version at .
@plugin development guide
*************************************************************************
*************************************************************************
* This module associates the name of a built-in function that might be used
during elaboration with the corresponding varinfo. This is done when
parsing ${TIS_KERNEL_SHARE}/libc/__fc_builtins.h, which is always performed
before processing the actual list of files provided on the command line (see
{!File.init_from_c_files}). Actual list of such built-ins is managed in
{!Cabs2cil}.
* @return true if the given variable refers to a Frama-C builtin.
@since Fluorine-20130401
* @return true if the given variable refers to a Frama-C builtin that
is not used in the current program. Plugins may (and in fact should)
hide this builtin from their outputs
* @return [true] if the given name refers to a special built-in function.
A special built-in function can have any number of arguments. It is up to
the plug-ins to know what to do with it.
@since Boron-20100401-dev
* register a new special built-in function
* register a new family of special built-in functions.
@since Carbon-20101201
* initialize the C built-ins. Should be called once per project, after the
machine has been set.
* Call this function to perform some initialization, and only after you have
set [Cil.msvcMode]. [initLogicBuiltins] is the function to call to init
logic builtins. The [Machdeps] argument is a description of the hardware
platform and of the compiler used.
*************************************************************************
*************************************************************************
* Do lower constants (default true)
* Do insert implicit casts (default true)
* An unsigned integer type that fits pointers.
* An integer type that fits wchar_t.
* An integer type that fits ptrdiff_t.
* An integer type that is the type of sizeof.
* Current machine description
* whether current project has set its machine description.
*************************************************************************
*************************************************************************
* Make an empty function
* Update the formals of a [fundec] and make sure that the function type
has the same information. Will copy the name as well into the type.
* Takes as input a function type (or a typename on it) and return its
return type.
* Set the type of the function and make formal arguments for them
* state of the table associating formals to each prototype.
* creates a new varinfo for the parameter of a prototype.
* remove a binding from the table.
@since Oxygen-20120901
* iters the given function on declared prototypes.
@since Oxygen-20120901
* Get the formals of a function declaration registered with
{!Cil.setFormalsDecl}.
@raise Not_found if the function is not registered (this is in particular
the case for prototypes with an empty list of arguments.
See {!Cil.setFormalsDecl})
* A dummy file
* Iterate over all globals, including the global initializer
* Fold over all globals, including the global initializer
* Map over all globals, including the global initializer and change things
in place
* Find a function or function prototype with the given name in the file.
* If it does not exist, create a prototype with the given type, and return
* the new varinfo. This is useful when you need to call a libc function
* whose prototype may or may not already exist in the file.
*
* Because the new prototype is added to the start of the file, you shouldn't
* refer to any struct or union types in the function type.
* creates an expression with a fresh id
* Return [true] on case and default labels, [false] otherwise.
* CIL keeps the types at the beginning of the file and the variables at the
* end of the file. This function will take a global and add it to the
* corresponding stack. Its operation is actually more complicated because if
* the global declares a type that contains references to variables (e.g. in
* sizeof in an array length) then it will also add declarations for the
* variables to the types stack
* An empty statement. Used in pretty printing
* This is used as the location of the prototypes of builtin functions.
*************************************************************************
*************************************************************************
*************************************************************************
*************************************************************************
* void
* is the given type "void"?
* is the given type "void *"?
* int
* unsigned int
* long
* long long
* unsigned long
* unsigned long long
* char
* char *
* char const *
* void *
* void const *
* int *
* unsigned int *
* float
* double
* long double
* @return true if and only if the given type is a signed integer type.
* @return true if and only if the given type is an unsigned integer type.
@since Oxygen-20120901
whether it is a struct or a union
name of the composite type; cannot be empty
original name of the composite type, empty when anonymous
a function that when given a forward
representation of the structure type constructs the type of
the fields. The function can ignore this argument if not
constructing a recursive type.
* This is a constant used as the name of an unnamed bitfield. These fields
do not participate in initialization and their name is not printed.
* Get the full name of a comp
* Returns true if this is a complete type.
This means that sizeof(t) makes sense.
Incomplete types are not yet defined structures and empty arrays.
Expects a valid type as argument.
@param allowZeroSizeArrays defaults to [false]. When [true], arrays of
size 0 (a gcc extension) are considered as complete
* Returns true iff this is a structure type with a flexible array member or a
union type containing, possibly recursively, a member of such a structure
type.
* Unroll a type until it exposes a non
* [TNamed]. Will collect all attributes appearing in [TNamed]!!!
* Separate out the storage-modifier name attributes
* True if the argument is a character type (i.e. plain, signed or unsigned)
* True if the argument is a short type (i.e. signed or unsigned)
* True if the argument is a pointer to a character type
(i.e. plain, signed or unsigned)
* True if the argument is an array of a character type
(i.e. plain, signed or unsigned)
* True if the argument is an integral type (i.e. integer or enum)
* True if the argument is an integral or pointer type.
* True if the argument is a floating point type
* True if the argument is a floating point type
* True if the argument is a C floating point type or logic 'real' type
* True if the argument is the logic 'real' type
* True if the argument is an arithmetic type (i.e. integer, enum or
floating point
* True if the argument is an arithmetic or pointer type (i.e. integer, enum,
floating point or pointer
* True if the argument is a pointer type
* True if the argument is the type for reified C types
* True if the argument is a function type.
* Obtain the argument list ([] if None)
* True if the argument is an array type
* True if the argument is an array type of known size.
* True if the argument is an array type of unknown size.
* True if the argument is a struct or union type
* Raised when {!Cil.lenOfArray} fails either because the length is [None]
* or because it is a non-constant expression
* A datatype to be used in conjunction with [existsType]
* We have found it
* Stop processing this branch
* This node is not what we are
* looking for but maybe its
* successors are
* Given a function type split it into return type,
* arguments, is_vararg and attributes. An error is raised if the type is not
* a function type
* Same as {!Cil.splitFunctionType} but takes a varinfo. Prints a nicer
* error message if the varinfo is not for a function
*******************************************************
* Make a temporary variable and add it to a function's slocals. The name of
the temporary variable will be generated based on the given name hint so
that to avoid conflicts with other locals.
Optionally, you can give the variable a description of its contents.
Temporary variables are always considered as generated variables.
If [insert] is true (the default), the variable will be inserted
among other locals of the function. The value for [insert] should
only be changed if you are completely sure this is not useful.
* Make a global variable. Your responsibility to make sure that the name
is unique. [source] defaults to [true]. [temp] defaults to [false].
* Make a shallow copy of a [varinfo] and assign a new identifier.
If the original varinfo has an associated logic var, it is copied too and
associated to the copied varinfo
* Changes the type of a varinfo and of its associated logic var if any.
@since Neon-20140301
* Returns the last offset in the chain.
* Add an offset at the end of an lvalue. Make sure the type of the lvalue
* and the offset are compatible.
* [addOffset o1 o2] adds [o1] to the end of [o2].
* Compute the type of an lvalue
* Compute the type of an lhost (with no offset)
* Equivalent to [typeOfLval] for terms.
* Compute the type of an offset from a base type
* Equivalent to [typeOffset] for terms.
* Compute the type of an initializer
*************************************************************************
*************************************************************************
* -1
* Construct an integer of a given kind without literal representation.
Truncate the integer if [kind] is given, and the integer does not fit
inside the type. The integer can have an optional literal representation
[repr].
@raise Not_representable if no ikind is provided and the integer is not
representable.
* Constructs a floating point constant.
@since Oxygen-20120901
* True if the given expression is a (possibly cast'ed)
character or an integer constant
* True if the expression is a compile-time constant
* True if the expression is a compile-time integer constant
* True if the given offset contains only field nanmes or constant indices.
* True if the term is the constant 0
* True if the given term is [\null] or a constant null pointer
* gives the value of a wide char literal.
* gives the value of a char literal.
* Do constant folding on the given expression, just as [constFold] would. The
resulting integer value, if the const-folding was complete, is returned.
The [machdep] optional parameter, which is set to [true] by default,
forces the simplification of architecture-dependent expressions.
* Do constant folding on an term at toplevel only.
This uses compiler-dependent informations and will
remove all sizeof and alignof.
* Increment an expression. Can be arithmetic or pointer type
* Increment an expression. Can be arithmetic or pointer type
* Makes an lvalue out of a given variable
* Creates an expression corresponding to "&v".
@since Oxygen-20120901
* Like mkAddrOf except if the type of lval is an array then it uses
StartOf. This is the right operation for getting a pointer to the start
of the storage denoted by lval.
* Equivalent to [mkMem] for terms.
* Make an expression that is a string constant (of pointer type)
* Construct a cast when having the old type of the expression. If the new
type is the same as the old type, then no cast is added, unless [force]
is [true] (default is [false])
@modify Fluorine-20130401 add [force] argument
* Equivalent to [stripCasts] for terms.
* Removes info wrappers and return underlying expression
* Removes casts and info wrappers and return underlying expression
* Removes casts and info wrappers,except last info wrapper, and return
underlying expression
* Extracts term information in an expression information
* Constructs a term from a term node and an expression information
* Map some function on underlying expression if Info or else on expression
* Apply some function on underlying expression if Info or else on expression
* Compute the type of an expression.
* Returns the type pointed by the given type. Asserts it is a pointer type.
* Returns the type of the array elements of the given type.
Asserts it is an array type.
* Returns [true] whenever the type contains only arithmetic types
* @return true if the given variable appears in the expression.
********************************************
********************************************
* Construct a block with no attributes, given a list of statements
* Construct a block with no attributes, given a list of statements and
wrap it into the Cfg.
* A instr to serve as a placeholder
* A statement consisting of just [dummyInstr].
@plugin development guide
* Make a while loop. Can contain Break or Continue
* Make a for loop for(start; guard; next) \{ ... \}. The body can
contain Break but not Continue !!!
* creates a block with empty attributes from an unspecified sequence.
* Create an expression equivalent to the condition to enter a case branch.
*************************************************************************
*************************************************************************
* Various classes of attributes
* Attribute of a type
* Add a new attribute with a specified class
* Remove an attribute previously registered.
* Return the class of an attribute.
* Partition the attributes into classes:name attributes and type attributes
* Remove all attributes with the given name. Maintains the attributes in
sorted order.
* Remove all attributes with names appearing in the string list.
* Maintains the attributes in sorted order
* Remove any attribute appearing somewhere in the fully expanded
version of the type.
@since Oxygen-20120901
* Retains attributes with the given name
* True if the named attribute appears in the attribute list. The list of
attributes must be sorted.
* returns the complete name for an attribute annotation.
* Returns the name of an attribute.
* Returns the list of parameters associated to an attribute. The list is empty if there
is no such attribute or it has no parameters at all.
* Returns all the attributes contained in a type. This requires a traversal
of the type structure, in case of composite, enumeration and named types
* Returns the attributes of a type.
* Sets the attributes of the type to the given list. Previous attributes
are discarded.
* Add some attributes to a type
* Remove all attributes with the given names from a type. Note that this
does not remove attributes from typedef and tag definitions, just from
their uses (unfolding the type definition when needed).
It only removes attributes of topmost type, i.e. does not
recurse under pointers, arrays, ...
* same as above, but remove any existing attribute from the type.
@since Magnesium-20151001
* Remove all attributes relative to const, volatile and restrict attributes
when building a C cast
@since Oxygen-20120901
* Remove all attributes relative to const, volatile and restrict attributes
when building a logic cast
@since Oxygen-20120901
* given some attributes on an array type, split them into those that belong
to the type of the elements of the array (currently, qualifiers such as
const and volatile), and those that must remain on the array, in that
order
@since Oxygen-20120901
* Convert an expression into an attrparam, if possible. Otherwise raise
NotAnAttrParam with the offending subexpression
*************************************************************************
*************************************************************************
* Different visiting actions. 'a will be instantiated with [exp], [instr],
etc.
@plugin development guide
* Do not visit the children. Return the node as it is.
@plugin development guide
* Continue with the children of this node. Rebuild the node on
return if any of the children changes (use == test).
@plugin development guide
* visit the children, and apply the given function to the result.
@plugin development guide
* visit the children, but only to make the necessary copies
(only useful for copy visitor).
@plugin development guide
* same as JustCopy + applies the given function to the result.
@plugin development guide
* Replace the expression with the given one.
@plugin development guide
* applies the expression to the function and gives back the result.
Useful to insert some actions in an inheritance chain.
@plugin development guide
* @since Carbon-20101201
returns a dummy behavior with the default name [Cil.default_behavior_name].
invariant: [b_assumes] must always be
empty for behavior named [Cil.default_behavior_name]
* @since Carbon-20101201
* @since Carbon-20101201
* @since Carbon-20101201
*************************************************************************
*************************************************************************
* true iff the behavior is a copy behavior.
* resets the internal tables used by the given visitor_behavior. If you use
fresh instances of visitor for each round of transformation, this should
not be needed. In place modifications do not need that at all.
* retrieve the representative of a given varinfo in the current
state of the visitor
* @plugin development guide
* @plugin development guide
* retrieve the original representative of a given copy of a varinfo
in the current state of the visitor.
* change the reference of a given new varinfo in the current
state of the visitor. Use with care
* finds a binding in new project for the given varinfo, creating one
if it does not already exists.
* the kind of behavior expected for the behavior.
@plugin development guide
* Project the visitor operates on. Non-nil for copy visitor.
@since Oxygen-20120901
* a visitor who only does copies of the nodes according to [behavior]
* visit a whole file.
@plugin development guide
* Invoked on each expression occurrence. The subtrees are the
subexpressions, the types (for a [Cast] or [SizeOf] expression) or the
variable use.
@plugin development guide
* Invoked on each lvalue occurrence
* Invoked on each offset occurrence that is *not* as part of an
initializer list specification, i.e. in an lval or recursively inside an
offset.
@plugin development guide
* Invoked on each instruction occurrence. The [ChangeTo] action can
replace this instruction with a list of instructions
* Block.
* Function definition. Replaced in place.
* Global (vars, types, etc.)
@plugin development guide
* Initializers for globals, pass the global where this occurs, and the
offset
* declaration of a struct/union
* declaration of an enumeration
* visit the declaration of a field of a structure or union
* visit the declaration of an enumeration item
* Attribute. Each attribute can be replaced by a list
* Attribute parameters.
* Add here instructions while visiting to queue them to preceede the
current statement or instruction being processed. Use this method only
when you are visiting an expression that is inside a function body, or a
statement, because otherwise there will no place for the visitor to place
your instructions.
* Gets the queue of instructions and resets the queue. This is done
automatically for you when you visit statments.
* @plugin development guide
* @plugin development guide
* @plugin development guide
* @plugin development guide
* @plugin development guide
* @plugin development guide
* @plugin development guide
* @plugin development guide
*
@since Fluorine-20130401
the child of an identified predicate is treated as a predicate named:
if you wish to modify names, you only have to override vpredicate_named,
not both videntified_predicate and vpredicate_named.
*@since Oxygen-20120901
*@since Oxygen-20120901
*@since Oxygen-20120901
* fill the global environment tables at the end of a full copy in a
new project.
@plugin development guide
* get the queue of actions to be performed at the end of a full copy.
@plugin development guide
*/*
*/*
* generic visitor, parameterized by its copying behavior.
Traverses the CIL tree without modifying anything
* Default in place visitor doing nothing and operating on current project.
* same as above, but can return a list of nodes
* Visit a file. This will re-cons all globals TWICE (so that it is
* tail-recursive). Use {!Cil.visitCilFileSameGlobals} if your visitor will
* not change the list of globals.
@plugin development guide
* Same thing, but the result is ignored. The given visitor must thus be
an inplace visitor. Nothing is done if the visitor is a copy visitor.
@plugin development guide
* A visitor for the whole file that does not change the globals (but maybe
* changes things inside the globals). Use this function instead of
* {!Cil.visitCilFile} whenever appropriate because it is more efficient for
* long files.
@plugin development guide
* Visit a global
* Visit a function definition
Visit an expression
* Visit an lvalue
* Visit an lvalue or recursive offset
* Visit an initializer offset
* Visit an instruction
* Visit a statement
* Visit a block
* Visit a type
* Visit a variable declaration
* Visit an initializer, pass also the global to which this belongs and the
* offset.
* Visit a list of attributes
* @since Oxygen-20120901
* @since Oxygen-20120901
* @since Oxygen-20120901
* visit identified_term.
@since Oxygen-20120901
And some generic visitors. The above are built with these
*************************************************************************
*************************************************************************
* A visitor that does constant folding. Pass as argument whether you want
* machine specific simplifications to be done, or not.
*************************************************************************
*************************************************************************
* A reference to the current location. If you are careful to set this to
* the current location then you can use some built-in logging functions that
* will print the location.
* Pretty-print [(Cil.CurrentLoc.get ())]
* @return a dummy specification
* @return true if the given spec is empty.
* @return true if the given behavior is empty.
*************************************************************************
*************************************************************************
* Assign unique names to local variables. This might be necessary after you
transformed the code and added or renamed some new variables. Names are not
used by CIL internally, but once you print the file out the compiler
downstream might be confused. You might have added a new global that happens
to have the same name as a local in some function. Rename the local to
ensure that there would never be confusion. Or, viceversa, you might have
added a local with a name that conflicts with a global
*************************************************************************
*************************************************************************
*************************************************************************
*************************************************************************
* Create a fresh size cache with [Not_Computed]
* Give the unsigned kind corresponding to any integer kind
* Give the signed kind corresponding to any integer kind
* The float kind for a given size in bytes. Raises Not_found
* if no such kind exists
* Returns the number of bytes (resp. bits) to represent the given integer
kind depending on the current machdep.
* Returns the signedness of the given integer kind depending
on the current machdep.
* Returns a unique number representing the integer
conversion rank.
* Returns a unique number representing the floating-point conversion rank.
@since Oxygen-20120901
* Represents an integer as for a given kind.
* Returns a flag saying whether the value was changed
* during truncation (because it was too large to fit in k).
* Returns the maximal value representable in a signed integer type of the
given size (in bits)
* Returns the smallest value representable in a signed integer type of the
given size (in bits)
* Returns the maximal value representable in a unsigned integer type of the
given size (in bits)
* True if the integer fits within the kind's range
* raised by {!intKindForValue}.
* Generate an {!Cil_types.exp} to be used in case of errors.
* Generate an {!Cil_types.instr} to be used in case of errors.
* Generate a {!Cil_types.global} to be used in case of errors.
* Like map but try not to make a copy of the list
* same as mapNoCopy for options
* Like map but each call can return a list. Try not to make a copy of the
list
*************************************************************************
*************************************************************************
* The type of argument for the interpreter
* For array lengths
* For arguments in a function call
* For a formal argument
* For formal argument lists
* For the ellipsis in a function type
*************************************************************************
*************************************************************************
* Convert a C variable into the corresponding logic variable.
The returned logic variable is unique for a given C variable.
* Make a temporary variable to use in annotations
* The constant logic term -1.
* The given constant logic term
* Bind all free variables with an universal quantifier
* extract [varinfo] elements from an [exp]
* extract [varinfo] elements from an [lval]
* extract [logic_var] elements from a [term]
* extract [logic_var] elements from a [predicate]
* extract [logic_label] elements from a [code_annotation]
* extract [logic_label] elements from a [term]
* extract [logic_label] elements from a [pred]
*/*
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
Copyright ( C ) 2001 - 2003
< >
< >
< >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . The names of the contributors may not be used to endorse or
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
File modified by CEA ( Commissariat à l'énergie atomique et aux
and INRIA ( Institut National de Recherche en Informatique
open Cil_types
open Cil_datatype
* { 2 Builtins management }
module Frama_c_builtins:
State_builder.Hashtbl with type key = string and type data = Cil_types.varinfo
val is_builtin: Cil_types.varinfo -> bool
val is_unused_builtin: Cil_types.varinfo -> bool
val is_special_builtin: string -> bool
val add_special_builtin: string -> unit
val add_special_builtin_family: (string -> bool) -> unit
val init_builtins: unit -> unit
val initCIL: initLogicBuiltins:(unit -> unit) -> Cil_types.mach -> unit
* { 2 Customization }
type theMachine = private
{ mutable useLogicalOperators: bool;
* Whether to use the logical operands LAnd and LOr . By default , do not
use them because they are unlike other expressions and do not
evaluate both of their operands
use them because they are unlike other expressions and do not
evaluate both of their operands *)
mutable theMachine: mach;
mutable insertImplicitCasts: bool;
mutable stringLiteralType: typ;
mutable upointKind: ikind
mutable upointType: typ;
mutable wcharType: typ;
mutable ptrdiffType: typ;
mutable typeOfSizeOf: typ;
mutable kindOfSizeOf: ikind;
* The integer kind of { ! } .
}
val theMachine : theMachine
val selfMachine: State.t
val selfMachine_is_computed: ?project:Project.project -> unit -> bool
val msvcMode: unit -> bool
val gccMode: unit -> bool
* { 2 Values for manipulating globals }
* Make an empty function from an existing global varinfo .
@since
@since Nitrogen-20111001 *)
val emptyFunctionFromVI: varinfo -> fundec
val emptyFunction: string -> fundec
val setFormals: fundec -> varinfo list -> unit
val getReturnType: typ -> typ
* Change the return type of the function passed as 1st argument to be
the type passed as 2nd argument .
the type passed as 2nd argument. *)
val setReturnTypeVI: varinfo -> typ -> unit
val setReturnType: fundec -> typ -> unit
* Set the types of arguments and results as given by the function type
* passed as the second argument . Will not copy the names from the function
* type to the formals
* passed as the second argument. Will not copy the names from the function
* type to the formals *)
val setFunctionType: fundec -> typ -> unit
val setFunctionTypeMakeFormals: fundec -> typ -> unit
* Update the smaxid after you have populated with locals and formals
* ( unless you constructed those using { ! } or
* { ! } .
* (unless you constructed those using {!Cil.makeLocalVar} or
* {!Cil.makeTempVar}. *)
val setMaxId: fundec -> unit
* Strip const attribute from the type . This is useful for
any type used as the type of a local variable which may be assigned .
Note that the type attributes are mutated in place .
@since
any type used as the type of a local variable which may be assigned.
Note that the type attributes are mutated in place.
@since Nitrogen-20111001
*)
val stripConstLocalType : Cil_types.typ -> Cil_types.typ
val selfFormalsDecl: State.t
val makeFormalsVarDecl: (string * typ * attributes) -> varinfo
* Update the formals of a function declaration from its identifier and its
type . For a function definition , use { ! } .
Do nothing if the type is not a function type or if the list of
argument is empty .
type. For a function definition, use {!Cil.setFormals}.
Do nothing if the type is not a function type or if the list of
argument is empty.
*)
val setFormalsDecl: varinfo -> typ -> unit
val removeFormalsDecl: varinfo -> unit
* replace to formals of a function declaration with the given
list of varinfo .
list of varinfo.
*)
val unsafeSetFormalsDecl: varinfo -> varinfo list -> unit
val iterFormalsDecl: (varinfo -> varinfo list -> unit) -> unit
val getFormalsDecl: varinfo -> varinfo list
val dummyFile: file
* Get the global initializer and create one if it does not already exist .
When it creates a global initializer it attempts to place a call to it in
the main function named by the optional argument ( default " main " ) .
@deprecated using this function is incorrect since it modifies the
current AST ( see Plug - in Development Guide , Section " Using Projects " ) .
When it creates a global initializer it attempts to place a call to it in
the main function named by the optional argument (default "main").
@deprecated using this function is incorrect since it modifies the
current AST (see Plug-in Development Guide, Section "Using Projects"). *)
val getGlobInit: ?main_name:string -> file -> fundec
val iterGlobals: file -> (global -> unit) -> unit
val foldGlobals: file -> ('a -> global -> 'a) -> 'a -> 'a
val mapGlobals: file -> (global -> global) -> unit
val findOrCreateFunc: file -> string -> typ -> varinfo
module Sid: sig
val next: unit -> int
end
module Eid: sig
val next: unit -> int
end
val new_exp: loc:location -> exp_node -> exp
* performs a deep copy of an expression ( especially , avoid eid sharing ) .
@since
@since Nitrogen-20111001
*)
val copy_exp: exp -> exp
* creates an expression with a dummy i d.
Use with caution , { i i.e. } not on expressions that may be put in the AST .
Use with caution, {i i.e.} not on expressions that may be put in the AST.
*)
val dummy_exp: exp_node -> exp
val is_case_label: label -> bool
val pushGlobal: global -> types: global list ref
-> variables: global list ref -> unit
val invalidStmt: stmt
* A list of the built - in functions for the current compiler ( GCC or
* MSVC , depending on [ ! msvcMode ] ) . Maps the name to the
* result and argument types , and whether it is vararg .
* Initialized by { ! Cil.initCIL }
*
* This map replaces [ gccBuiltins ] and [ msvcBuiltins ] in previous
* versions of CIL .
* MSVC, depending on [!msvcMode]). Maps the name to the
* result and argument types, and whether it is vararg.
* Initialized by {!Cil.initCIL}
*
* This map replaces [gccBuiltins] and [msvcBuiltins] in previous
* versions of CIL.*)
module Builtin_functions :
State_builder.Hashtbl with type key = string
and type data = typ * typ list * bool
val builtinLoc: location
* Returns a location that ranges over the two locations in arguments .
val range_loc: location -> location -> location
* { 2 Values for manipulating initializers }
* Make a initializer for zero - ing a data type
val makeZeroInit: loc:location -> typ -> init
* Fold over the list of initializers in a Compound ( not also the nested
* ones ) . [ doinit ] is called on every present initializer , even if it is of
* compound type . The parameters of [ doinit ] are : the offset in the compound
* ( this is [ Field(f , ) ] or [ Index(i , ) ] ) , the initializer
* value , expected type of the initializer value , accumulator . In the case of
* arrays there might be missing zero - initializers at the end of the list .
* These are scanned only if [ implicit ] is true . This is much like
* [ List.fold_left ] except we also pass the type of the initializer .
* This is a good way to use it to scan even nested initializers :
{ v
let rec myInit ( lv : lval ) ( i : init ) ( acc : ' a ) : ' a =
match i with
SingleInit e - > ... do something with lv and e and acc ...
| CompoundInit ( ct , ) - >
foldLeftCompound ~implicit : false
~doinit:(fun off ' i ' t ' acc - >
myInit ( addOffsetLval lv off ' ) i ' acc )
~ct : ct
~initl : initl
~acc : acc
v }
* ones). [doinit] is called on every present initializer, even if it is of
* compound type. The parameters of [doinit] are: the offset in the compound
* (this is [Field(f,NoOffset)] or [Index(i,NoOffset)]), the initializer
* value, expected type of the initializer value, accumulator. In the case of
* arrays there might be missing zero-initializers at the end of the list.
* These are scanned only if [implicit] is true. This is much like
* [List.fold_left] except we also pass the type of the initializer.
* This is a good way to use it to scan even nested initializers :
{v
let rec myInit (lv: lval) (i: init) (acc: 'a) : 'a =
match i with
SingleInit e -> ... do something with lv and e and acc ...
| CompoundInit (ct, initl) ->
foldLeftCompound ~implicit:false
~doinit:(fun off' i' t' acc ->
myInit (addOffsetLval lv off') i' acc)
~ct:ct
~initl:initl
~acc:acc
v}
*)
val foldLeftCompound:
implicit:bool ->
doinit: (offset -> init -> typ -> 'a -> 'a) ->
ct: typ ->
initl: (offset * init) list ->
acc: 'a -> 'a
* { 2 Values for manipulating types }
val voidType: typ
val isVoidType: typ -> bool
val isVoidPtrType: typ -> bool
val intType: typ
val uintType: typ
val longType: typ
val longLongType: typ
val ulongType: typ
val ulongLongType: typ
* Any unsigned integer type of size 16 bits .
It is equivalent to the ISO C uint16_t type but without using the
corresponding header .
Shall not be called if not such type exists in the current architecture .
@since
It is equivalent to the ISO C uint16_t type but without using the
corresponding header.
Shall not be called if not such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint16_t: unit -> typ
* Any unsigned integer type of size 32 bits .
It is equivalent to the ISO C uint32_t type but without using the
corresponding header .
Shall not be called if not such type exists in the current architecture .
@since
It is equivalent to the ISO C uint32_t type but without using the
corresponding header.
Shall not be called if not such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint32_t: unit -> typ
* Any unsigned integer type of size 64 bits .
It is equivalent to the ISO C uint64_t type but without using the
corresponding header .
Shall not be called if no such type exists in the current architecture .
@since
It is equivalent to the ISO C uint64_t type but without using the
corresponding header.
Shall not be called if no such type exists in the current architecture.
@since Nitrogen-20111001
*)
val uint64_t: unit -> typ
* Any signed integer type of size 128 bits .
It is equivalent to the GCC _ _ int128 type .
Shall not be called if no such type exists in the current architecture .
@since TIS - Kernel 1.30
It is equivalent to the GCC __int128 type.
Shall not be called if no such type exists in the current architecture.
@since TIS-Kernel 1.30
*)
val int128_t: unit -> typ
val charType: typ
val scharType: typ
val ucharType: typ
val charPtrType: typ
val scharPtrType: typ
val ucharPtrType: typ
val charConstPtrType: typ
val voidPtrType: typ
val voidConstPtrType: typ
val intPtrType: typ
val uintPtrType: typ
val floatType: typ
val doubleType: typ
val longDoubleType: typ
val isSignedInteger: typ -> bool
val isUnsignedInteger: typ -> bool
* Creates a ( potentially recursive ) composite type . The arguments are :
* ( 1 ) a boolean indicating whether it is a struct or a union , ( 2 ) the name
* ( always non - empty ) , ( 3 ) a function that when given a representation of the
* structure type constructs the type of the fields recursive type ( the first
* argument is only useful when some fields need to refer to the type of the
* structure itself ) , and ( 4 ) a list of attributes to be associated with the
* composite type . The resulting compinfo has the field " cdefined " only if
* the list of fields is non - empty .
* (1) a boolean indicating whether it is a struct or a union, (2) the name
* (always non-empty), (3) a function that when given a representation of the
* structure type constructs the type of the fields recursive type (the first
* argument is only useful when some fields need to refer to the type of the
* structure itself), and (4) a list of attributes to be associated with the
* composite type. The resulting compinfo has the field "cdefined" only if
* the list of fields is non-empty. *)
(compinfo ->
(string * typ * int option * attributes * location) list) ->
attributes -> compinfo
* Makes a shallow copy of a { ! Cil_types.compinfo } changing the name . It also
copies the fields , and makes sure that the copied field points back to the
copied .
If [ fresh ] is [ true ] ( the default ) , it will also give a fresh i d to the
copy .
copies the fields, and makes sure that the copied field points back to the
copied compinfo.
If [fresh] is [true] (the default), it will also give a fresh id to the
copy.
*)
val copyCompInfo: ?fresh:bool -> compinfo -> string -> compinfo
val missingFieldName: string
val compFullName: compinfo -> string
val isCompleteType: ?allowZeroSizeArrays:bool -> typ -> bool
val isNestedStructWithFlexibleArrayMemberType : typ -> bool
val unrollType: typ -> typ
* Unroll all the TNamed in a type ( even under type constructors such as
* [ TPtr ] , [ TFun ] or [ TArray ] . Does not unroll the types of fields in [ TComp ]
* types . Will collect all attributes
* [TPtr], [TFun] or [TArray]. Does not unroll the types of fields in [TComp]
* types. Will collect all attributes *)
val unrollTypeDeep: typ -> typ
val separateStorageModifiers: attribute list -> attribute list * attribute list
* returns the type of the result of an arithmetic operator applied to
values of the corresponding input types .
@since ( moved from Cabs2cil )
values of the corresponding input types.
@since Nitrogen-20111001 (moved from Cabs2cil)
*)
val arithmeticConversion : Cil_types.typ -> Cil_types.typ -> Cil_types.typ
* performs the usual integral promotions mentioned in C reference manual .
@since ( moved from Cabs2cil )
@since Nitrogen-20111001 (moved from Cabs2cil)
*)
val integralPromotion : Cil_types.typ -> Cil_types.typ
val isCharType: typ -> bool
val isShortType: typ -> bool
val isCharPtrType: typ -> bool
val isCharArrayType: typ -> bool
val isIntegralType: typ -> bool
val isIntegralOrPointerType: typ -> bool
* True if the argument is an integral type ( i.e. integer or enum ) , either
C or mathematical one
C or mathematical one *)
val isLogicIntegralType: logic_type -> bool
val isFloatingType: typ -> bool
val isLogicFloatType: logic_type -> bool
val isLogicRealOrFloatType: logic_type -> bool
val isLogicRealType: logic_type -> bool
val isArithmeticType: typ -> bool
val isArithmeticOrPointerType: typ -> bool
* True if the argument is a logic arithmetic type ( i.e. integer , enum or
floating point , either C or mathematical one
floating point, either C or mathematical one *)
val isLogicArithmeticType: logic_type -> bool
val isPointerType: typ -> bool
val isTypeTagType: logic_type -> bool
val isFunctionType: typ -> bool
* True if the argument denotes the type of ... in a variadic function .
@since moved from cabs2cil
@since Nitrogen-20111001 moved from cabs2cil *)
val isVariadicListType: typ -> bool
val argsToList:
(string * typ * attributes) list option -> (string * typ * attributes) list
val isArrayType: typ -> bool
val isKnownSizeArrayType: typ -> bool
val isUnspecifiedSizeArrayType: typ -> bool
val isStructOrUnionType: typ -> bool
exception LenOfArray
* Call to compute the array length as present in the array type , to an
* integer . Raises { ! . LenOfArray } if not able to compute the length , such
* as when there is no length or the length is not a constant .
* integer. Raises {!Cil.LenOfArray} if not able to compute the length, such
* as when there is no length or the length is not a constant. *)
val lenOfArray: exp option -> int
val lenOfArray64: exp option -> Integer.t
* Return a named fieldinfo in , or raise Not_found
val getCompField: compinfo -> string -> fieldinfo
type existsAction =
* Scans a type by applying the function on all elements .
When the function returns ExistsTrue , the scan stops with
true . When the function returns ExistsFalse then the current branch is not
scanned anymore . Care is taken to
apply the function only once on each composite type , thus avoiding
circularity . When the function returns ExistsMaybe then the types that
construct the current type are scanned ( e.g. the base type for TPtr and
TArray , the type of fields for a TComp , etc ) .
When the function returns ExistsTrue, the scan stops with
true. When the function returns ExistsFalse then the current branch is not
scanned anymore. Care is taken to
apply the function only once on each composite type, thus avoiding
circularity. When the function returns ExistsMaybe then the types that
construct the current type are scanned (e.g. the base type for TPtr and
TArray, the type of fields for a TComp, etc). *)
val existsType: (typ -> existsAction) -> typ -> bool
val splitFunctionType:
typ -> typ * (string * typ * attributes) list option * bool * attributes
val splitFunctionTypeVI:
varinfo ->
typ * (string * typ * attributes) list option * bool * attributes
* Return a call instruction corresponding to the the function call related
to the GCC cleanup attribute .
The semantics is : this instruction has to be executed as soon as the
variable escapes its block scope . This semantics is desugared
during Oneret .
If there is no such attribute or a non GCC machdep is selected ,
it returns None .
The returned statement is not is the AST .
For any given varinfo the same physical statement will
be returned . It needs to be copied before it is inserted in
the AST .
to the GCC cleanup attribute.
The semantics is: this instruction has to be executed as soon as the
variable escapes its block scope. This semantics is desugared
during Oneret.
If there is no such attribute or a non GCC machdep is selected,
it returns None.
The returned statement is not is the AST.
For any given varinfo the same physical statement will
be returned. It needs to be copied before it is inserted in
the AST.
*)
val get_cleanup_stmt: varinfo -> stmt option
* LVALUES
* Make a varinfo . Use this ( rarely ) to make a raw varinfo . Use other
functions to make locals ( { ! } or { ! Cil.makeFormalVar } or
{ ! } ) and globals ( { ! Cil.makeGlobalVar } ) . Note that this
function will assign a new identifier .
The [ temp ] argument defaults to [ false ] , and corresponds to the
[ vtemp ] field in type { ! Cil_types.varinfo } .
The [ source ] argument defaults to [ true ] , and corresponds to the field
[ vsource ] .
The first unnmamed argument specifies whether the varinfo is for a global and
the second is for formals .
functions to make locals ({!Cil.makeLocalVar} or {!Cil.makeFormalVar} or
{!Cil.makeTempVar}) and globals ({!Cil.makeGlobalVar}). Note that this
function will assign a new identifier.
The [temp] argument defaults to [false], and corresponds to the
[vtemp] field in type {!Cil_types.varinfo}.
The [source] argument defaults to [true], and corresponds to the field
[vsource] .
The first unnmamed argument specifies whether the varinfo is for a global and
the second is for formals. *)
val makeVarinfo:
?source:bool -> ?temp:bool -> bool -> bool -> string -> typ -> varinfo
* Make a formal variable for a function declaration . Insert it in both the
sformals and the type of the function . You can optionally specify where to
insert this one . If where = " ^ " then it is inserted first . If where = " $ "
then it is inserted last . Otherwise where must be the name of a formal
after which to insert this . By default it is inserted at the end .
sformals and the type of the function. You can optionally specify where to
insert this one. If where = "^" then it is inserted first. If where = "$"
then it is inserted last. Otherwise where must be the name of a formal
after which to insert this. By default it is inserted at the end.
*)
val makeFormalVar: fundec -> ?where:string -> string -> typ -> varinfo
* Make a local variable and add it to a function 's slocals and to the given
block ( only if insert = true , which is the default ) .
Make sure you know what you are doing if you set [ insert = false ] .
[ temp ] is passed to { ! Cil.makeVarinfo } .
The variable is attached to the toplevel block if [ scope ] is not specified .
@since This function will strip const attributes
of its type in place in order for local variable to be assignable at
least once .
block (only if insert = true, which is the default).
Make sure you know what you are doing if you set [insert=false].
[temp] is passed to {!Cil.makeVarinfo}.
The variable is attached to the toplevel block if [scope] is not specified.
@since Nitrogen-20111001 This function will strip const attributes
of its type in place in order for local variable to be assignable at
least once.
*)
val makeLocalVar:
fundec -> ?scope:block -> ?temp:bool -> ?insert:bool
-> string -> typ -> varinfo
val makeTempVar: fundec -> ?insert:bool -> ?name:string -> ?descr:string ->
?descrpure:bool -> typ -> varinfo
val makeGlobalVar: ?source:bool -> ?temp:bool -> string -> typ -> varinfo
val copyVarinfo: varinfo -> string -> varinfo
val update_var_type: varinfo -> typ -> unit
* Is an lvalue a bitfield ?
val isBitfield: lval -> bool
val lastOffset: offset -> offset
val addOffsetLval: offset -> lval -> lval
val addOffset: offset -> offset -> offset
* Remove ONE offset from the end of an lvalue . Returns the lvalue with the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffsetLval: lval -> lval * offset
* Remove ONE offset from the end of an offset sequence . Returns the
* trimmed offset and the final offset . If the final offset is [ NoOffset ]
* then the original [ lval ] did not have an offset .
* trimmed offset and the final offset. If the final offset is [NoOffset]
* then the original [lval] did not have an offset. *)
val removeOffset: offset -> offset * offset
val typeOfLval: lval -> typ
val typeOfLhost: lhost -> typ
val typeOfTermLval: term_lval -> logic_type
val typeOffset: typ -> offset -> typ
val typeTermOffset: logic_type -> term_offset -> logic_type
val typeOfInit: init -> typ
* { 2 Values for manipulating expressions }
Construct integer constants
* 0
val zero: loc:Location.t -> exp
* 1
val one: loc:Location.t -> exp
val mone: loc:Location.t -> exp
val kinteger64: loc:location -> ?repr:string -> ?kind:ikind -> Integer.t -> exp
* Construct an integer of a given kind . Converts the integer to int64 and
* then uses kinteger64 . This might truncate the value if you use a kind
* that can not represent the given integer . This can only happen for one of
* the or Short kinds
* then uses kinteger64. This might truncate the value if you use a kind
* that cannot represent the given integer. This can only happen for one of
* the Char or Short kinds *)
val kinteger: loc:location -> ikind -> int -> exp
* Construct an integer of kind IInt . You can use this always since the
OCaml integers are 31 bits and are guaranteed to fit in an IInt
OCaml integers are 31 bits and are guaranteed to fit in an IInt *)
val integer: loc:location -> int -> exp
val kfloat: loc:location -> fkind -> float -> exp
val isInteger: exp -> Integer.t option
val isConstant: exp -> bool
val isIntegerConstant: exp -> bool
val isConstantOffset: offset -> bool
* True if the given expression is a ( possibly cast'ed ) integer or character
constant with value zero
constant with value zero *)
val isZero: exp -> bool
val isLogicZero: term -> bool
val isLogicNull: term -> bool
val reduce_multichar: Cil_types.typ -> int64 list -> int64
val interpret_character_constant:
int64 list -> Cil_types.constant * Cil_types.typ
* Given the character c in a ( CChr c ) , sign - extend it to 32 bits .
( This is the official way of interpreting character constants , according to
ISO C 6.4.4.4.10 , which says that character constants are chars cast to ints )
Returns CInt64(sign - extened c , IInt , None )
(This is the official way of interpreting character constants, according to
ISO C 6.4.4.4.10, which says that character constants are chars cast to ints)
Returns CInt64(sign-extened c, IInt, None) *)
val charConstToInt: char -> Integer.t
val charConstToIntConstant: char -> constant
* Do constant folding on an expression . If the first argument is [ true ] then
will also compute compiler - dependent expressions such as sizeof .
See also { ! Cil.constFoldVisitor } , which will run constFold on all
expressions in a given AST node .
will also compute compiler-dependent expressions such as sizeof.
See also {!Cil.constFoldVisitor}, which will run constFold on all
expressions in a given AST node. *)
val constFold: bool -> exp -> exp
val constFoldToInt: ?machdep:bool -> exp -> Integer.t option
val constFoldTermNodeAtTop: term_node -> term_node
* Do constant folding on an term .
If the first argument is true then
will also compute compiler - dependent expressions such as [ sizeof ]
and [ alignof ] .
If the first argument is true then
will also compute compiler-dependent expressions such as [sizeof]
and [alignof]. *)
val constFoldTerm: bool -> term -> term
* Do constant folding on a binary operation . The bulk of the work done by
[ constFold ] is done here . If the second argument is true then
will also compute compiler - dependent expressions such as [ sizeof ] .
[constFold] is done here. If the second argument is true then
will also compute compiler-dependent expressions such as [sizeof]. *)
val constFoldBinOp: loc:location -> bool -> binop -> exp -> exp -> typ -> exp
* [ true ] if the two constant are equal .
@since
@since Nitrogen-20111001
*)
val compareConstant: constant -> constant -> bool
val increm: exp -> int -> exp
val increm64: exp -> Integer.t -> exp
val var: varinfo -> lval
* Creates an expr representing the variable .
@since
@since Nitrogen-20111001
*)
val evar: ?loc:location -> varinfo -> exp
* Make an . Given an lvalue of type T will give back an expression of
type ptr(T ) . It optimizes somewhat expressions like " & v " and " & v[0 ] "
type ptr(T). It optimizes somewhat expressions like "& v" and "& v[0]" *)
val mkAddrOf: loc:location -> lval -> exp
val mkAddrOfVi: varinfo -> exp
val mkAddrOrStartOf: loc:location -> lval -> exp
* Make a Mem , while optimizing . The type of the addr must be
TPtr(t ) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply . You must do the conversion yourself using
StartOf
TPtr(t) and the type of the resulting lval is t. Note that in CIL the
implicit conversion between an array and the pointer to the first
element does not apply. You must do the conversion yourself using
StartOf *)
val mkMem: addr:exp -> off:offset -> lval
* makes a binary operation and performs const folding . Inserts
casts between arithmetic types as needed , or between pointer
types , but do not attempt to cast pointer to int or
vice - versa . Use appropriate binop ( PlusPI & friends ) for that .
casts between arithmetic types as needed, or between pointer
types, but do not attempt to cast pointer to int or
vice-versa. Use appropriate binop (PlusPI & friends) for that. *)
val mkBinOp: loc:location -> binop -> exp -> exp -> exp
val mkTermMem: addr:term -> off:term_offset -> term_lval
val mkString: loc:location -> string -> exp
* [ true ] if both types are not equivalent .
if [ force ] is [ true ] , returns [ true ] whenever both types are not equal
( modulo typedefs ) . If [ force ] is [ false ] ( the default ) , other equivalences
are considered , in particular between an enum and its representative
integer type .
added [ force ] argument
if [force] is [true], returns [true] whenever both types are not equal
(modulo typedefs). If [force] is [false] (the default), other equivalences
are considered, in particular between an enum and its representative
integer type.
@modify Fluorine-20130401 added [force] argument
*)
val need_cast: ?force:bool -> typ -> typ -> bool
val mkCastT: ?force:bool -> e:exp -> oldt:typ -> newt:typ -> exp
* Like { ! Cil.mkCastT } but uses to get [ oldt ]
val mkCast: ?force:bool -> e:exp -> newt:typ -> exp
val stripTermCasts: term -> term
* Removes casts from this expression , but ignores casts within
other expression constructs . So we delete the ( A ) and ( B ) casts from
" ( A)(B)(x + ( C)y ) " , but leave the ( C ) cast .
other expression constructs. So we delete the (A) and (B) casts from
"(A)(B)(x + (C)y)", but leave the (C) cast. *)
val stripCasts: exp -> exp
* Same as stripCasts but only remove casts to void and stop at the first
non - void cast .
non-void cast. *)
val stripCastsToVoid: exp -> exp
val stripInfo: exp -> exp
val stripCastsAndInfo: exp -> exp
val stripCastsButLastInfo: exp -> exp
val exp_info_of_term: term -> exp_info
val term_of_exp_info: location -> term_node -> exp_info -> term
val map_under_info: (exp -> exp) -> exp -> exp
val app_under_info: (exp -> unit) -> exp -> unit
val typeOf: exp -> typ
val typeOf_pointed : typ -> typ
val typeOf_array_elem : typ -> typ
val is_fully_arithmetic: typ -> bool
* Convert a string representing a C integer literal to an expression .
Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL .
Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL.
*)
val parseInt: string -> Integer.t
val parseIntExp: loc:location -> string -> exp
val parseIntLogic: loc:location -> string -> term
* Convert a string representing a C integer literal to an expression .
Handles the prefixes 0x and 0 and the suffixes L , U , UL , LL , ULL
Handles the prefixes 0x and 0 and the suffixes L, U, UL, LL, ULL *)
val appears_in_expr: varinfo -> exp -> bool
* { 3 Values for manipulating statements }
* Construct a statement , given its kind . Initialize the [ sid ] field to -1
if [ valid_sid ] is false ( the default ) ,
or to a valid if [ valid_sid ] is true ,
and [ labels ] , [ succs ] and [ ] to the empty list
if [valid_sid] is false (the default),
or to a valid sid if [valid_sid] is true,
and [labels], [succs] and [preds] to the empty list *)
val mkStmt: ?ghost:bool -> ?valid_sid:bool -> stmtkind -> stmt
make the [ new_stmtkind ] changing the CFG relatively to [ ref_stmt ]
val mkStmtCfg: before:bool -> new_stmtkind:stmtkind -> ref_stmt:stmt -> stmt
val mkBlock: stmt list -> block
val mkStmtCfgBlock: stmt list -> stmt
* Construct a statement consisting of just one instruction
See { ! Cil.mkStmt } for the signification of the optional args .
See {!Cil.mkStmt} for the signification of the optional args.
*)
val mkStmtOneInstr: ?ghost:bool -> ?valid_sid:bool -> instr -> stmt
* Try to compress statements so as to get maximal basic blocks .
* use this instead of List.@ because you get fewer basic blocks
* use this instead of List.@ because you get fewer basic blocks *)
: stmt list - > stmt list
* Returns an empty statement ( of kind [ Instr ] ) . See [ mkStmt ] for [ ghost ] and
[ valid_sid ] arguments .
adds the [ valid_sid ] optional argument .
[valid_sid] arguments.
@modify Neon-20130301 adds the [valid_sid] optional argument. *)
val mkEmptyStmt: ?ghost:bool -> ?valid_sid:bool -> ?loc:location -> unit -> stmt
val dummyInstr: instr
val dummyStmt: stmt
val mkWhile: guard:exp -> body:stmt list -> stmt list
* Make a for loop for(i = start ; i < past ; i + = incr ) \ { ... \ } . The body
can contain Break but not Continue . Can be used with i a pointer
or an integer . Start and done must have the same type but incr
must be an integer
can contain Break but not Continue. Can be used with i a pointer
or an integer. Start and done must have the same type but incr
must be an integer *)
val mkForIncr: iter:varinfo -> first:exp -> stopat:exp -> incr:exp
-> body:stmt list -> stmt list
val mkFor: start:stmt list -> guard:exp -> next: stmt list ->
body: stmt list -> stmt list
val block_from_unspecified_sequence:
(stmt * lval list * lval list * lval list * stmt ref list) list -> block
val mkCase_condition:
loc:Cil_types.location ->
case:Cil_types.case -> switch:Cil_types.exp -> Cil_types.exp
* { 2 Values for manipulating attributes }
type attributeClass =
AttrName of bool
* Attribute of a name . If argument is true and we are on MSVC then
the attribute is printed using _ _ as part of the storage
specifier
the attribute is printed using __declspec as part of the storage
specifier *)
val registerAttribute: string -> attributeClass -> unit
val removeAttribute: string -> unit
val attributeClass: string -> attributeClass
val partitionAttributes: default:attributeClass ->
AttrType
* Add an attribute . Maintains the attributes in sorted order of the second
argument
argument *)
val addAttribute: attribute -> attributes -> attributes
* Add a list of attributes . Maintains the attributes in sorted order . The
second argument must be sorted , but not necessarily the first
second argument must be sorted, but not necessarily the first *)
val addAttributes: attribute list -> attributes -> attributes
val dropAttribute: string -> attributes -> attributes
val dropAttributes: string list -> attributes -> attributes
* Remove attributes whose name appears in the first argument that are
present anywhere in the fully expanded version of the type .
@since Oxygen-20120901
present anywhere in the fully expanded version of the type.
@since Oxygen-20120901
*)
val typeDeepDropAttributes: string list -> typ -> typ
val typeDeepDropAllAttributes: typ -> typ
val filterAttributes: string -> attributes -> attributes
val hasAttribute: string -> attributes -> bool
val mkAttrAnnot: string -> string
val attributeName: attribute -> string
val findAttribute: string -> attribute list -> attrparam list list
val typeAttrs: typ -> attribute list
val typeAttr: typ -> attribute list
val setTypeAttrs: typ -> attributes -> typ
val typeAddAttributes: attribute list -> typ -> typ
val typeRemoveAttributes: string list -> typ -> typ
val typeRemoveAllAttributes: typ -> typ
val typeHasAttribute: string -> typ -> bool
* Does the type have the given attribute . Does
not recurse through pointer types , nor inside function prototypes .
@since Sodium-20150201
not recurse through pointer types, nor inside function prototypes.
@since Sodium-20150201 *)
val typeHasQualifier: string -> typ -> bool
* Does the type have the given qualifier . Handles the case of arrays , for
which the qualifiers are actually carried by the type of the elements .
It is always correct to call this function instead of { ! typeHasAttribute } .
For l - values , both functions return the same results , as l - values can not
have array type .
@since Sodium-20150201
which the qualifiers are actually carried by the type of the elements.
It is always correct to call this function instead of {!typeHasAttribute}.
For l-values, both functions return the same results, as l-values cannot
have array type.
@since Sodium-20150201 *)
val typeHasAttributeDeep: string -> typ -> bool
* Does the type or one of its subtypes have the given attribute . Does
not recurse through pointer types , nor inside function prototypes .
@since Oxygen-20120901
not recurse through pointer types, nor inside function prototypes.
@since Oxygen-20120901 *)
* Remove all attributes relative to const , volatile and restrict attributes
@since
@since Nitrogen-20111001
*)
val type_remove_qualifier_attributes: typ -> typ
*
remove also qualifiers under Ptr and Arrays
@since Sodium-20150201
remove also qualifiers under Ptr and Arrays
@since Sodium-20150201
*)
val type_remove_qualifier_attributes_deep: typ -> typ
val type_remove_attributes_for_c_cast: typ -> typ
val type_remove_attributes_for_logic_type: typ -> typ
* retains attributes corresponding to type qualifiers ( 6.7.3 )
val filter_qualifier_attributes: attributes -> attributes
val splitArrayAttributes: attributes -> attributes * attributes
val bitfield_attribute_name: string
* Name of the attribute that is automatically inserted ( with an [ AINT size ]
argument when querying the type of a field that is a bitfield
argument when querying the type of a field that is a bitfield *)
val expToAttrParam: exp -> attrparam
exception NotAnAttrParam of exp
* { 2 The visitor }
type 'a visitAction =
| DoChildrenPost of ('a -> 'a)
| JustCopyPost of ('a -> 'a)
| ChangeToPost of 'a * ('a -> 'a)
| ChangeDoChildrenPost of 'a * ('a -> 'a)
* First consider that the entire exp is replaced by the first parameter . Then
continue with the children . On return rebuild the node if any of the
children has changed and then apply the function on the node .
@plugin development guide
continue with the children. On return rebuild the node if any of the
children has changed and then apply the function on the node.
@plugin development guide *)
val mk_behavior :
?name:string ->
?assumes:('a list) ->
?requires:('a list) ->
?post_cond:((termination_kind * 'a) list) ->
?assigns:('b Cil_types.assigns ) ->
?allocation:('b Cil_types.allocation option) ->
?extended:((string * int * 'a list) list) ->
unit ->
('a, 'b) Cil_types.behavior
val default_behavior_name: string
val is_default_behavior: ('a,'b) behavior -> bool
val find_default_behavior: funspec -> funbehavior option
val find_default_requires: ('a, 'b) behavior list -> 'a list
* { 2 Visitor mechanism }
* { 3 Visitor behavior }
type visitor_behavior
* How the visitor should behave in front of mutable fields : in
place modification or copy of the structure . This type is abstract .
Use one of the two values below in your classes .
@plugin development guide
place modification or copy of the structure. This type is abstract.
Use one of the two values below in your classes.
@plugin development guide *)
val inplace_visit: unit -> visitor_behavior
* In - place modification . Behavior of the original cil visitor .
@plugin development guide
@plugin development guide *)
val copy_visit: Project.t -> visitor_behavior
* Makes fresh copies of the mutable structures .
- preserves sharing for varinfo .
- makes fresh copy of varinfo only for declarations . Variables that are
only used in the visited AST are thus still shared with the original
AST . This allows for instance to copy a function with its
formals and local variables , and to keep the references to other
globals in the function 's body .
@plugin development guide
- preserves sharing for varinfo.
- makes fresh copy of varinfo only for declarations. Variables that are
only used in the visited AST are thus still shared with the original
AST. This allows for instance to copy a function with its
formals and local variables, and to keep the references to other
globals in the function's body.
@plugin development guide *)
val refresh_visit: Project.t -> visitor_behavior
* Makes fresh copies of the mutable structures and provides fresh i d
for the structures that have ids . Note that as for { ! , only
varinfo that are declared in the scope of the visit will be copied and
provided with a new i d.
@since Sodium-20150201
for the structures that have ids. Note that as for {!copy_visit}, only
varinfo that are declared in the scope of the visit will be copied and
provided with a new id.
@since Sodium-20150201
*)
* true iff the behavior provides fresh i d for copied structs with i d.
Always [ false ] for an inplace visitor .
@since Sodium-20150201
Always [false] for an inplace visitor.
@since Sodium-20150201
*)
val is_fresh_behavior: visitor_behavior -> bool
val is_copy_behavior: visitor_behavior -> bool
val reset_behavior_varinfo: visitor_behavior -> unit
val reset_behavior_compinfo: visitor_behavior -> unit
val reset_behavior_enuminfo: visitor_behavior -> unit
val reset_behavior_enumitem: visitor_behavior -> unit
val reset_behavior_typeinfo: visitor_behavior -> unit
val reset_behavior_stmt: visitor_behavior -> unit
val reset_behavior_logic_info: visitor_behavior -> unit
val reset_behavior_logic_type_info: visitor_behavior -> unit
val reset_behavior_fieldinfo: visitor_behavior -> unit
val reset_behavior_model_info: visitor_behavior -> unit
val reset_logic_var: visitor_behavior -> unit
val reset_behavior_kernel_function: visitor_behavior -> unit
val reset_behavior_fundec: visitor_behavior -> unit
val get_varinfo: visitor_behavior -> varinfo -> varinfo
val get_compinfo: visitor_behavior -> compinfo -> compinfo
val get_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val get_enumitem: visitor_behavior -> enumitem -> enumitem
val get_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val get_stmt: visitor_behavior -> stmt -> stmt
val get_logic_info: visitor_behavior -> logic_info -> logic_info
val get_logic_type_info: visitor_behavior -> logic_type_info -> logic_type_info
val get_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val get_model_info: visitor_behavior -> model_info -> model_info
val get_logic_var: visitor_behavior -> logic_var -> logic_var
val get_kernel_function: visitor_behavior -> kernel_function -> kernel_function
val get_fundec: visitor_behavior -> fundec -> fundec
val get_original_varinfo: visitor_behavior -> varinfo -> varinfo
val get_original_compinfo: visitor_behavior -> compinfo -> compinfo
val get_original_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val get_original_enumitem: visitor_behavior -> enumitem -> enumitem
val get_original_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val get_original_stmt: visitor_behavior -> stmt -> stmt
val get_original_logic_info: visitor_behavior -> logic_info -> logic_info
val get_original_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info
val get_original_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val get_original_model_info: visitor_behavior -> model_info -> model_info
val get_original_logic_var: visitor_behavior -> logic_var -> logic_var
val get_original_kernel_function:
visitor_behavior -> kernel_function -> kernel_function
val get_original_fundec: visitor_behavior -> fundec -> fundec
val set_varinfo: visitor_behavior -> varinfo -> varinfo -> unit
* change the representative of a given varinfo in the current
state of the visitor . Use with care ( i.e. makes sure that the old one
is not referenced anywhere in the AST , or sharing will be lost .
state of the visitor. Use with care (i.e. makes sure that the old one
is not referenced anywhere in the AST, or sharing will be lost.
*)
val set_compinfo: visitor_behavior -> compinfo -> compinfo -> unit
val set_enuminfo: visitor_behavior -> enuminfo -> enuminfo -> unit
val set_enumitem: visitor_behavior -> enumitem -> enumitem -> unit
val set_typeinfo: visitor_behavior -> typeinfo -> typeinfo -> unit
val set_stmt: visitor_behavior -> stmt -> stmt -> unit
val set_logic_info: visitor_behavior -> logic_info -> logic_info -> unit
val set_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info -> unit
val set_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo -> unit
val set_model_info: visitor_behavior -> model_info -> model_info -> unit
val set_logic_var: visitor_behavior -> logic_var -> logic_var -> unit
val set_kernel_function:
visitor_behavior -> kernel_function -> kernel_function -> unit
val set_fundec: visitor_behavior -> fundec -> fundec -> unit
val set_orig_varinfo: visitor_behavior -> varinfo -> varinfo -> unit
val set_orig_compinfo: visitor_behavior -> compinfo -> compinfo -> unit
val set_orig_enuminfo: visitor_behavior -> enuminfo -> enuminfo -> unit
val set_orig_enumitem: visitor_behavior -> enumitem -> enumitem -> unit
val set_orig_typeinfo: visitor_behavior -> typeinfo -> typeinfo -> unit
val set_orig_stmt: visitor_behavior -> stmt -> stmt -> unit
val set_orig_logic_info: visitor_behavior -> logic_info -> logic_info -> unit
val set_orig_logic_type_info:
visitor_behavior -> logic_type_info -> logic_type_info -> unit
val set_orig_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo -> unit
val set_orig_model_info: visitor_behavior -> model_info -> model_info -> unit
val set_orig_logic_var: visitor_behavior -> logic_var -> logic_var -> unit
val set_orig_kernel_function:
visitor_behavior -> kernel_function -> kernel_function -> unit
val set_orig_fundec: visitor_behavior -> fundec -> fundec -> unit
val memo_varinfo: visitor_behavior -> varinfo -> varinfo
val memo_compinfo: visitor_behavior -> compinfo -> compinfo
val memo_enuminfo: visitor_behavior -> enuminfo -> enuminfo
val memo_enumitem: visitor_behavior -> enumitem -> enumitem
val memo_typeinfo: visitor_behavior -> typeinfo -> typeinfo
val memo_stmt: visitor_behavior -> stmt -> stmt
val memo_logic_info: visitor_behavior -> logic_info -> logic_info
val memo_logic_type_info: visitor_behavior -> logic_type_info -> logic_type_info
val memo_fieldinfo: visitor_behavior -> fieldinfo -> fieldinfo
val memo_model_info: visitor_behavior -> model_info -> model_info
val memo_logic_var: visitor_behavior -> logic_var -> logic_var
val memo_kernel_function:
visitor_behavior -> kernel_function -> kernel_function
val memo_fundec: visitor_behavior -> fundec -> fundec
* [ iter_visitor_varinfo vis f ] iterates [ f ] over each pair of
varinfo registered in [ vis ] . for the old AST is presented
to [ f ] first .
@since Oxygen-20120901
varinfo registered in [vis]. Varinfo for the old AST is presented
to [f] first.
@since Oxygen-20120901
*)
val iter_visitor_varinfo:
visitor_behavior -> (varinfo -> varinfo -> unit) -> unit
val iter_visitor_compinfo:
visitor_behavior -> (compinfo -> compinfo -> unit) -> unit
val iter_visitor_enuminfo:
visitor_behavior -> (enuminfo -> enuminfo -> unit) -> unit
val iter_visitor_enumitem:
visitor_behavior -> (enumitem -> enumitem -> unit) -> unit
val iter_visitor_typeinfo:
visitor_behavior -> (typeinfo -> typeinfo -> unit) -> unit
val iter_visitor_stmt:
visitor_behavior -> (stmt -> stmt -> unit) -> unit
val iter_visitor_logic_info:
visitor_behavior -> (logic_info -> logic_info -> unit) -> unit
val iter_visitor_logic_type_info:
visitor_behavior -> (logic_type_info -> logic_type_info -> unit) -> unit
val iter_visitor_fieldinfo:
visitor_behavior -> (fieldinfo -> fieldinfo -> unit) -> unit
val iter_visitor_model_info:
visitor_behavior -> (model_info -> model_info -> unit) -> unit
val iter_visitor_logic_var:
visitor_behavior -> (logic_var -> logic_var -> unit) -> unit
val iter_visitor_kernel_function:
visitor_behavior -> (kernel_function -> kernel_function -> unit) -> unit
val iter_visitor_fundec:
visitor_behavior -> (fundec -> fundec -> unit) -> unit
* [ fold_visitor_varinfo vis f ] folds [ f ] over each pair of varinfo registered
in [ vis ] . for the old AST is presented to [ f ] first .
@since Oxygen-20120901
in [vis]. Varinfo for the old AST is presented to [f] first.
@since Oxygen-20120901
*)
val fold_visitor_varinfo:
visitor_behavior -> (varinfo -> varinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_compinfo:
visitor_behavior -> (compinfo -> compinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_enuminfo:
visitor_behavior -> (enuminfo -> enuminfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_enumitem:
visitor_behavior -> (enumitem -> enumitem -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_typeinfo:
visitor_behavior -> (typeinfo -> typeinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_stmt:
visitor_behavior -> (stmt -> stmt -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_info:
visitor_behavior -> (logic_info -> logic_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_type_info:
visitor_behavior ->
(logic_type_info -> logic_type_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_fieldinfo:
visitor_behavior -> (fieldinfo -> fieldinfo -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_model_info:
visitor_behavior -> (model_info -> model_info -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_logic_var:
visitor_behavior -> (logic_var -> logic_var -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_kernel_function:
visitor_behavior ->
(kernel_function -> kernel_function -> 'a -> 'a) -> 'a -> 'a
val fold_visitor_fundec:
visitor_behavior -> (fundec -> fundec -> 'a -> 'a) -> 'a -> 'a
* { 3 Visitor class }
* A visitor interface for traversing CIL trees . Create instantiations of
this type by specializing the class { ! nopCilVisitor } . Each of the
specialized visiting functions can also call the [ queueInstr ] to specify
that some instructions should be inserted before the current instruction
or statement . Use syntax like [ self#queueInstr ] to call a method
associated with the current object .
{ b Important Note for Frama - C Users :} Unless you really know what you are
doing , you should probably inherit from the
{ ! Visitor.generic_frama_c_visitor } instead of { ! genericCilVisitor } or
{ ! nopCilVisitor }
@plugin development guide
this type by specializing the class {!nopCilVisitor}. Each of the
specialized visiting functions can also call the [queueInstr] to specify
that some instructions should be inserted before the current instruction
or statement. Use syntax like [self#queueInstr] to call a method
associated with the current object.
{b Important Note for Frama-C Users:} Unless you really know what you are
doing, you should probably inherit from the
{!Visitor.generic_frama_c_visitor} instead of {!genericCilVisitor} or
{!nopCilVisitor}
@plugin development guide *)
class type cilVisitor = object
method behavior: visitor_behavior
method project: Project.t option
method plain_copy_visitor: cilVisitor
method vfile: file -> file visitAction
method vvdec: varinfo -> varinfo visitAction
* Invoked for each variable declaration . The children to be traversed
are those corresponding to the type and attributes of the variable .
Note that variable declarations are [ GVar ] , [ GVarDecl ] , [ GFun ] and
[ GFunDecl ] globals , the formals of functions prototypes , and the
formals and locals of function definitions . This means that the list
of formals of a function may be traversed multiple times if there exists
both a declaration and a definition , or multiple declarations .
@plugin development guide
are those corresponding to the type and attributes of the variable.
Note that variable declarations are [GVar], [GVarDecl], [GFun] and
[GFunDecl] globals, the formals of functions prototypes, and the
formals and locals of function definitions. This means that the list
of formals of a function may be traversed multiple times if there exists
both a declaration and a definition, or multiple declarations.
@plugin development guide *)
method vvrbl: varinfo -> varinfo visitAction
* Invoked on each variable use . Here only the [ SkipChildren ] and
[ ChangeTo ] actions make sense since there are no subtrees . Note that
the type and attributes of the variable are not traversed for a
variable use .
@plugin development guide
[ChangeTo] actions make sense since there are no subtrees. Note that
the type and attributes of the variable are not traversed for a
variable use.
@plugin development guide *)
method vexpr: exp -> exp visitAction
method vlval: lval -> lval visitAction
method voffs: offset -> offset visitAction
method vinitoffs: offset -> offset visitAction
* Invoked on each offset appearing in the list of a
CompoundInit initializer .
CompoundInit initializer. *)
method vinst: instr -> instr list visitAction
method vstmt: stmt -> stmt visitAction
* Control - flow statement . The default [ DoChildren ] action does not create a
new statement when the components change . Instead it updates the contents
of the original statement . This is done to preserve the sharing with
[ ] and [ Case ] statements that point to the original statement . If you
use the [ ChangeTo ] action then you should take care of preserving that
sharing yourself .
@plugin development guide
new statement when the components change. Instead it updates the contents
of the original statement. This is done to preserve the sharing with
[Goto] and [Case] statements that point to the original statement. If you
use the [ChangeTo] action then you should take care of preserving that
sharing yourself.
@plugin development guide *)
method vblock: block -> block visitAction
method vfunc: fundec -> fundec visitAction
method vglob: global -> global list visitAction
method vinit: varinfo -> offset -> init -> init visitAction
method vtype: typ -> typ visitAction
* Use of some type . For typedef , struct , union and enum , the visit is
done once at the global defining the type . Thus , children of
[ TComp ] , [ TEnum ] and [ TNamed ] are not visited again .
done once at the global defining the type. Thus, children of
[TComp], [TEnum] and [TNamed] are not visited again. *)
method vcompinfo: compinfo -> compinfo visitAction
method venuminfo: enuminfo -> enuminfo visitAction
method vfieldinfo: fieldinfo -> fieldinfo visitAction
method venumitem: enumitem -> enumitem visitAction
method vattr: attribute -> attribute list visitAction
method vattrparam: attrparam -> attrparam visitAction
method queueInstr: instr list -> unit
method unqueueInstr: unit -> instr list
method current_stmt: stmt option
* link to the current statement being visited .
{ b NB :} for copy visitor , the stmt is the original one ( use
[ get_stmt ] to obtain the corresponding copy )
{b NB:} for copy visitor, the stmt is the original one (use
[get_stmt] to obtain the corresponding copy) *)
method current_kinstr: kinstr
* [ stmt ] when visiting statement stmt , [ Kglobal ] when called outside
of a statement .
@since Carbon-20101201
@plugin development guide
of a statement.
@since Carbon-20101201
@plugin development guide *)
method push_stmt : stmt -> unit
method pop_stmt : stmt -> unit
method current_func: fundec option
* link to the current function being visited .
{ b NB :} for copy visitors , the fundec is the original one .
{b NB:} for copy visitors, the fundec is the original one. *)
method set_current_func: fundec -> unit
method reset_current_func: unit -> unit
method vlogic_type: logic_type -> logic_type visitAction
method vmodel_info: model_info -> model_info visitAction
method videntified_term: identified_term -> identified_term visitAction
method vterm: term -> term visitAction
method vterm_node: term_node -> term_node visitAction
method vterm_lval: term_lval -> term_lval visitAction
method vterm_lhost: term_lhost -> term_lhost visitAction
method vterm_offset: term_offset -> term_offset visitAction
method vlogic_label: logic_label -> logic_label visitAction
method vlogic_info_decl: logic_info -> logic_info visitAction
method vlogic_info_use: logic_info -> logic_info visitAction
method vlogic_type_info_decl: logic_type_info -> logic_type_info visitAction
method vlogic_type_info_use: logic_type_info -> logic_type_info visitAction
method vlogic_type_def: logic_type_def -> logic_type_def visitAction
method vlogic_ctor_info_decl: logic_ctor_info -> logic_ctor_info visitAction
method vlogic_ctor_info_use: logic_ctor_info -> logic_ctor_info visitAction
method vlogic_var_decl: logic_var -> logic_var visitAction
method vlogic_var_use: logic_var -> logic_var visitAction
method vquantifiers: quantifiers -> quantifiers visitAction
method videntified_predicate:
identified_predicate -> identified_predicate visitAction
method vpredicate: predicate -> predicate visitAction
method vpredicate_named: predicate named -> predicate named visitAction
method vbehavior: funbehavior -> funbehavior visitAction
method vspec: funspec -> funspec visitAction
method vassigns:
identified_term assigns -> identified_term assigns visitAction
method vfrees:
identified_term list -> identified_term list visitAction
method vallocates:
identified_term list -> identified_term list visitAction
method vallocation:
identified_term allocation -> identified_term allocation visitAction
method vloop_pragma: term loop_pragma -> term loop_pragma visitAction
method vslice_pragma: term slice_pragma -> term slice_pragma visitAction
method vimpact_pragma: term impact_pragma -> term impact_pragma visitAction
method vdeps: identified_term deps -> identified_term deps visitAction
method vfrom: identified_term from -> identified_term from visitAction
method vcode_annot: code_annotation -> code_annotation visitAction
method vannotation: global_annotation -> global_annotation visitAction
method fill_global_tables: unit
method get_filling_actions: (unit -> unit) Queue.t
end
* Indicates how an extended behavior clause is supposed to be visited .
The default behavior is [ DoChildren ] , which ends up visiting
each identified predicate in the list and leave the i d as is .
@plugin development guide
@since Sodium-20150201
The default behavior is [DoChildren], which ends up visiting
each identified predicate in the list and leave the id as is.
@plugin development guide
@since Sodium-20150201
*)
val register_behavior_extension:
string ->
(cilVisitor -> (int * identified_predicate list) ->
(int * identified_predicate list) visitAction) -> unit
class internal_genericCilVisitor:
fundec option ref -> visitor_behavior -> (unit->unit) Queue.t -> cilVisitor
class genericCilVisitor: visitor_behavior -> cilVisitor
class nopCilVisitor: cilVisitor
* { 3 Generic visit functions }
* [ doVisit vis deepCopyVisitor copy action children node ]
visits a [ node ]
( or its copy according to the result of [ copy ] ) and if needed
its [ children ] . { b Do not use it if you do n't understand Cil visitor
mechanism }
@param vis the visitor performing the needed transformations . The open
type allows for extensions to to be visited by the same mechanisms .
@param deepCopyVisitor a generator for a visitor of the same type
of the current one that performs a deep copy of the AST .
Needed when the visitAction is [ SkipChildren ] or [ ChangeTo ] and [ vis ]
is a copy visitor ( we need to finish the copy anyway )
@param copy function that may return a copy of the actual node .
@param action the visiting function for the current node
@param children what to do on the children of the current node
@param node the current node
visits a [node]
(or its copy according to the result of [copy]) and if needed
its [children]. {b Do not use it if you don't understand Cil visitor
mechanism}
@param vis the visitor performing the needed transformations. The open
type allows for extensions to Cil to be visited by the same mechanisms.
@param deepCopyVisitor a generator for a visitor of the same type
of the current one that performs a deep copy of the AST.
Needed when the visitAction is [SkipChildren] or [ChangeTo] and [vis]
is a copy visitor (we need to finish the copy anyway)
@param copy function that may return a copy of the actual node.
@param action the visiting function for the current node
@param children what to do on the children of the current node
@param node the current node
*)
val doVisit:
'visitor -> 'visitor ->
('a -> 'a) ->
('a -> 'a visitAction) ->
('visitor -> 'a -> 'a) -> 'a -> 'a
val doVisitList:
'visitor -> 'visitor ->
('a -> 'a) ->
('a -> 'a list visitAction) ->
('visitor -> 'a -> 'a) -> 'a -> 'a list
other cil constructs
* { 3 Visitor 's entry points }
val visitCilFileCopy: cilVisitor -> file -> file
val visitCilFile: cilVisitor -> file -> unit
val visitCilFileSameGlobals: cilVisitor -> file -> unit
val visitCilGlobal: cilVisitor -> global -> global list
val visitCilFunction: cilVisitor -> fundec -> fundec
val visitCilExpr: cilVisitor -> exp -> exp
val visitCilEnumInfo: cilVisitor -> enuminfo -> enuminfo
val visitCilLval: cilVisitor -> lval -> lval
val visitCilOffset: cilVisitor -> offset -> offset
val visitCilInitOffset: cilVisitor -> offset -> offset
val visitCilInstr: cilVisitor -> instr -> instr list
val visitCilStmt: cilVisitor -> stmt -> stmt
val visitCilBlock: cilVisitor -> block -> block
val visitCilType: cilVisitor -> typ -> typ
val visitCilVarDecl: cilVisitor -> varinfo -> varinfo
val visitCilInit: cilVisitor -> varinfo -> offset -> init -> init
val visitCilAttributes: cilVisitor -> attribute list -> attribute list
val visitCilAnnotation: cilVisitor -> global_annotation -> global_annotation
val visitCilCodeAnnotation: cilVisitor -> code_annotation -> code_annotation
val visitCilDeps:
cilVisitor -> identified_term deps -> identified_term deps
val visitCilFrom:
cilVisitor -> identified_term from -> identified_term from
val visitCilAssigns:
cilVisitor -> identified_term assigns -> identified_term assigns
val visitCilFrees:
cilVisitor -> identified_term list -> identified_term list
val visitCilAllocates:
cilVisitor -> identified_term list -> identified_term list
val visitCilAllocation:
cilVisitor -> identified_term allocation -> identified_term allocation
val visitCilFunspec: cilVisitor -> funspec -> funspec
val visitCilBehavior: cilVisitor -> funbehavior -> funbehavior
val visitCilBehaviors: cilVisitor -> funbehavior list -> funbehavior list
* visit an extended clause of a behavior .
@since
@since Nitrogen-20111001
*)
val visitCilExtended:
cilVisitor -> (string * int * identified_predicate list)
-> (string * int * identified_predicate list)
val visitCilModelInfo: cilVisitor -> model_info -> model_info
val visitCilLogicType: cilVisitor -> logic_type -> logic_type
val visitCilIdPredicate:
cilVisitor -> identified_predicate -> identified_predicate
val visitCilPredicate: cilVisitor -> predicate -> predicate
val visitCilPredicateNamed: cilVisitor -> predicate named -> predicate named
val visitCilPredicates:
cilVisitor -> identified_predicate list -> identified_predicate list
val visitCilTerm: cilVisitor -> term -> term
val visitCilIdTerm: cilVisitor -> identified_term -> identified_term
* visit term_lval .
@since
@since Nitrogen-20111001
*)
val visitCilTermLval: cilVisitor -> term_lval -> term_lval
val visitCilTermLhost: cilVisitor -> term_lhost -> term_lhost
val visitCilTermOffset: cilVisitor -> term_offset -> term_offset
val visitCilLogicInfo: cilVisitor -> logic_info -> logic_info
val visitCilLogicVarUse: cilVisitor -> logic_var -> logic_var
val visitCilLogicVarDecl: cilVisitor -> logic_var -> logic_var
* { 3 Visiting children of a node }
val childrenBehavior: cilVisitor -> funbehavior -> funbehavior
* { 2 Utility functions }
val is_skip: stmtkind -> bool
val constFoldVisitor: bool -> cilVisitor
* { 2 Debugging support }
module CurrentLoc: State_builder.Ref with type data = location
val pp_thisloc: Format.formatter -> unit
val empty_funspec : unit -> funspec
val is_empty_funspec: funspec -> bool
val is_empty_behavior: funbehavior -> bool
* { 2 ALPHA conversion } has been moved to the Alpha module .
val uniqueVarNames: file -> unit
* { 2 Optimization Passes }
* A peephole optimizer that processes two adjacent statements and possibly
replaces them both . If some replacement happens and [ agressive ] is true ,
then the new statements are themselves subject to optimization . Each
statement in the list is optimized independently .
replaces them both. If some replacement happens and [agressive] is true,
then the new statements are themselves subject to optimization. Each
statement in the list is optimized independently. *)
val peepHole2:
agressive:bool -> (stmt * stmt -> stmt list option) -> stmt list -> stmt list
* Similar to [ peepHole2 ] except that the optimization window consists of
one statement , not two
one statement, not two *)
val peepHole1: (instr -> instr list option) -> stmt list -> unit
* { 2 Machine dependency }
* Raised when one of the SizeOf / AlignOf functions can not compute the size of a
type . This can happen because the type contains array - length expressions
that we do n't know how to compute or because it is a type whose size is not
defined ( e.g. TFun or an undefined ) . The string is an explanation
of the error
type. This can happen because the type contains array-length expressions
that we don't know how to compute or because it is a type whose size is not
defined (e.g. TFun or an undefined compinfo). The string is an explanation
of the error *)
exception SizeOfError of string * typ
val empty_size_cache : unit -> bitsSizeofTypCache
val unsignedVersionOf : ikind -> ikind
val signedVersionOf : ikind -> ikind
* The signed integer kind for a given size in bytes ( unsigned if second
* argument is true ) . Raises Not_found if no such kind exists
* argument is true). Raises Not_found if no such kind exists *)
val intKindForSize : int -> bool -> ikind
* The signed integer kind for a given size in bits ( unsigned if second
* argument is true ) . Raises Not_found if no such kind exists
* argument is true). Raises Not_found if no such kind exists *)
val intKindForBits : int -> bool -> ikind
val floatKindForSize : int-> fkind
* The size of a type , in bits . Trailing padding is added for structs and
* arrays . Raises { ! . SizeOfError } when it can not compute the size . This
* function is architecture dependent , so you should only call this after you
* call { ! Cil.initCIL } . Remember that on GCC sizeof(void ) is 1 !
* arrays. Raises {!Cil.SizeOfError} when it cannot compute the size. This
* function is architecture dependent, so you should only call this after you
* call {!Cil.initCIL}. Remember that on GCC sizeof(void) is 1! *)
val bitsSizeOf: typ -> int
* The size of a type , in bytes . Raises { ! . SizeOfError } when it can not
compute the size .
compute the size. *)
val bytesSizeOf: typ -> int
val bytesSizeOfInt: ikind -> int
val bitsSizeOfInt: ikind -> int
val isSigned: ikind -> bool
val rank: ikind -> int
* [ intTypeIncluded i1 i2 ] returns [ true ] iff the range of values
representable in [ i1 ] is included in the one of [ i2 ]
representable in [i1] is included in the one of [i2] *)
val intTypeIncluded: ikind -> ikind -> bool
val frank: fkind -> int
val truncateInteger64: ikind -> Integer.t -> Integer.t * bool
val max_signed_number: int -> Integer.t
val min_signed_number: int -> Integer.t
val max_unsigned_number: int -> Integer.t
val fitsInInt: ikind -> Integer.t -> bool
exception Not_representable
* @return the smallest kind that will hold the integer 's value .
The kind will be unsigned if the 2nd argument is true .
@raise if the bigint is not representable .
@modify Neon-20130301 may raise .
The kind will be unsigned if the 2nd argument is true.
@raise Not_representable if the bigint is not representable.
@modify Neon-20130301 may raise Not_representable. *)
val intKindForValue: Integer.t -> bool -> ikind
* The size of a type , in bytes . Returns a constant expression or a " sizeof "
* expression if it can not compute the size . This function is architecture
* dependent , so you should only call this after you call { ! Cil.initCIL } .
* expression if it cannot compute the size. This function is architecture
* dependent, so you should only call this after you call {!Cil.initCIL}. *)
val sizeOf: loc:location -> typ -> exp
* The minimum alignment ( in bytes ) for a type . This function is
* architecture dependent , so you should only call this after you call
* { ! Cil.initCIL } .
* architecture dependent, so you should only call this after you call
* {!Cil.initCIL}. *)
val bytesAlignOf: typ -> int
* Give a type of a base and an offset , returns the number of bits from the
* base address and the width ( also expressed in bits ) for the subobject
* denoted by the offset . Raises { ! . SizeOfError } when it can not compute
* the size . This function is architecture dependent , so you should only call
* this after you call { ! Cil.initCIL } .
* base address and the width (also expressed in bits) for the subobject
* denoted by the offset. Raises {!Cil.SizeOfError} when it cannot compute
* the size. This function is architecture dependent, so you should only call
* this after you call {!Cil.initCIL}. *)
val bitsOffset: typ -> offset -> int * int
val dExp:string -> exp
val dInstr: string -> location -> instr
val dGlobal: string -> location -> global
val mapNoCopy: ('a -> 'a) -> 'a list -> 'a list
val optMapNoCopy: ('a -> 'a) -> 'a option -> 'a option
val mapNoCopyList: ('a -> 'a list) -> 'a list -> 'a list
* sm : return true if the first is a prefix of the second string
val startsWith: string -> string -> bool
* { 2 An Interpreter for constructing CIL constructs }
type formatArg =
Fe of exp
| Fu of unop
| Fb of binop
| Fk of ikind
| Fv of varinfo
| Fl of lval
| Flo of lval option
| Fo of offset
| Fc of compinfo
| Fi of instr
| FI of instr list
| Ft of typ
| Fd of int
| Fg of string
| Fs of stmt
| FS of stmt list
| FA of attributes
| Fp of attrparam
| FP of attrparam list
| FX of string
val d_formatarg : Format.formatter -> formatArg -> unit
* { 2 Misc }
val stmt_of_instr_list : ?loc:location -> instr list -> stmtkind
val cvar_to_lvar : varinfo -> logic_var
val make_temp_logic_var: logic_type -> logic_var
* The constant logic term zero .
@plugin development guide
@plugin development guide *)
val lzero : ?loc:location -> unit -> term
* The constant logic term 1 .
val lone : ?loc:location -> unit -> term
val lmone : ?loc:location -> unit -> term
val lconstant : ?loc:location -> Integer.t -> term
val close_predicate : predicate named -> predicate named
val extract_varinfos_from_exp : exp -> Varinfo.Set.t
val extract_varinfos_from_lval : lval -> Varinfo.Set.t
val extract_free_logicvars_from_term : term -> Logic_var.Set.t
val extract_free_logicvars_from_predicate :
predicate named -> Logic_var.Set.t
val extract_labels_from_annot:
code_annotation -> Cil_datatype.Logic_label.Set.t
val extract_labels_from_term: term -> Cil_datatype.Logic_label.Set.t
val extract_labels_from_pred:
predicate named -> Cil_datatype.Logic_label.Set.t
* extract [ stmt ] elements from [ logic_label ] elements
val extract_stmts_from_labels:
Cil_datatype.Logic_label.Set.t -> Cil_datatype.Stmt.Set.t
* creates a visitor that will replace in place uses of var in the first
list by their counterpart in the second list .
@raise Invalid_argument if the lists have different lengths .
list by their counterpart in the second list.
@raise Invalid_argument if the lists have different lengths. *)
val create_alpha_renaming: varinfo list -> varinfo list -> cilVisitor
* Provided [ s ] is a switch , [ separate_switch_succs s ] returns the
subset of [ s.succs ] that correspond to the Case labels of [ s ] , and a
" default statement " that either corresponds to the label , or to the
syntactic successor of [ s ] if there is no default label . Note that this " default
statement " can thus appear in the returned list .
subset of [s.succs] that correspond to the Case labels of [s], and a
"default statement" that either corresponds to the Default label, or to the
syntactic successor of [s] if there is no default label. Note that this "default
statement" can thus appear in the returned list. *)
val separate_switch_succs: stmt -> stmt list * stmt
* Provided [ s ] is a if , [ separate_if_succs s ] splits the successors
of s according to the truth value of the condition . The first
element of the pair is the successor statement if the condition is
true , and the second if the condition is false .
of s according to the truth value of the condition. The first
element of the pair is the successor statement if the condition is
true, and the second if the condition is false. *)
val separate_if_succs: stmt -> stmt * stmt
val dependency_on_ast: State.t -> unit
* indicates that the given state depends on the AST and is monotonic .
val set_dependencies_of_ast : (State.t -> unit) -> State.t -> unit
* Makes all states that have been marked as depending on the AST by
{ ! dependency_on_ast } depend on the given state . Should only be used
once when creating the AST state .
The first argument is always bound to { Ast.add_monotonic_state }
and will be applied to each state declared by { dependency_on_ast } .
{!dependency_on_ast} depend on the given state. Should only be used
once when creating the AST state.
The first argument is always bound to {Ast.add_monotonic_state}
and will be applied to each state declared by {dependency_on_ast}.
*)
val pp_typ_ref: (Format.formatter -> typ -> unit) ref
val pp_global_ref: (Format.formatter -> global -> unit) ref
val pp_exp_ref: (Format.formatter -> exp -> unit) ref
val pp_lval_ref: (Format.formatter -> lval -> unit) ref
val pp_ikind_ref: (Format.formatter -> ikind -> unit) ref
val pp_attribute_ref: (Format.formatter -> attribute -> unit) ref
val pp_attributes_ref: (Format.formatter -> attribute list -> unit) ref
|
d19cf6252c3a5432f6aeb16a636d648ce0301a23a1176bb22144c94ea208c837 | nvim-treesitter/nvim-treesitter | injections.scm | (comment) @comment
(apply_expression
function: (_) @_func
argument: [
(string_expression (string_fragment) @regex)
(indented_string_expression (string_fragment) @regex)
]
(#match? @_func "(^|\\.)match$"))
@combined
(binding
attrpath: (attrpath (identifier) @_path)
expression: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
]
(#match? @_path "(^\\w+(Phase|Hook)|(pre|post)[A-Z]\\w+|script)$"))
(apply_expression
function: (_) @_func
argument: (_ (_)* (_ (_)* (binding
attrpath: (attrpath (identifier) @_path)
expression: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
])))
(#match? @_func "(^|\\.)writeShellApplication$")
(#match? @_path "^text$"))
@combined
(apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
]
(#match? @_func "(^|\\.)runCommand((No)?CC)?(Local)?$"))
@combined
((apply_expression
function: (apply_expression function: (_) @_func)
argument: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
])
(#match? @_func "(^|\\.)write(Bash|Dash|ShellScript)(Bin)?$"))
@combined
((apply_expression
function: (apply_expression function: (_) @_func)
argument: [
(string_expression (string_fragment) @fish)
(indented_string_expression (string_fragment) @fish)
])
(#match? @_func "(^|\\.)writeFish(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @haskell)
(indented_string_expression (string_fragment) @haskell)
])
(#match? @_func "(^|\\.)writeHaskell(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @javascript)
(indented_string_expression (string_fragment) @javascript)
])
(#match? @_func "(^|\\.)writeJS(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @perl)
(indented_string_expression (string_fragment) @perl)
])
(#match? @_func "(^|\\.)writePerl(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @python)
(indented_string_expression (string_fragment) @python)
])
(#match? @_func "(^|\\.)write(PyPy|Python)[23](Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @rust)
(indented_string_expression (string_fragment) @rust)
])
(#match? @_func "(^|\\.)writeRust(Bin)?$"))
@combined
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/332fd5338ff11b94803f2629f67f7d3db289b946/queries/nix/injections.scm | scheme | (comment) @comment
(apply_expression
function: (_) @_func
argument: [
(string_expression (string_fragment) @regex)
(indented_string_expression (string_fragment) @regex)
]
(#match? @_func "(^|\\.)match$"))
@combined
(binding
attrpath: (attrpath (identifier) @_path)
expression: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
]
(#match? @_path "(^\\w+(Phase|Hook)|(pre|post)[A-Z]\\w+|script)$"))
(apply_expression
function: (_) @_func
argument: (_ (_)* (_ (_)* (binding
attrpath: (attrpath (identifier) @_path)
expression: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
])))
(#match? @_func "(^|\\.)writeShellApplication$")
(#match? @_path "^text$"))
@combined
(apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
]
(#match? @_func "(^|\\.)runCommand((No)?CC)?(Local)?$"))
@combined
((apply_expression
function: (apply_expression function: (_) @_func)
argument: [
(string_expression (string_fragment) @bash)
(indented_string_expression (string_fragment) @bash)
])
(#match? @_func "(^|\\.)write(Bash|Dash|ShellScript)(Bin)?$"))
@combined
((apply_expression
function: (apply_expression function: (_) @_func)
argument: [
(string_expression (string_fragment) @fish)
(indented_string_expression (string_fragment) @fish)
])
(#match? @_func "(^|\\.)writeFish(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @haskell)
(indented_string_expression (string_fragment) @haskell)
])
(#match? @_func "(^|\\.)writeHaskell(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @javascript)
(indented_string_expression (string_fragment) @javascript)
])
(#match? @_func "(^|\\.)writeJS(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @perl)
(indented_string_expression (string_fragment) @perl)
])
(#match? @_func "(^|\\.)writePerl(Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @python)
(indented_string_expression (string_fragment) @python)
])
(#match? @_func "(^|\\.)write(PyPy|Python)[23](Bin)?$"))
@combined
((apply_expression
function: (apply_expression
function: (apply_expression function: (_) @_func))
argument: [
(string_expression (string_fragment) @rust)
(indented_string_expression (string_fragment) @rust)
])
(#match? @_func "(^|\\.)writeRust(Bin)?$"))
@combined
|
|
e917cb4defdefba6c1e6175920555685d72732afaa7b5cc37fedffa710c1e340 | rescript-lang/rescript-compiler | res_scanner.ml | module Diagnostics = Res_diagnostics
module Token = Res_token
module Comment = Res_comment
type mode = Jsx | Diamond
(* We hide the implementation detail of the scanner reading character. Our char
will also contain the special -1 value to indicate end-of-file. This isn't
ideal; we should clean this up *)
let hackyEOFChar = Char.unsafe_chr (-1)
type charEncoding = Char.t
type t = {
filename: string;
src: string;
mutable err:
startPos:Lexing.position ->
endPos:Lexing.position ->
Diagnostics.category ->
unit;
mutable ch: charEncoding; (* current character *)
mutable offset: int; (* character offset *)
mutable lineOffset: int; (* current line offset *)
mutable lnum: int; (* current line number *)
mutable mode: mode list;
}
let setDiamondMode scanner = scanner.mode <- Diamond :: scanner.mode
let setJsxMode scanner = scanner.mode <- Jsx :: scanner.mode
let popMode scanner mode =
match scanner.mode with
| m :: ms when m = mode -> scanner.mode <- ms
| _ -> ()
let inDiamondMode scanner =
match scanner.mode with
| Diamond :: _ -> true
| _ -> false
let inJsxMode scanner =
match scanner.mode with
| Jsx :: _ -> true
| _ -> false
let position scanner =
Lexing.
{
pos_fname = scanner.filename;
(* line number *)
pos_lnum = scanner.lnum;
(* offset of the beginning of the line (number
of characters between the beginning of the scanner and the beginning
of the line) *)
pos_bol = scanner.lineOffset;
(* [pos_cnum] is the offset of the position (number of
characters between the beginning of the scanner and the position). *)
pos_cnum = scanner.offset;
}
Small debugging util
❯ echo ' let msg = " hello " ' | ./lib / rescript.exe
let msg = " hello "
^-^ let 0 - 3
let msg = " hello "
^-^ msg 4 - 7
let msg = " hello "
^ = 8 - 9
let msg = " hello "
^-----^ string " hello " 10 - 17
let msg = " hello "
^ eof 18 - 18
let msg = " hello "
❯ echo 'let msg = "hello"' | ./lib/rescript.exe
let msg = "hello"
^-^ let 0-3
let msg = "hello"
^-^ msg 4-7
let msg = "hello"
^ = 8-9
let msg = "hello"
^-----^ string "hello" 10-17
let msg = "hello"
^ eof 18-18
let msg = "hello"
*)
let _printDebug ~startPos ~endPos scanner token =
let open Lexing in
print_string scanner.src;
print_string ((String.make [@doesNotRaise]) startPos.pos_cnum ' ');
print_char '^';
(match endPos.pos_cnum - startPos.pos_cnum with
| 0 -> if token = Token.Eof then () else assert false
| 1 -> ()
| n ->
print_string ((String.make [@doesNotRaise]) (n - 2) '-');
print_char '^');
print_char ' ';
print_string (Res_token.toString token);
print_char ' ';
print_int startPos.pos_cnum;
print_char '-';
print_int endPos.pos_cnum;
print_endline ""
[@@live]
let next scanner =
let nextOffset = scanner.offset + 1 in
(match scanner.ch with
| '\n' ->
scanner.lineOffset <- nextOffset;
scanner.lnum <- scanner.lnum + 1
(* What about CRLF (\r + \n) on windows?
* \r\n will always be terminated by a \n
* -> we can just bump the line count on \n *)
| _ -> ());
if nextOffset < String.length scanner.src then (
scanner.offset <- nextOffset;
scanner.ch <- String.unsafe_get scanner.src scanner.offset)
else (
scanner.offset <- String.length scanner.src;
scanner.ch <- hackyEOFChar)
let next2 scanner =
next scanner;
next scanner
let next3 scanner =
next scanner;
next scanner;
next scanner
let peek scanner =
if scanner.offset + 1 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 1)
else hackyEOFChar
let peek2 scanner =
if scanner.offset + 2 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 2)
else hackyEOFChar
let peek3 scanner =
if scanner.offset + 3 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 3)
else hackyEOFChar
let make ~filename src =
{
filename;
src;
err = (fun ~startPos:_ ~endPos:_ _ -> ());
ch = (if src = "" then hackyEOFChar else String.unsafe_get src 0);
offset = 0;
lineOffset = 0;
lnum = 1;
mode = [];
}
(* generic helpers *)
let isWhitespace ch =
match ch with
| ' ' | '\t' | '\n' | '\r' -> true
| _ -> false
let rec skipWhitespace scanner =
if isWhitespace scanner.ch then (
next scanner;
skipWhitespace scanner)
let digitValue ch =
match ch with
| '0' .. '9' -> Char.code ch - 48
| 'a' .. 'f' -> Char.code ch - Char.code 'a' + 10
| 'A' .. 'F' -> Char.code ch + 32 - Char.code 'a' + 10
| _ -> 16 (* larger than any legal value *)
(* scanning helpers *)
let scanIdentifier scanner =
let startOff = scanner.offset in
let rec skipGoodChars scanner =
match scanner.ch with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '\'' ->
next scanner;
skipGoodChars scanner
| _ -> ()
in
skipGoodChars scanner;
let str =
(String.sub [@doesNotRaise]) scanner.src startOff (scanner.offset - startOff)
in
if '{' == scanner.ch && str = "list" then (
next scanner;
(* TODO: this isn't great *)
Token.lookupKeyword "list{")
else Token.lookupKeyword str
let scanDigits scanner ~base =
if base <= 10 then
let rec loop scanner =
match scanner.ch with
| '0' .. '9' | '_' ->
next scanner;
loop scanner
| _ -> ()
in
loop scanner
else
let rec loop scanner =
match scanner.ch with
(* hex *)
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' | '_' ->
next scanner;
loop scanner
| _ -> ()
in
loop scanner
float : ( 0 … 9 ) { 0 … 9∣ _ } [ . { 0 … 9∣ _ } ] [ ( e∣ E ) [ + ∣ - ] ( 0 … 9 ) { 0 … 9∣ _ } ]
let scanNumber scanner =
let startOff = scanner.offset in
(* integer part *)
let base =
match scanner.ch with
| '0' -> (
match peek scanner with
| 'x' | 'X' ->
next2 scanner;
16
| 'o' | 'O' ->
next2 scanner;
8
| 'b' | 'B' ->
next2 scanner;
2
| _ ->
next scanner;
8)
| _ -> 10
in
scanDigits scanner ~base;
(* *)
let isFloat =
if '.' == scanner.ch then (
next scanner;
scanDigits scanner ~base;
true)
else false
in
(* exponent part *)
let isFloat =
match scanner.ch with
| 'e' | 'E' | 'p' | 'P' ->
(match peek scanner with
| '+' | '-' -> next2 scanner
| _ -> next scanner);
scanDigits scanner ~base;
true
| _ -> isFloat
in
let literal =
(String.sub [@doesNotRaise]) scanner.src startOff (scanner.offset - startOff)
in
(* suffix *)
let suffix =
match scanner.ch with
| 'n' ->
let msg =
"Unsupported number type (nativeint). Did you mean `" ^ literal ^ "`?"
in
let pos = position scanner in
scanner.err ~startPos:pos ~endPos:pos (Diagnostics.message msg);
next scanner;
Some 'n'
| ('g' .. 'z' | 'G' .. 'Z') as ch ->
next scanner;
Some ch
| _ -> None
in
if isFloat then Token.Float {f = literal; suffix}
else Token.Int {i = literal; suffix}
let scanExoticIdentifier scanner =
(* TODO: are we disregarding the current char...? Should be a quote *)
next scanner;
let buffer = Buffer.create 20 in
let startPos = position scanner in
let rec scan () =
match scanner.ch with
| '"' -> next scanner
| '\n' | '\r' ->
(* line break *)
let endPos = position scanner in
scanner.err ~startPos ~endPos
(Diagnostics.message "A quoted identifier can't contain line breaks.");
next scanner
| ch when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos
(Diagnostics.message "Did you forget a \" here?")
| ch ->
Buffer.add_char buffer ch;
next scanner;
scan ()
in
scan ();
(* TODO: do we really need to create a new buffer instead of substring once? *)
Token.Lident (Buffer.contents buffer)
let scanStringEscapeSequence ~startPos scanner =
let scan ~n ~base ~max =
let rec loop n x =
if n == 0 then x
else
let d = digitValue scanner.ch in
if d >= base then (
let pos = position scanner in
let msg =
if scanner.ch == hackyEOFChar then "unclosed escape sequence"
else "unknown escape sequence"
in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg);
-1)
else
let () = next scanner in
loop (n - 1) ((x * base) + d)
in
let x = loop n 0 in
if x > max || (0xD800 <= x && x < 0xE000) then
let pos = position scanner in
let msg = "escape sequence is invalid unicode code point" in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg)
in
match scanner.ch with
(* \ already consumed *)
| 'n' | 't' | 'b' | 'r' | '\\' | ' ' | '\'' | '"' -> next scanner
| '0'
when let c = peek scanner in
c < '0' || c > '9' ->
(* Allow \0 *)
next scanner
| '0' .. '9' -> scan ~n:3 ~base:10 ~max:255
| 'x' ->
(* hex *)
next scanner;
scan ~n:2 ~base:16 ~max:255
| 'u' -> (
next scanner;
match scanner.ch with
| '{' -> (
unicode code point escape sequence : ' \u{7A } ' , one or more hex digits
next scanner;
let x = ref 0 in
while
match scanner.ch with
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
do
x := (!x * 16) + digitValue scanner.ch;
next scanner
done;
(* consume '}' in '\u{7A}' *)
match scanner.ch with
| '}' -> next scanner
| _ -> ())
| _ -> scan ~n:4 ~base:16 ~max:Res_utf8.max)
| _ ->
(* unknown escape sequence
* TODO: we should warn the user here. Let's not make it a hard error for now, for reason compat *)
(*
let pos = position scanner in
let msg =
if ch == -1 then "unclosed escape sequence"
else "unknown escape sequence"
in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg)
*)
()
let scanString scanner =
(* assumption: we've just matched a quote *)
let startPosWithQuote = position scanner in
next scanner;
(* If the text needs changing, a buffer is used *)
let buf = Buffer.create 0 in
let firstCharOffset = scanner.offset in
let lastOffsetInBuf = ref firstCharOffset in
let bringBufUpToDate ~startOffset =
let strUpToNow =
(String.sub scanner.src !lastOffsetInBuf
(startOffset - !lastOffsetInBuf) [@doesNotRaise])
in
Buffer.add_string buf strUpToNow;
lastOffsetInBuf := startOffset
in
let result ~firstCharOffset ~lastCharOffset =
if Buffer.length buf = 0 then
(String.sub [@doesNotRaise]) scanner.src firstCharOffset
(lastCharOffset - firstCharOffset)
else (
bringBufUpToDate ~startOffset:lastCharOffset;
Buffer.contents buf)
in
let rec scan () =
match scanner.ch with
| '"' ->
let lastCharOffset = scanner.offset in
next scanner;
result ~firstCharOffset ~lastCharOffset
| '\\' ->
let startPos = position scanner in
let startOffset = scanner.offset + 1 in
next scanner;
scanStringEscapeSequence ~startPos scanner;
let endOffset = scanner.offset in
convertOctalToHex ~startOffset ~endOffset
| ch when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos:startPosWithQuote ~endPos Diagnostics.unclosedString;
let lastCharOffset = scanner.offset in
result ~firstCharOffset ~lastCharOffset
| _ ->
next scanner;
scan ()
and convertOctalToHex ~startOffset ~endOffset =
let len = endOffset - startOffset in
let isDigit = function
| '0' .. '9' -> true
| _ -> false
in
let txt = scanner.src in
let isNumericEscape =
len = 3
&& (isDigit txt.[startOffset] [@doesNotRaise])
&& (isDigit txt.[startOffset + 1] [@doesNotRaise])
&& (isDigit txt.[startOffset + 2] [@doesNotRaise])
in
if isNumericEscape then (
let strDecimal = (String.sub txt startOffset 3 [@doesNotRaise]) in
bringBufUpToDate ~startOffset;
let strHex = Res_string.convertDecimalToHex ~strDecimal in
lastOffsetInBuf := startOffset + 3;
Buffer.add_string buf strHex;
scan ())
else scan ()
in
Token.String (scan ())
let scanEscape scanner =
(* '\' consumed *)
let offset = scanner.offset - 1 in
let convertNumber scanner ~n ~base =
let x = ref 0 in
for _ = n downto 1 do
let d = digitValue scanner.ch in
x := (!x * base) + d;
next scanner
done;
let c = !x in
if Res_utf8.isValidCodePoint c then c else Res_utf8.repl
in
let codepoint =
match scanner.ch with
| '0' .. '9' -> convertNumber scanner ~n:3 ~base:10
| 'b' ->
next scanner;
8
| 'n' ->
next scanner;
10
| 'r' ->
next scanner;
13
| 't' ->
next scanner;
009
| 'x' ->
next scanner;
convertNumber scanner ~n:2 ~base:16
| 'o' ->
next scanner;
convertNumber scanner ~n:3 ~base:8
| 'u' -> (
next scanner;
match scanner.ch with
| '{' ->
unicode code point escape sequence : ' \u{7A } ' , one or more hex digits
next scanner;
let x = ref 0 in
while
match scanner.ch with
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
do
x := (!x * 16) + digitValue scanner.ch;
next scanner
done;
(* consume '}' in '\u{7A}' *)
(match scanner.ch with
| '}' -> next scanner
| _ -> ());
let c = !x in
if Res_utf8.isValidCodePoint c then c else Res_utf8.repl
| _ ->
unicode escape sequence : ' \u007A ' , exactly 4 hex digits
convertNumber scanner ~n:4 ~base:16)
| ch ->
next scanner;
Char.code ch
in
let contents =
(String.sub [@doesNotRaise]) scanner.src offset (scanner.offset - offset)
in
next scanner;
(* Consume \' *)
(* TODO: do we know it's \' ? *)
Token.Codepoint {c = codepoint; original = contents}
let scanSingleLineComment scanner =
let startOff = scanner.offset in
let startPos = position scanner in
let rec skip scanner =
match scanner.ch with
| '\n' | '\r' -> ()
| ch when ch == hackyEOFChar -> ()
| _ ->
next scanner;
skip scanner
in
skip scanner;
let endPos = position scanner in
Token.Comment
(Comment.makeSingleLineComment
~loc:Location.{loc_start = startPos; loc_end = endPos; loc_ghost = false}
((String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - startOff)))
let scanMultiLineComment scanner =
(* assumption: we're only ever using this helper in `scan` after detecting a comment *)
let docComment = peek2 scanner = '*' && peek3 scanner <> '/' (* no /**/ *) in
let standalone = docComment && peek3 scanner = '*' (* /*** *) in
let contentStartOff =
scanner.offset + if docComment then if standalone then 4 else 3 else 2
in
let startPos = position scanner in
let rec scan ~depth =
(* invariant: depth > 0 right after this match. See assumption *)
match (scanner.ch, peek scanner) with
| '/', '*' ->
next2 scanner;
scan ~depth:(depth + 1)
| '*', '/' ->
next2 scanner;
if depth > 1 then scan ~depth:(depth - 1)
| ch, _ when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos Diagnostics.unclosedComment
| _ ->
next scanner;
scan ~depth
in
scan ~depth:0;
let length = scanner.offset - 2 - contentStartOff in
in case of EOF
Token.Comment
(Comment.makeMultiLineComment ~docComment ~standalone
~loc:
Location.
{loc_start = startPos; loc_end = position scanner; loc_ghost = false}
((String.sub [@doesNotRaise]) scanner.src contentStartOff length))
let scanTemplateLiteralToken scanner =
let startOff = scanner.offset in
(* if starting } here, consume it *)
if scanner.ch == '}' then next scanner;
let startPos = position scanner in
let rec scan () =
let lastPos = position scanner in
match scanner.ch with
| '`' ->
next scanner;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - 1 - startOff)
in
Token.TemplateTail (contents, lastPos)
| '$' -> (
match peek scanner with
| '{' ->
next2 scanner;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - 2 - startOff)
in
Token.TemplatePart (contents, lastPos)
| _ ->
next scanner;
scan ())
| '\\' -> (
match peek scanner with
| '`' | '\\' | '$' | '\n' | '\r' ->
(* line break *)
next2 scanner;
scan ()
| _ ->
next scanner;
scan ())
| ch when ch = hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos Diagnostics.unclosedTemplate;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(max (scanner.offset - 1 - startOff) 0)
in
Token.TemplateTail (contents, lastPos)
| _ ->
next scanner;
scan ()
in
let token = scan () in
let endPos = position scanner in
(startPos, endPos, token)
let rec scan scanner =
skipWhitespace scanner;
let startPos = position scanner in
let token =
match scanner.ch with
(* peeking 0 char *)
| 'A' .. 'Z' | 'a' .. 'z' -> scanIdentifier scanner
| '0' .. '9' -> scanNumber scanner
| '`' ->
next scanner;
Token.Backtick
| '~' ->
next scanner;
Token.Tilde
| '?' ->
next scanner;
Token.Question
| ';' ->
next scanner;
Token.Semicolon
| '(' ->
next scanner;
Token.Lparen
| ')' ->
next scanner;
Token.Rparen
| '[' ->
next scanner;
Token.Lbracket
| ']' ->
next scanner;
Token.Rbracket
| '{' ->
next scanner;
Token.Lbrace
| '}' ->
next scanner;
Token.Rbrace
| ',' ->
next scanner;
Token.Comma
| '"' -> scanString scanner
peeking 1 char
| '_' -> (
match peek scanner with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' -> scanIdentifier scanner
| _ ->
next scanner;
Token.Underscore)
| '#' -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.HashEqual
| _ ->
next scanner;
Token.Hash)
| '*' -> (
match peek scanner with
| '*' ->
next2 scanner;
Token.Exponentiation
| '.' ->
next2 scanner;
Token.AsteriskDot
| _ ->
next scanner;
Token.Asterisk)
| '@' -> (
match peek scanner with
| '@' ->
next2 scanner;
Token.AtAt
| _ ->
next scanner;
Token.At)
| '%' -> (
match peek scanner with
| '%' ->
next2 scanner;
Token.PercentPercent
| _ ->
next scanner;
Token.Percent)
| '|' -> (
match peek scanner with
| '|' ->
next2 scanner;
Token.Lor
| '>' ->
next2 scanner;
Token.BarGreater
| _ ->
next scanner;
Token.Bar)
| '&' -> (
match peek scanner with
| '&' ->
next2 scanner;
Token.Land
| _ ->
next scanner;
Token.Band)
| ':' -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.ColonEqual
| '>' ->
next2 scanner;
Token.ColonGreaterThan
| _ ->
next scanner;
Token.Colon)
| '\\' ->
next scanner;
scanExoticIdentifier scanner
| '/' -> (
match peek scanner with
| '/' ->
next2 scanner;
scanSingleLineComment scanner
| '*' -> scanMultiLineComment scanner
| '.' ->
next2 scanner;
Token.ForwardslashDot
| _ ->
next scanner;
Token.Forwardslash)
| '-' -> (
match peek scanner with
| '.' ->
next2 scanner;
Token.MinusDot
| '>' ->
next2 scanner;
Token.MinusGreater
| _ ->
next scanner;
Token.Minus)
| '+' -> (
match peek scanner with
| '.' ->
next2 scanner;
Token.PlusDot
| '+' ->
next2 scanner;
Token.PlusPlus
| '=' ->
next2 scanner;
Token.PlusEqual
| _ ->
next scanner;
Token.Plus)
| '>' -> (
match peek scanner with
| '=' when not (inDiamondMode scanner) ->
next2 scanner;
Token.GreaterEqual
| _ ->
next scanner;
Token.GreaterThan)
| '<' when not (inJsxMode scanner) -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.LessEqual
| _ ->
next scanner;
Token.LessThan)
special handling for JSX <
| '<' -> (
Imagine the following : < div > <
* < indicates the start of a new jsx - element , the parser expects
* the name of a new element after the <
* Example : < div > < div
* But what if we have a / here : example < / in < div></div >
* This signals a closing element . To simulate the two - token lookahead ,
* the < / is emitted as a single new token LessThanSlash
* < indicates the start of a new jsx-element, the parser expects
* the name of a new element after the <
* Example: <div> <div
* But what if we have a / here: example </ in <div></div>
* This signals a closing element. To simulate the two-token lookahead,
* the </ is emitted as a single new token LessThanSlash *)
next scanner;
skipWhitespace scanner;
match scanner.ch with
| '/' ->
next scanner;
Token.LessThanSlash
| '=' ->
next scanner;
Token.LessEqual
| _ -> Token.LessThan)
peeking 2 chars
| '.' -> (
match (peek scanner, peek2 scanner) with
| '.', '.' ->
next3 scanner;
Token.DotDotDot
| '.', _ ->
next2 scanner;
Token.DotDot
| _ ->
next scanner;
Token.Dot)
| '\'' -> (
match (peek scanner, peek2 scanner) with
| '\\', '"' ->
(* careful with this one! We're next-ing _once_ (not twice),
then relying on matching on the quote *)
next scanner;
SingleQuote
| '\\', _ ->
next2 scanner;
scanEscape scanner
| ch, '\'' ->
let offset = scanner.offset + 1 in
next3 scanner;
Token.Codepoint
{
c = Char.code ch;
original = (String.sub [@doesNotRaise]) scanner.src offset 1;
}
| ch, _ ->
next scanner;
let offset = scanner.offset in
let codepoint, length =
Res_utf8.decodeCodePoint scanner.offset scanner.src
(String.length scanner.src)
in
for _ = 0 to length - 1 do
next scanner
done;
if scanner.ch = '\'' then (
let contents =
(String.sub [@doesNotRaise]) scanner.src offset length
in
next scanner;
Token.Codepoint {c = codepoint; original = contents})
else (
scanner.ch <- ch;
scanner.offset <- offset;
SingleQuote))
| '!' -> (
match (peek scanner, peek2 scanner) with
| '=', '=' ->
next3 scanner;
Token.BangEqualEqual
| '=', _ ->
next2 scanner;
Token.BangEqual
| _ ->
next scanner;
Token.Bang)
| '=' -> (
match (peek scanner, peek2 scanner) with
| '=', '=' ->
next3 scanner;
Token.EqualEqualEqual
| '=', _ ->
next2 scanner;
Token.EqualEqual
| '>', _ ->
next2 scanner;
Token.EqualGreater
| _ ->
next scanner;
Token.Equal)
(* special cases *)
| ch when ch == hackyEOFChar ->
next scanner;
Token.Eof
| ch ->
(* if we arrive here, we're dealing with an unknown character,
* report the error and continue scanning… *)
next scanner;
let endPos = position scanner in
scanner.err ~startPos ~endPos (Diagnostics.unknownUchar ch);
let _, _, token = scan scanner in
token
in
let endPos = position scanner in
_ scanner token ;
(startPos, endPos, token)
(* misc helpers used elsewhere *)
Imagine : < div > < Navbar / > <
* is ` < ` the start of a jsx - child ? < div …
* or is it the start of a closing tag ? < /div >
* reconsiderLessThan peeks at the next token and
* determines the correct token to disambiguate
* is `<` the start of a jsx-child? <div …
* or is it the start of a closing tag? </div>
* reconsiderLessThan peeks at the next token and
* determines the correct token to disambiguate *)
let reconsiderLessThan scanner =
(* < consumed *)
skipWhitespace scanner;
if scanner.ch == '/' then
let () = next scanner in
Token.LessThanSlash
else Token.LessThan
(* If an operator has whitespace around both sides, it's a binary operator *)
(* TODO: this helper seems out of place *)
let isBinaryOp src startCnum endCnum =
if startCnum == 0 then false
else (
(* we're gonna put some assertions and invariant checks here because this is
used outside of the scanner's normal invariant assumptions *)
assert (endCnum >= 0);
assert (startCnum > 0 && startCnum < String.length src);
let leftOk = isWhitespace (String.unsafe_get src (startCnum - 1)) in
(* we need some stronger confidence that endCnum is ok *)
let rightOk =
endCnum >= String.length src
|| isWhitespace (String.unsafe_get src endCnum)
in
leftOk && rightOk)
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/fa299663d8a0172916f86f56a9fd9978d631e4a3/res_syntax/src/res_scanner.ml | ocaml | We hide the implementation detail of the scanner reading character. Our char
will also contain the special -1 value to indicate end-of-file. This isn't
ideal; we should clean this up
current character
character offset
current line offset
current line number
line number
offset of the beginning of the line (number
of characters between the beginning of the scanner and the beginning
of the line)
[pos_cnum] is the offset of the position (number of
characters between the beginning of the scanner and the position).
What about CRLF (\r + \n) on windows?
* \r\n will always be terminated by a \n
* -> we can just bump the line count on \n
generic helpers
larger than any legal value
scanning helpers
TODO: this isn't great
hex
integer part
exponent part
suffix
TODO: are we disregarding the current char...? Should be a quote
line break
TODO: do we really need to create a new buffer instead of substring once?
\ already consumed
Allow \0
hex
consume '}' in '\u{7A}'
unknown escape sequence
* TODO: we should warn the user here. Let's not make it a hard error for now, for reason compat
let pos = position scanner in
let msg =
if ch == -1 then "unclosed escape sequence"
else "unknown escape sequence"
in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg)
assumption: we've just matched a quote
If the text needs changing, a buffer is used
'\' consumed
consume '}' in '\u{7A}'
Consume \'
TODO: do we know it's \' ?
assumption: we're only ever using this helper in `scan` after detecting a comment
no /**/
/***
invariant: depth > 0 right after this match. See assumption
if starting } here, consume it
line break
peeking 0 char
careful with this one! We're next-ing _once_ (not twice),
then relying on matching on the quote
special cases
if we arrive here, we're dealing with an unknown character,
* report the error and continue scanning…
misc helpers used elsewhere
< consumed
If an operator has whitespace around both sides, it's a binary operator
TODO: this helper seems out of place
we're gonna put some assertions and invariant checks here because this is
used outside of the scanner's normal invariant assumptions
we need some stronger confidence that endCnum is ok | module Diagnostics = Res_diagnostics
module Token = Res_token
module Comment = Res_comment
type mode = Jsx | Diamond
let hackyEOFChar = Char.unsafe_chr (-1)
type charEncoding = Char.t
type t = {
filename: string;
src: string;
mutable err:
startPos:Lexing.position ->
endPos:Lexing.position ->
Diagnostics.category ->
unit;
mutable mode: mode list;
}
let setDiamondMode scanner = scanner.mode <- Diamond :: scanner.mode
let setJsxMode scanner = scanner.mode <- Jsx :: scanner.mode
let popMode scanner mode =
match scanner.mode with
| m :: ms when m = mode -> scanner.mode <- ms
| _ -> ()
let inDiamondMode scanner =
match scanner.mode with
| Diamond :: _ -> true
| _ -> false
let inJsxMode scanner =
match scanner.mode with
| Jsx :: _ -> true
| _ -> false
let position scanner =
Lexing.
{
pos_fname = scanner.filename;
pos_lnum = scanner.lnum;
pos_bol = scanner.lineOffset;
pos_cnum = scanner.offset;
}
Small debugging util
❯ echo ' let msg = " hello " ' | ./lib / rescript.exe
let msg = " hello "
^-^ let 0 - 3
let msg = " hello "
^-^ msg 4 - 7
let msg = " hello "
^ = 8 - 9
let msg = " hello "
^-----^ string " hello " 10 - 17
let msg = " hello "
^ eof 18 - 18
let msg = " hello "
❯ echo 'let msg = "hello"' | ./lib/rescript.exe
let msg = "hello"
^-^ let 0-3
let msg = "hello"
^-^ msg 4-7
let msg = "hello"
^ = 8-9
let msg = "hello"
^-----^ string "hello" 10-17
let msg = "hello"
^ eof 18-18
let msg = "hello"
*)
let _printDebug ~startPos ~endPos scanner token =
let open Lexing in
print_string scanner.src;
print_string ((String.make [@doesNotRaise]) startPos.pos_cnum ' ');
print_char '^';
(match endPos.pos_cnum - startPos.pos_cnum with
| 0 -> if token = Token.Eof then () else assert false
| 1 -> ()
| n ->
print_string ((String.make [@doesNotRaise]) (n - 2) '-');
print_char '^');
print_char ' ';
print_string (Res_token.toString token);
print_char ' ';
print_int startPos.pos_cnum;
print_char '-';
print_int endPos.pos_cnum;
print_endline ""
[@@live]
let next scanner =
let nextOffset = scanner.offset + 1 in
(match scanner.ch with
| '\n' ->
scanner.lineOffset <- nextOffset;
scanner.lnum <- scanner.lnum + 1
| _ -> ());
if nextOffset < String.length scanner.src then (
scanner.offset <- nextOffset;
scanner.ch <- String.unsafe_get scanner.src scanner.offset)
else (
scanner.offset <- String.length scanner.src;
scanner.ch <- hackyEOFChar)
let next2 scanner =
next scanner;
next scanner
let next3 scanner =
next scanner;
next scanner;
next scanner
let peek scanner =
if scanner.offset + 1 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 1)
else hackyEOFChar
let peek2 scanner =
if scanner.offset + 2 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 2)
else hackyEOFChar
let peek3 scanner =
if scanner.offset + 3 < String.length scanner.src then
String.unsafe_get scanner.src (scanner.offset + 3)
else hackyEOFChar
let make ~filename src =
{
filename;
src;
err = (fun ~startPos:_ ~endPos:_ _ -> ());
ch = (if src = "" then hackyEOFChar else String.unsafe_get src 0);
offset = 0;
lineOffset = 0;
lnum = 1;
mode = [];
}
let isWhitespace ch =
match ch with
| ' ' | '\t' | '\n' | '\r' -> true
| _ -> false
let rec skipWhitespace scanner =
if isWhitespace scanner.ch then (
next scanner;
skipWhitespace scanner)
let digitValue ch =
match ch with
| '0' .. '9' -> Char.code ch - 48
| 'a' .. 'f' -> Char.code ch - Char.code 'a' + 10
| 'A' .. 'F' -> Char.code ch + 32 - Char.code 'a' + 10
let scanIdentifier scanner =
let startOff = scanner.offset in
let rec skipGoodChars scanner =
match scanner.ch with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '\'' ->
next scanner;
skipGoodChars scanner
| _ -> ()
in
skipGoodChars scanner;
let str =
(String.sub [@doesNotRaise]) scanner.src startOff (scanner.offset - startOff)
in
if '{' == scanner.ch && str = "list" then (
next scanner;
Token.lookupKeyword "list{")
else Token.lookupKeyword str
let scanDigits scanner ~base =
if base <= 10 then
let rec loop scanner =
match scanner.ch with
| '0' .. '9' | '_' ->
next scanner;
loop scanner
| _ -> ()
in
loop scanner
else
let rec loop scanner =
match scanner.ch with
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' | '_' ->
next scanner;
loop scanner
| _ -> ()
in
loop scanner
float : ( 0 … 9 ) { 0 … 9∣ _ } [ . { 0 … 9∣ _ } ] [ ( e∣ E ) [ + ∣ - ] ( 0 … 9 ) { 0 … 9∣ _ } ]
let scanNumber scanner =
let startOff = scanner.offset in
let base =
match scanner.ch with
| '0' -> (
match peek scanner with
| 'x' | 'X' ->
next2 scanner;
16
| 'o' | 'O' ->
next2 scanner;
8
| 'b' | 'B' ->
next2 scanner;
2
| _ ->
next scanner;
8)
| _ -> 10
in
scanDigits scanner ~base;
let isFloat =
if '.' == scanner.ch then (
next scanner;
scanDigits scanner ~base;
true)
else false
in
let isFloat =
match scanner.ch with
| 'e' | 'E' | 'p' | 'P' ->
(match peek scanner with
| '+' | '-' -> next2 scanner
| _ -> next scanner);
scanDigits scanner ~base;
true
| _ -> isFloat
in
let literal =
(String.sub [@doesNotRaise]) scanner.src startOff (scanner.offset - startOff)
in
let suffix =
match scanner.ch with
| 'n' ->
let msg =
"Unsupported number type (nativeint). Did you mean `" ^ literal ^ "`?"
in
let pos = position scanner in
scanner.err ~startPos:pos ~endPos:pos (Diagnostics.message msg);
next scanner;
Some 'n'
| ('g' .. 'z' | 'G' .. 'Z') as ch ->
next scanner;
Some ch
| _ -> None
in
if isFloat then Token.Float {f = literal; suffix}
else Token.Int {i = literal; suffix}
let scanExoticIdentifier scanner =
next scanner;
let buffer = Buffer.create 20 in
let startPos = position scanner in
let rec scan () =
match scanner.ch with
| '"' -> next scanner
| '\n' | '\r' ->
let endPos = position scanner in
scanner.err ~startPos ~endPos
(Diagnostics.message "A quoted identifier can't contain line breaks.");
next scanner
| ch when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos
(Diagnostics.message "Did you forget a \" here?")
| ch ->
Buffer.add_char buffer ch;
next scanner;
scan ()
in
scan ();
Token.Lident (Buffer.contents buffer)
let scanStringEscapeSequence ~startPos scanner =
let scan ~n ~base ~max =
let rec loop n x =
if n == 0 then x
else
let d = digitValue scanner.ch in
if d >= base then (
let pos = position scanner in
let msg =
if scanner.ch == hackyEOFChar then "unclosed escape sequence"
else "unknown escape sequence"
in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg);
-1)
else
let () = next scanner in
loop (n - 1) ((x * base) + d)
in
let x = loop n 0 in
if x > max || (0xD800 <= x && x < 0xE000) then
let pos = position scanner in
let msg = "escape sequence is invalid unicode code point" in
scanner.err ~startPos ~endPos:pos (Diagnostics.message msg)
in
match scanner.ch with
| 'n' | 't' | 'b' | 'r' | '\\' | ' ' | '\'' | '"' -> next scanner
| '0'
when let c = peek scanner in
c < '0' || c > '9' ->
next scanner
| '0' .. '9' -> scan ~n:3 ~base:10 ~max:255
| 'x' ->
next scanner;
scan ~n:2 ~base:16 ~max:255
| 'u' -> (
next scanner;
match scanner.ch with
| '{' -> (
unicode code point escape sequence : ' \u{7A } ' , one or more hex digits
next scanner;
let x = ref 0 in
while
match scanner.ch with
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
do
x := (!x * 16) + digitValue scanner.ch;
next scanner
done;
match scanner.ch with
| '}' -> next scanner
| _ -> ())
| _ -> scan ~n:4 ~base:16 ~max:Res_utf8.max)
| _ ->
()
let scanString scanner =
let startPosWithQuote = position scanner in
next scanner;
let buf = Buffer.create 0 in
let firstCharOffset = scanner.offset in
let lastOffsetInBuf = ref firstCharOffset in
let bringBufUpToDate ~startOffset =
let strUpToNow =
(String.sub scanner.src !lastOffsetInBuf
(startOffset - !lastOffsetInBuf) [@doesNotRaise])
in
Buffer.add_string buf strUpToNow;
lastOffsetInBuf := startOffset
in
let result ~firstCharOffset ~lastCharOffset =
if Buffer.length buf = 0 then
(String.sub [@doesNotRaise]) scanner.src firstCharOffset
(lastCharOffset - firstCharOffset)
else (
bringBufUpToDate ~startOffset:lastCharOffset;
Buffer.contents buf)
in
let rec scan () =
match scanner.ch with
| '"' ->
let lastCharOffset = scanner.offset in
next scanner;
result ~firstCharOffset ~lastCharOffset
| '\\' ->
let startPos = position scanner in
let startOffset = scanner.offset + 1 in
next scanner;
scanStringEscapeSequence ~startPos scanner;
let endOffset = scanner.offset in
convertOctalToHex ~startOffset ~endOffset
| ch when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos:startPosWithQuote ~endPos Diagnostics.unclosedString;
let lastCharOffset = scanner.offset in
result ~firstCharOffset ~lastCharOffset
| _ ->
next scanner;
scan ()
and convertOctalToHex ~startOffset ~endOffset =
let len = endOffset - startOffset in
let isDigit = function
| '0' .. '9' -> true
| _ -> false
in
let txt = scanner.src in
let isNumericEscape =
len = 3
&& (isDigit txt.[startOffset] [@doesNotRaise])
&& (isDigit txt.[startOffset + 1] [@doesNotRaise])
&& (isDigit txt.[startOffset + 2] [@doesNotRaise])
in
if isNumericEscape then (
let strDecimal = (String.sub txt startOffset 3 [@doesNotRaise]) in
bringBufUpToDate ~startOffset;
let strHex = Res_string.convertDecimalToHex ~strDecimal in
lastOffsetInBuf := startOffset + 3;
Buffer.add_string buf strHex;
scan ())
else scan ()
in
Token.String (scan ())
let scanEscape scanner =
let offset = scanner.offset - 1 in
let convertNumber scanner ~n ~base =
let x = ref 0 in
for _ = n downto 1 do
let d = digitValue scanner.ch in
x := (!x * base) + d;
next scanner
done;
let c = !x in
if Res_utf8.isValidCodePoint c then c else Res_utf8.repl
in
let codepoint =
match scanner.ch with
| '0' .. '9' -> convertNumber scanner ~n:3 ~base:10
| 'b' ->
next scanner;
8
| 'n' ->
next scanner;
10
| 'r' ->
next scanner;
13
| 't' ->
next scanner;
009
| 'x' ->
next scanner;
convertNumber scanner ~n:2 ~base:16
| 'o' ->
next scanner;
convertNumber scanner ~n:3 ~base:8
| 'u' -> (
next scanner;
match scanner.ch with
| '{' ->
unicode code point escape sequence : ' \u{7A } ' , one or more hex digits
next scanner;
let x = ref 0 in
while
match scanner.ch with
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
do
x := (!x * 16) + digitValue scanner.ch;
next scanner
done;
(match scanner.ch with
| '}' -> next scanner
| _ -> ());
let c = !x in
if Res_utf8.isValidCodePoint c then c else Res_utf8.repl
| _ ->
unicode escape sequence : ' \u007A ' , exactly 4 hex digits
convertNumber scanner ~n:4 ~base:16)
| ch ->
next scanner;
Char.code ch
in
let contents =
(String.sub [@doesNotRaise]) scanner.src offset (scanner.offset - offset)
in
next scanner;
Token.Codepoint {c = codepoint; original = contents}
let scanSingleLineComment scanner =
let startOff = scanner.offset in
let startPos = position scanner in
let rec skip scanner =
match scanner.ch with
| '\n' | '\r' -> ()
| ch when ch == hackyEOFChar -> ()
| _ ->
next scanner;
skip scanner
in
skip scanner;
let endPos = position scanner in
Token.Comment
(Comment.makeSingleLineComment
~loc:Location.{loc_start = startPos; loc_end = endPos; loc_ghost = false}
((String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - startOff)))
let scanMultiLineComment scanner =
let contentStartOff =
scanner.offset + if docComment then if standalone then 4 else 3 else 2
in
let startPos = position scanner in
let rec scan ~depth =
match (scanner.ch, peek scanner) with
| '/', '*' ->
next2 scanner;
scan ~depth:(depth + 1)
| '*', '/' ->
next2 scanner;
if depth > 1 then scan ~depth:(depth - 1)
| ch, _ when ch == hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos Diagnostics.unclosedComment
| _ ->
next scanner;
scan ~depth
in
scan ~depth:0;
let length = scanner.offset - 2 - contentStartOff in
in case of EOF
Token.Comment
(Comment.makeMultiLineComment ~docComment ~standalone
~loc:
Location.
{loc_start = startPos; loc_end = position scanner; loc_ghost = false}
((String.sub [@doesNotRaise]) scanner.src contentStartOff length))
let scanTemplateLiteralToken scanner =
let startOff = scanner.offset in
if scanner.ch == '}' then next scanner;
let startPos = position scanner in
let rec scan () =
let lastPos = position scanner in
match scanner.ch with
| '`' ->
next scanner;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - 1 - startOff)
in
Token.TemplateTail (contents, lastPos)
| '$' -> (
match peek scanner with
| '{' ->
next2 scanner;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(scanner.offset - 2 - startOff)
in
Token.TemplatePart (contents, lastPos)
| _ ->
next scanner;
scan ())
| '\\' -> (
match peek scanner with
| '`' | '\\' | '$' | '\n' | '\r' ->
next2 scanner;
scan ()
| _ ->
next scanner;
scan ())
| ch when ch = hackyEOFChar ->
let endPos = position scanner in
scanner.err ~startPos ~endPos Diagnostics.unclosedTemplate;
let contents =
(String.sub [@doesNotRaise]) scanner.src startOff
(max (scanner.offset - 1 - startOff) 0)
in
Token.TemplateTail (contents, lastPos)
| _ ->
next scanner;
scan ()
in
let token = scan () in
let endPos = position scanner in
(startPos, endPos, token)
let rec scan scanner =
skipWhitespace scanner;
let startPos = position scanner in
let token =
match scanner.ch with
| 'A' .. 'Z' | 'a' .. 'z' -> scanIdentifier scanner
| '0' .. '9' -> scanNumber scanner
| '`' ->
next scanner;
Token.Backtick
| '~' ->
next scanner;
Token.Tilde
| '?' ->
next scanner;
Token.Question
| ';' ->
next scanner;
Token.Semicolon
| '(' ->
next scanner;
Token.Lparen
| ')' ->
next scanner;
Token.Rparen
| '[' ->
next scanner;
Token.Lbracket
| ']' ->
next scanner;
Token.Rbracket
| '{' ->
next scanner;
Token.Lbrace
| '}' ->
next scanner;
Token.Rbrace
| ',' ->
next scanner;
Token.Comma
| '"' -> scanString scanner
peeking 1 char
| '_' -> (
match peek scanner with
| 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' -> scanIdentifier scanner
| _ ->
next scanner;
Token.Underscore)
| '#' -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.HashEqual
| _ ->
next scanner;
Token.Hash)
| '*' -> (
match peek scanner with
| '*' ->
next2 scanner;
Token.Exponentiation
| '.' ->
next2 scanner;
Token.AsteriskDot
| _ ->
next scanner;
Token.Asterisk)
| '@' -> (
match peek scanner with
| '@' ->
next2 scanner;
Token.AtAt
| _ ->
next scanner;
Token.At)
| '%' -> (
match peek scanner with
| '%' ->
next2 scanner;
Token.PercentPercent
| _ ->
next scanner;
Token.Percent)
| '|' -> (
match peek scanner with
| '|' ->
next2 scanner;
Token.Lor
| '>' ->
next2 scanner;
Token.BarGreater
| _ ->
next scanner;
Token.Bar)
| '&' -> (
match peek scanner with
| '&' ->
next2 scanner;
Token.Land
| _ ->
next scanner;
Token.Band)
| ':' -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.ColonEqual
| '>' ->
next2 scanner;
Token.ColonGreaterThan
| _ ->
next scanner;
Token.Colon)
| '\\' ->
next scanner;
scanExoticIdentifier scanner
| '/' -> (
match peek scanner with
| '/' ->
next2 scanner;
scanSingleLineComment scanner
| '*' -> scanMultiLineComment scanner
| '.' ->
next2 scanner;
Token.ForwardslashDot
| _ ->
next scanner;
Token.Forwardslash)
| '-' -> (
match peek scanner with
| '.' ->
next2 scanner;
Token.MinusDot
| '>' ->
next2 scanner;
Token.MinusGreater
| _ ->
next scanner;
Token.Minus)
| '+' -> (
match peek scanner with
| '.' ->
next2 scanner;
Token.PlusDot
| '+' ->
next2 scanner;
Token.PlusPlus
| '=' ->
next2 scanner;
Token.PlusEqual
| _ ->
next scanner;
Token.Plus)
| '>' -> (
match peek scanner with
| '=' when not (inDiamondMode scanner) ->
next2 scanner;
Token.GreaterEqual
| _ ->
next scanner;
Token.GreaterThan)
| '<' when not (inJsxMode scanner) -> (
match peek scanner with
| '=' ->
next2 scanner;
Token.LessEqual
| _ ->
next scanner;
Token.LessThan)
special handling for JSX <
| '<' -> (
Imagine the following : < div > <
* < indicates the start of a new jsx - element , the parser expects
* the name of a new element after the <
* Example : < div > < div
* But what if we have a / here : example < / in < div></div >
* This signals a closing element . To simulate the two - token lookahead ,
* the < / is emitted as a single new token LessThanSlash
* < indicates the start of a new jsx-element, the parser expects
* the name of a new element after the <
* Example: <div> <div
* But what if we have a / here: example </ in <div></div>
* This signals a closing element. To simulate the two-token lookahead,
* the </ is emitted as a single new token LessThanSlash *)
next scanner;
skipWhitespace scanner;
match scanner.ch with
| '/' ->
next scanner;
Token.LessThanSlash
| '=' ->
next scanner;
Token.LessEqual
| _ -> Token.LessThan)
peeking 2 chars
| '.' -> (
match (peek scanner, peek2 scanner) with
| '.', '.' ->
next3 scanner;
Token.DotDotDot
| '.', _ ->
next2 scanner;
Token.DotDot
| _ ->
next scanner;
Token.Dot)
| '\'' -> (
match (peek scanner, peek2 scanner) with
| '\\', '"' ->
next scanner;
SingleQuote
| '\\', _ ->
next2 scanner;
scanEscape scanner
| ch, '\'' ->
let offset = scanner.offset + 1 in
next3 scanner;
Token.Codepoint
{
c = Char.code ch;
original = (String.sub [@doesNotRaise]) scanner.src offset 1;
}
| ch, _ ->
next scanner;
let offset = scanner.offset in
let codepoint, length =
Res_utf8.decodeCodePoint scanner.offset scanner.src
(String.length scanner.src)
in
for _ = 0 to length - 1 do
next scanner
done;
if scanner.ch = '\'' then (
let contents =
(String.sub [@doesNotRaise]) scanner.src offset length
in
next scanner;
Token.Codepoint {c = codepoint; original = contents})
else (
scanner.ch <- ch;
scanner.offset <- offset;
SingleQuote))
| '!' -> (
match (peek scanner, peek2 scanner) with
| '=', '=' ->
next3 scanner;
Token.BangEqualEqual
| '=', _ ->
next2 scanner;
Token.BangEqual
| _ ->
next scanner;
Token.Bang)
| '=' -> (
match (peek scanner, peek2 scanner) with
| '=', '=' ->
next3 scanner;
Token.EqualEqualEqual
| '=', _ ->
next2 scanner;
Token.EqualEqual
| '>', _ ->
next2 scanner;
Token.EqualGreater
| _ ->
next scanner;
Token.Equal)
| ch when ch == hackyEOFChar ->
next scanner;
Token.Eof
| ch ->
next scanner;
let endPos = position scanner in
scanner.err ~startPos ~endPos (Diagnostics.unknownUchar ch);
let _, _, token = scan scanner in
token
in
let endPos = position scanner in
_ scanner token ;
(startPos, endPos, token)
Imagine : < div > < Navbar / > <
* is ` < ` the start of a jsx - child ? < div …
* or is it the start of a closing tag ? < /div >
* reconsiderLessThan peeks at the next token and
* determines the correct token to disambiguate
* is `<` the start of a jsx-child? <div …
* or is it the start of a closing tag? </div>
* reconsiderLessThan peeks at the next token and
* determines the correct token to disambiguate *)
let reconsiderLessThan scanner =
skipWhitespace scanner;
if scanner.ch == '/' then
let () = next scanner in
Token.LessThanSlash
else Token.LessThan
let isBinaryOp src startCnum endCnum =
if startCnum == 0 then false
else (
assert (endCnum >= 0);
assert (startCnum > 0 && startCnum < String.length src);
let leftOk = isWhitespace (String.unsafe_get src (startCnum - 1)) in
let rightOk =
endCnum >= String.length src
|| isWhitespace (String.unsafe_get src endCnum)
in
leftOk && rightOk)
|
13cb029c5e5e753b5ac67f9cdc33813f4699a2ef5b684a81fe182171d7cadeca | AlacrisIO/legicash-facts | ppx_deriving_rlp_test_data.ml | open Ppx_deriving_rlp_runtime
type foo = A of int | B of float * bool
[@@deriving rlp]
type loi = Loimt | Loicons of { first : int; rest : loi }
[@@deriving rlp]
type wrapped_list1 = Wrap1 of int list
[@@deriving rlp]
type wrapped_list2 = Wrap2 of { value: int list }
[@@deriving rlp]
type wrapped_list3 = { value: int list }
[@@deriving rlp]
(* Type aliases *)
type alias_int = int
[@@deriving rlp]
type alias_list = int list
[@@deriving rlp]
type alias_unit = unit
[@@deriving rlp]
(* Polymorphic variants *)
type matter1 =
[ `Solid of string
| `Liquid of int
| `Gas of float ]
[@@deriving rlp]
type matter2 =
[ matter1
| `Plasma of char
| `Unknown ]
[@@deriving rlp]
(* Type parameters *)
type ('k, 'v) seq_tree_map = StmLeaf of 'v
| StmNode of ('k * (('k,'v) seq_tree_map)) list
[@@deriving rlp]
(* Using { rlping = expression } attribute *)
type int_seq = int Seq.t
[@@deriving rlp { rlping = rlping_by_isomorphism List.to_seq List.of_seq (list_rlping int_rlping) }]
| null | https://raw.githubusercontent.com/AlacrisIO/legicash-facts/5d3663bade68c09bed47b3f58fa12580f38fdb46/src/ppx_deriving_rlp/test/ppx_deriving_rlp_test_data.ml | ocaml | Type aliases
Polymorphic variants
Type parameters
Using { rlping = expression } attribute | open Ppx_deriving_rlp_runtime
type foo = A of int | B of float * bool
[@@deriving rlp]
type loi = Loimt | Loicons of { first : int; rest : loi }
[@@deriving rlp]
type wrapped_list1 = Wrap1 of int list
[@@deriving rlp]
type wrapped_list2 = Wrap2 of { value: int list }
[@@deriving rlp]
type wrapped_list3 = { value: int list }
[@@deriving rlp]
type alias_int = int
[@@deriving rlp]
type alias_list = int list
[@@deriving rlp]
type alias_unit = unit
[@@deriving rlp]
type matter1 =
[ `Solid of string
| `Liquid of int
| `Gas of float ]
[@@deriving rlp]
type matter2 =
[ matter1
| `Plasma of char
| `Unknown ]
[@@deriving rlp]
type ('k, 'v) seq_tree_map = StmLeaf of 'v
| StmNode of ('k * (('k,'v) seq_tree_map)) list
[@@deriving rlp]
type int_seq = int Seq.t
[@@deriving rlp { rlping = rlping_by_isomorphism List.to_seq List.of_seq (list_rlping int_rlping) }]
|
cf05cae249719a08306bd3827f88af5820b9c5951054ca2b4a0d37392c6fc396 | jyp/topics | IncrementalParserWithGeneralizedErrorCorrection.hs | Copyright ( c ) JP Bernardy 2008
{-# OPTIONS -fglasgow-exts #-}
module Yi.IncrementalParse (Process, Void,
recoverWith, symbol, eof, lookNext, runPolish,
runP, profile, pushSyms, pushEof, evalR,
P, AlexState (..), scanner) where
import Yi.Lexer.Alex (AlexState (..))
import Yi.Prelude
import Prelude (Ordering(..))
import Yi.Syntax
import Data.List hiding (map, minimumBy)
import Data.Char
import Data.Maybe (listToMaybe)
----------------------------------------
- Based on a mix between " Polish Parsers , Step by Step ( Hughes and Swierstra ) " ,
and " Parallel Parsing Processes ( Claessen ) "
It 's strongly advised to read the papers ! :)
- The parser has " online " behaviour .
This is a big advantage because we do n't have to parse the whole file to
begin syntax highlight the beginning of it .
- Basic error correction
- Based on Applicative functors .
This is not as powerful as Monadic parsers , but easier to work with . This is
needed if we want to build the result lazily .
------------------------------------------
- Based on a mix between "Polish Parsers, Step by Step (Hughes and Swierstra)",
and "Parallel Parsing Processes (Claessen)"
It's strongly advised to read the papers! :)
- The parser has "online" behaviour.
This is a big advantage because we don't have to parse the whole file to
begin syntax highlight the beginning of it.
- Basic error correction
- Based on Applicative functors.
This is not as powerful as Monadic parsers, but easier to work with. This is
needed if we want to build the result lazily.
-------------------------------------------}
data Void
type Process s a = Steps s a (Steps s Void Void)
-- | Our parsing processes.
-- To understand the design of this data type it is important to consider the
-- basic design goal: Our parser should return a (partial) result as soon as
-- possible, that is, as soon as only one of all possible parses of an input
-- can succeed. This also means we want to be able to return partial results.
-- We therefore have to transform our parse tree into a linearized form that
-- allows us to return parts of it as we parse them. Consider the following
-- data type:
--
> data
-- > ex1 = Node (Leaf 1) (Node (Leaf 2) (Leaf 3))
--
-- Provided we know the arity of each constructor, we can unambiguously
-- represent @ex1@ (without using parentheses to resolve ambiguity) as:
--
-- > Node Leaf 1 Node Leaf 2 Leaf 3
--
-- This is simply a pre-order printing of the tree type and, in this case, is
-- exactly how we defined @ex1@ without all the parentheses. It would,
-- however, be unnecessarily complicated to keep track of the arity of each
-- constructor, so we use a well-known trick: currying. Note, that the
original definition of @ex1@ is actually a shorter notation for
--
> ( ( Node $ ( Leaf $ 1 ) ) $ ( ( Node $ ( Leaf $ 2 ) ) $ ( Leaf $ 3 ) ) )
--
-- or as a tree
--
-- > $
-- > .-------------'----------------------.
-- > $ $
-- > .--'-------. .-------------'-------.
-- > Node $ $ $
-- > .--'-. .--'-------. .--'-.
> Leaf 1 Node $ Leaf 3
-- > .--'-.
> Leaf 2
--
where @$@ represents function application . We can print this tree in
-- prefix-order:
--
> ( $ ) ( $ ) Node ( $ ) Leaf 1 ( $ ) ( $ ) Node ( $ ) Leaf 2 ( $ ) Leaf 3
--
This consists of only two types of nodes -- values and applications -- but
-- we can construct values of any (non-strict) Haskell data type with it.
--
-- Unfortunately, it is a bit tricky to type those kinds of expressions in
-- Haskell. [XXX: example; develop solution step by step; continuations]
--
-- The parameter @r@ represents the type of the remainder of our expression.
TODO : Replace ' Doc : ' by ^ when haddock supports GADTs
data Steps s a r where
-- These constructors describe the tree of values, as above
Val :: a -> Steps s b r -> Steps s a (Steps s b r)
Doc : The process that returns the value of type @a@ which is followed by a parser returning a value of type @b@.
App :: Steps s (b -> a) (Steps s b r) -> Steps s a r
Doc : Takes a process that returns a function @f@ of type @b - > a@ and is
followed by a process returning a value @x@ of type @b@. The resulting
process will return the result of applying the function @f@ to @x@.
Stop :: Steps s Void Void
-- These constructors describe the parser state
Shift :: Steps s a r -> Steps s a r
Done :: Steps s a r -> Steps s a r
-- Doc: The parser that signals success. The argument is the continuation.
Fails :: Steps s a r
-- Doc: The parser that signals failure.
Dislike :: Steps s a r -> Steps s a r
Suspend :: ([s] -> Steps s a r) -> Steps s a r
-- Doc: A suspension of the parser (this is the part borrowed from
Parallel Parsing Processes ) The parameter to suspend 's
-- continuation is a whole chunk of text; [] represents the
-- end of the input
Best :: Ordering -> Profile -> Steps s a r -> Steps s a r -> Steps s a r
profile ! ! s = number of found to do s Shifts
data Profile = PSusp | PFail | PRes Int | !Int :> Profile
deriving Show
mapSucc PSusp = PSusp
mapSucc PFail = PFail
mapSucc (PRes x) = PRes (succ x)
mapSucc (x :> xs) = succ x :> mapSucc xs
-- Map lookahead to maximum dislike difference we accept. When looking much further,
we are more prone to discard smaller differences . It 's essential that this drops to zero when
-- its argument increases, so that we can discard things with dislikes using only
-- finite lookahead.
dislikeThreshold :: Int -> Int
dislikeThreshold n | n < 2 = 1
dislikeThreshold n = 0
| Compute the combination of two profiles , as well as which one is the best .
better :: Int -> Profile -> Profile -> (Ordering, Profile)
better _ PFail p = (GT, p) -- avoid failure
better _ p PFail = (LT, p)
better _ PSusp _ = (EQ, PSusp) -- could not decide before suspension => leave undecided.
better _ _ PSusp = (EQ, PSusp)
two results , just pick the best .
better lk xs@(PRes x) (y:>ys) = if x == 0 || y-x > dislikeThreshold lk then (LT, xs) else min x y +> better (lk+1) xs ys
better lk (y:>ys) xs@(PRes x) = if x == 0 || y-x > dislikeThreshold lk then (GT, xs) else min x y +> better (lk+1) ys xs
better lk (x:>xs) (y:>ys)
| x == 0 && y == 0 = rec -- never drop things with no error: this ensures to find a correct parse if it exists.
| y - x > threshold = (LT, x:>xs) -- if at any point something is too disliked, drop it.
| x - y > threshold = (GT, y:>ys)
| otherwise = rec
where threshold = dislikeThreshold lk
rec = min x y +> better (lk + 1) xs ys
x +> ~(ordering, xs) = (ordering, x :> xs)
profile :: Steps s a r -> Profile
profile (Val _ p) = profile p
profile (App p) = profile p
profile (Stop) = error "profile: Stop" -- this should always be "hidden" by Done
profile (Shift p) = 0 :> profile p
success with zero dislikes
profile (Fails) = PFail
profile (Dislike p) = mapSucc (profile p)
profile (Suspend _) = PSusp
profile (Best _ pr _ _) = pr
instance Show (Steps s a r) where
show (Val _ p) = "v" ++ show p
show (App p) = "*" ++ show p
show (Stop) = "1"
show (Shift p) = ">" ++ show p
show (Done p) = "!" ++ show p
show (Dislike p) = "?" ++ show p
show (Fails) = "0"
show (Suspend _) = "..."
show (Best _ _ p q) = "(" ++ show p ++ ")" ++ show q
-- | Right-eval a fully defined process (ie. one that has no Suspend)
-- Returns value and continuation.
evalR :: Steps s a r -> (a, r)
evalR z@(Val a r) = (a,r)
evalR (App s) = let (f, s') = evalR s
(x, s'') = evalR s'
in (f x, s'')
evalR Stop = error "evalR: Can't create values of type Void"
evalR (Shift v) = evalR v
evalR (Done v) = evalR v
evalR (Dislike v) = evalR v
evalR (Fails) = error "evalR: No parse!"
evalR (Suspend _) = error "evalR: Not fully evaluated!"
evalR (Best choice _ p q) = case choice of
LT -> evalR p
GT -> evalR q
EQ -> error $ "evalR: Ambiguous parse: " ++ show p ++ " ~~~ " ++ show q
-- | Pre-compute a left-prefix of some steps (as far as possible)
evalL :: Steps s a r -> Steps s a r
evalL (Shift p) = evalL p
evalL (Dislike p) = evalL p
evalL (Val x r) = Val x (evalL r)
evalL (App f) = case evalL f of
(Val a (Val b r)) -> Val (a b) r
(Val f1 (App (Val f2 r))) -> App (Val (f1 . f2) r)
r -> App r
evalL x@(Best choice _ p q) = case choice of
LT -> evalL p
GT -> evalL q
EQ -> x -- don't know where to go: don't speculate on evaluating either branch.
evalL x = x
-- | Intelligent, caching best.
iBest p q = let ~(choice, pr) = better 0 (profile p) (profile q) in Best choice pr p q
-- | Push a chunk of symbols or eof in the process. This forces some suspensions.
push :: Maybe [s] -> Steps s a r -> Steps s a r
push (Just []) p = p -- nothing more left to push
push ss p = case p of
(Suspend f) -> case ss of
Nothing -> f []
Just ss' -> f ss'
(Dislike p') -> Dislike (push ss p')
(Shift p') -> Shift (push ss p')
(Done p') -> Done (push ss p')
(Val x p') -> Val x (push ss p')
(App p') -> App (push ss p')
Stop -> Stop
Fails -> Fails
Best _ _ p' q' -> iBest (push ss p') (push ss q')
-- TODO: it would be nice to be able to reuse the profile here.
repush :: [s] -> Steps s a r -> Steps s a r
repush [] = pushEof
repush input = pushSyms input
-- | Push some symbols.
pushSyms :: [s] -> Steps s a r -> Steps s a r
pushSyms x = push (Just x)
-- | Push eof
pushEof :: Steps s a r -> Steps s a r
pushEof = push Nothing
-- | A parser. (This is actually a parsing process segment)
newtype P s a = P (forall b r. Steps s b r -> Steps s a (Steps s b r))
instance Functor (P s) where
fmap f x = pure f <*> x
instance Applicative (P s) where
P f <*> P x = P (App . f . x)
pure x = P (Val x)
instance Alternative (P s) where
empty = P $ \_fut -> Fails
P a <|> P b = P $ \fut -> iBest (a fut) (b fut)
runP :: forall s a. P s a -> Process s a
runP (P p) = p (Done Stop)
-- | Run a parser.
runPolish :: forall s a. P s a -> [s] -> a
runPolish p input = fst $ evalR $ pushEof $ pushSyms input $ runP p
-- | Parse a symbol
symbol :: (s -> Bool) -> P s s
symbol f = P $ \fut -> Suspend $ \input ->
case input of
[] -> Fails -- This is the eof!
(s:ss) -> if f s then Shift (Val s (push (Just ss) (fut)))
else Fails
lookNext :: (Maybe s -> Bool) -> P s ()
lookNext f = P $ \fut -> Suspend $ \input ->
if (f $ listToMaybe input) then Val () (repush input fut)
else Fails
| Parse the eof
eof :: P s ()
eof = P $ \fut -> Suspend $ \input ->
case input of
[] -> Shift (Val () (push Nothing fut))
_ -> Fails
-- | Parse the same thing as the argument, but will be used only as
-- backup. ie, it will be used only if disjuncted with a failing
-- parser.
recoverWith :: forall s a. P s a -> P s a
recoverWith (P p) = P (Dislike . p)
----------------------------------------------------
type State st token result = (st, Process token result)
scanner :: forall st token result. P token result -> Scanner st token -> Scanner (State st token result) result
scanner parser input = Scanner
{
scanInit = (scanInit input, runP parser),
scanLooked = scanLooked input . fst,
scanRun = run,
scanEmpty = fst $ evalR $ pushEof $ runP parser
}
where
run :: State st token result -> [(State st token result, result)]
run (st,process) = updateState0 process $ scanRun input st
updateState0 :: Process token result -> [(st,token)] -> [(State st token result, result)]
updateState0 _ [] = []
updateState0 curState toks@((st,tok):rest) = ((st, curState), result) : updateState0 nextState rest
where nextState = evalL $ pushSyms [tok] $ curState
result = fst $ evalR $ pushEof $ pushSyms (fmap snd toks) $ curState
------------------
data Expr = V Int | Add Expr Expr
deriving Show
pExprParen = symbol (== '(') *> pExprTop <* symbol (== ')')
pExprVal = V <$> toInt <$> symbol (isDigit)
where toInt c = ord c - ord '0'
pExprAtom = pExprVal <|> pExprParen
pExprAdd = pExprAtom <|> Add <$> pExprAtom <*> (symbol (== '+') *> pExprAdd)
pExprTop = pExprAdd
pExpr = pExprTop <* eof
| null | https://raw.githubusercontent.com/jyp/topics/8442d82711a02ba1356fd4eca598d1368684fa69/Parsers/IncrementalParserWithGeneralizedErrorCorrection.hs | haskell | # OPTIONS -fglasgow-exts #
--------------------------------------
----------------------------------------
-----------------------------------------}
| Our parsing processes.
To understand the design of this data type it is important to consider the
basic design goal: Our parser should return a (partial) result as soon as
possible, that is, as soon as only one of all possible parses of an input
can succeed. This also means we want to be able to return partial results.
We therefore have to transform our parse tree into a linearized form that
allows us to return parts of it as we parse them. Consider the following
data type:
> ex1 = Node (Leaf 1) (Node (Leaf 2) (Leaf 3))
Provided we know the arity of each constructor, we can unambiguously
represent @ex1@ (without using parentheses to resolve ambiguity) as:
> Node Leaf 1 Node Leaf 2 Leaf 3
This is simply a pre-order printing of the tree type and, in this case, is
exactly how we defined @ex1@ without all the parentheses. It would,
however, be unnecessarily complicated to keep track of the arity of each
constructor, so we use a well-known trick: currying. Note, that the
or as a tree
> $
> .-------------'----------------------.
> $ $
> .--'-------. .-------------'-------.
> Node $ $ $
> .--'-. .--'-------. .--'-.
> .--'-.
prefix-order:
values and applications -- but
we can construct values of any (non-strict) Haskell data type with it.
Unfortunately, it is a bit tricky to type those kinds of expressions in
Haskell. [XXX: example; develop solution step by step; continuations]
The parameter @r@ represents the type of the remainder of our expression.
These constructors describe the tree of values, as above
These constructors describe the parser state
Doc: The parser that signals success. The argument is the continuation.
Doc: The parser that signals failure.
Doc: A suspension of the parser (this is the part borrowed from
continuation is a whole chunk of text; [] represents the
end of the input
Map lookahead to maximum dislike difference we accept. When looking much further,
its argument increases, so that we can discard things with dislikes using only
finite lookahead.
avoid failure
could not decide before suspension => leave undecided.
never drop things with no error: this ensures to find a correct parse if it exists.
if at any point something is too disliked, drop it.
this should always be "hidden" by Done
| Right-eval a fully defined process (ie. one that has no Suspend)
Returns value and continuation.
| Pre-compute a left-prefix of some steps (as far as possible)
don't know where to go: don't speculate on evaluating either branch.
| Intelligent, caching best.
| Push a chunk of symbols or eof in the process. This forces some suspensions.
nothing more left to push
TODO: it would be nice to be able to reuse the profile here.
| Push some symbols.
| Push eof
| A parser. (This is actually a parsing process segment)
| Run a parser.
| Parse a symbol
This is the eof!
| Parse the same thing as the argument, but will be used only as
backup. ie, it will be used only if disjuncted with a failing
parser.
--------------------------------------------------
---------------- | Copyright ( c ) JP Bernardy 2008
module Yi.IncrementalParse (Process, Void,
recoverWith, symbol, eof, lookNext, runPolish,
runP, profile, pushSyms, pushEof, evalR,
P, AlexState (..), scanner) where
import Yi.Lexer.Alex (AlexState (..))
import Yi.Prelude
import Prelude (Ordering(..))
import Yi.Syntax
import Data.List hiding (map, minimumBy)
import Data.Char
import Data.Maybe (listToMaybe)
- Based on a mix between " Polish Parsers , Step by Step ( Hughes and Swierstra ) " ,
and " Parallel Parsing Processes ( Claessen ) "
It 's strongly advised to read the papers ! :)
- The parser has " online " behaviour .
This is a big advantage because we do n't have to parse the whole file to
begin syntax highlight the beginning of it .
- Basic error correction
- Based on Applicative functors .
This is not as powerful as Monadic parsers , but easier to work with . This is
needed if we want to build the result lazily .
- Based on a mix between "Polish Parsers, Step by Step (Hughes and Swierstra)",
and "Parallel Parsing Processes (Claessen)"
It's strongly advised to read the papers! :)
- The parser has "online" behaviour.
This is a big advantage because we don't have to parse the whole file to
begin syntax highlight the beginning of it.
- Basic error correction
- Based on Applicative functors.
This is not as powerful as Monadic parsers, but easier to work with. This is
needed if we want to build the result lazily.
data Void
type Process s a = Steps s a (Steps s Void Void)
> data
original definition of @ex1@ is actually a shorter notation for
> ( ( Node $ ( Leaf $ 1 ) ) $ ( ( Node $ ( Leaf $ 2 ) ) $ ( Leaf $ 3 ) ) )
> Leaf 1 Node $ Leaf 3
> Leaf 2
where @$@ represents function application . We can print this tree in
> ( $ ) ( $ ) Node ( $ ) Leaf 1 ( $ ) ( $ ) Node ( $ ) Leaf 2 ( $ ) Leaf 3
TODO : Replace ' Doc : ' by ^ when haddock supports GADTs
data Steps s a r where
Val :: a -> Steps s b r -> Steps s a (Steps s b r)
Doc : The process that returns the value of type @a@ which is followed by a parser returning a value of type @b@.
App :: Steps s (b -> a) (Steps s b r) -> Steps s a r
Doc : Takes a process that returns a function @f@ of type @b - > a@ and is
followed by a process returning a value @x@ of type @b@. The resulting
process will return the result of applying the function @f@ to @x@.
Stop :: Steps s Void Void
Shift :: Steps s a r -> Steps s a r
Done :: Steps s a r -> Steps s a r
Fails :: Steps s a r
Dislike :: Steps s a r -> Steps s a r
Suspend :: ([s] -> Steps s a r) -> Steps s a r
Parallel Parsing Processes ) The parameter to suspend 's
Best :: Ordering -> Profile -> Steps s a r -> Steps s a r -> Steps s a r
profile ! ! s = number of found to do s Shifts
data Profile = PSusp | PFail | PRes Int | !Int :> Profile
deriving Show
mapSucc PSusp = PSusp
mapSucc PFail = PFail
mapSucc (PRes x) = PRes (succ x)
mapSucc (x :> xs) = succ x :> mapSucc xs
we are more prone to discard smaller differences . It 's essential that this drops to zero when
dislikeThreshold :: Int -> Int
dislikeThreshold n | n < 2 = 1
dislikeThreshold n = 0
| Compute the combination of two profiles , as well as which one is the best .
better :: Int -> Profile -> Profile -> (Ordering, Profile)
better _ p PFail = (LT, p)
better _ _ PSusp = (EQ, PSusp)
two results , just pick the best .
better lk xs@(PRes x) (y:>ys) = if x == 0 || y-x > dislikeThreshold lk then (LT, xs) else min x y +> better (lk+1) xs ys
better lk (y:>ys) xs@(PRes x) = if x == 0 || y-x > dislikeThreshold lk then (GT, xs) else min x y +> better (lk+1) ys xs
better lk (x:>xs) (y:>ys)
| x - y > threshold = (GT, y:>ys)
| otherwise = rec
where threshold = dislikeThreshold lk
rec = min x y +> better (lk + 1) xs ys
x +> ~(ordering, xs) = (ordering, x :> xs)
profile :: Steps s a r -> Profile
profile (Val _ p) = profile p
profile (App p) = profile p
profile (Shift p) = 0 :> profile p
success with zero dislikes
profile (Fails) = PFail
profile (Dislike p) = mapSucc (profile p)
profile (Suspend _) = PSusp
profile (Best _ pr _ _) = pr
instance Show (Steps s a r) where
show (Val _ p) = "v" ++ show p
show (App p) = "*" ++ show p
show (Stop) = "1"
show (Shift p) = ">" ++ show p
show (Done p) = "!" ++ show p
show (Dislike p) = "?" ++ show p
show (Fails) = "0"
show (Suspend _) = "..."
show (Best _ _ p q) = "(" ++ show p ++ ")" ++ show q
evalR :: Steps s a r -> (a, r)
evalR z@(Val a r) = (a,r)
evalR (App s) = let (f, s') = evalR s
(x, s'') = evalR s'
in (f x, s'')
evalR Stop = error "evalR: Can't create values of type Void"
evalR (Shift v) = evalR v
evalR (Done v) = evalR v
evalR (Dislike v) = evalR v
evalR (Fails) = error "evalR: No parse!"
evalR (Suspend _) = error "evalR: Not fully evaluated!"
evalR (Best choice _ p q) = case choice of
LT -> evalR p
GT -> evalR q
EQ -> error $ "evalR: Ambiguous parse: " ++ show p ++ " ~~~ " ++ show q
evalL :: Steps s a r -> Steps s a r
evalL (Shift p) = evalL p
evalL (Dislike p) = evalL p
evalL (Val x r) = Val x (evalL r)
evalL (App f) = case evalL f of
(Val a (Val b r)) -> Val (a b) r
(Val f1 (App (Val f2 r))) -> App (Val (f1 . f2) r)
r -> App r
evalL x@(Best choice _ p q) = case choice of
LT -> evalL p
GT -> evalL q
evalL x = x
iBest p q = let ~(choice, pr) = better 0 (profile p) (profile q) in Best choice pr p q
push :: Maybe [s] -> Steps s a r -> Steps s a r
push ss p = case p of
(Suspend f) -> case ss of
Nothing -> f []
Just ss' -> f ss'
(Dislike p') -> Dislike (push ss p')
(Shift p') -> Shift (push ss p')
(Done p') -> Done (push ss p')
(Val x p') -> Val x (push ss p')
(App p') -> App (push ss p')
Stop -> Stop
Fails -> Fails
Best _ _ p' q' -> iBest (push ss p') (push ss q')
repush :: [s] -> Steps s a r -> Steps s a r
repush [] = pushEof
repush input = pushSyms input
pushSyms :: [s] -> Steps s a r -> Steps s a r
pushSyms x = push (Just x)
pushEof :: Steps s a r -> Steps s a r
pushEof = push Nothing
newtype P s a = P (forall b r. Steps s b r -> Steps s a (Steps s b r))
instance Functor (P s) where
fmap f x = pure f <*> x
instance Applicative (P s) where
P f <*> P x = P (App . f . x)
pure x = P (Val x)
instance Alternative (P s) where
empty = P $ \_fut -> Fails
P a <|> P b = P $ \fut -> iBest (a fut) (b fut)
runP :: forall s a. P s a -> Process s a
runP (P p) = p (Done Stop)
runPolish :: forall s a. P s a -> [s] -> a
runPolish p input = fst $ evalR $ pushEof $ pushSyms input $ runP p
symbol :: (s -> Bool) -> P s s
symbol f = P $ \fut -> Suspend $ \input ->
case input of
(s:ss) -> if f s then Shift (Val s (push (Just ss) (fut)))
else Fails
lookNext :: (Maybe s -> Bool) -> P s ()
lookNext f = P $ \fut -> Suspend $ \input ->
if (f $ listToMaybe input) then Val () (repush input fut)
else Fails
| Parse the eof
eof :: P s ()
eof = P $ \fut -> Suspend $ \input ->
case input of
[] -> Shift (Val () (push Nothing fut))
_ -> Fails
recoverWith :: forall s a. P s a -> P s a
recoverWith (P p) = P (Dislike . p)
type State st token result = (st, Process token result)
scanner :: forall st token result. P token result -> Scanner st token -> Scanner (State st token result) result
scanner parser input = Scanner
{
scanInit = (scanInit input, runP parser),
scanLooked = scanLooked input . fst,
scanRun = run,
scanEmpty = fst $ evalR $ pushEof $ runP parser
}
where
run :: State st token result -> [(State st token result, result)]
run (st,process) = updateState0 process $ scanRun input st
updateState0 :: Process token result -> [(st,token)] -> [(State st token result, result)]
updateState0 _ [] = []
updateState0 curState toks@((st,tok):rest) = ((st, curState), result) : updateState0 nextState rest
where nextState = evalL $ pushSyms [tok] $ curState
result = fst $ evalR $ pushEof $ pushSyms (fmap snd toks) $ curState
data Expr = V Int | Add Expr Expr
deriving Show
pExprParen = symbol (== '(') *> pExprTop <* symbol (== ')')
pExprVal = V <$> toInt <$> symbol (isDigit)
where toInt c = ord c - ord '0'
pExprAtom = pExprVal <|> pExprParen
pExprAdd = pExprAtom <|> Add <$> pExprAtom <*> (symbol (== '+') *> pExprAdd)
pExprTop = pExprAdd
pExpr = pExprTop <* eof
|
c138bfd23372877565849f90eb3bbaea6317c85dd68914e447eed4c8abf1ffe7 | beijaflor-io/haskell-libui | Wrapped.hs | {-# LANGUAGE CApiFFI #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE InterruptibleFFI #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- |
Provides wrappers to make the imperative C API nicer to use in Haskell
--
-- This module should be enough to match how most imperative languages will
-- work with the foreign library, if you're ok with building your GUI
imperatively on the IO Monad , this should be fine
module Graphics.LibUI.FFI.Wrapped
(
-- * Basic API
uiInit
, uiMain
, uiQuit
, uiQueueMain
, uiOnShouldQuit
-- * UI Controls
, CUIControl (..)
, ToCUIControl (..)
, ToCUIControlIO (..)
, uiShow
, uiHide
, uiDestroy
, uiGetParent
, uiSetParent
, uiGetTopLevel
, uiGetVisible
, uiGetEnabled
, uiSetEnabled
-- ** Windows
, CUIWindow (..)
, uiNewWindow
, getBorderless
, setBorderless
, getContentSize
, setContentSize
, onContentSizeChange
, getFullscreen
, setFullscreen
-- ** Labels
, CUILabel (..)
, uiNewLabel
-- ** Layout Controls
-- *** Boxes
, CUIBox (..)
, uiNewHorizontalBox
, uiNewVerticalBox
-- *** Tabs
, CUITabs (..)
, uiNewTabs
, appendTab
, appendTabMargined
, removeTab
-- *** Named Groups
, CUIGroup (..)
, uiNewGroup
-- *** Grids
, CUIGrid (..)
, uiNewGrid
, uiGridAppend
, uiGridInsertAt
, UIAlign (..)
, UIAt (..)
-- *** Separators
, CUISeparator (..)
, uiNewHorizontalSeparator
, uiNewVerticalSeparator
-- ** Input Types
-- *** Buttons
, CUIButton (..)
, uiNewButton
* * *
, CUICheckbox (..)
, uiNewCheckbox
-- *** Text Inputs
, CUIEntry (..)
, uiNewEntry
, uiNewPasswordEntry
, uiNewSearchEntry
, CUISpinbox (..)
, uiNewSpinbox
-- *** Sliders
, CUISlider (..)
, uiNewSlider
-- *** Selects
, CUICombobox (..)
, uiNewCombobox
, CUIEditableCombobox (..)
, uiNewEditableCombobox
-- *** Radio Buttons
, CUIRadioButtons (..)
, uiNewRadioButtons
-- *** Labeled Forms
, CUIForm (..)
, uiNewForm
, uiFormAppend
-- *** Date & Time Pickers
, CUIDateTimePicker (..)
, uiNewDatePicker
, uiNewTimePicker
, uiNewDateTimePicker
* * *
, CUIFontButton (..)
, uiNewFontButton
-- *** Color Picker
, CUIColorButton (..)
, uiNewColorButton
* * * Inputs
, CUIMultilineEntry (..)
, appendText
, uiNewMultilineEntry
, uiNewNonWrappingMultilineEntry
-- ** Progress Indicators
, CUIProgressBar (..)
, uiNewProgressBar
* * The Menubar
, CUIMenu (..)
, uiNewMenu
, uiMenuAppendItem
, uiMenuAppendCheckItem
, uiMenuAppendQuitItem
, uiMenuAppendPreferencesItem
, uiMenuAppendAboutItem
, uiMenuAppendSeparator
, CUIMenuItem (..)
, uiMenuItemEnable
, uiMenuItemDisable
-- ** UI Alerts and Dialogs
, uiOpenFile
, uiSaveFile
, uiMsgBox
, uiMsgBoxError
-- * Type-Classes
, HasSetTitle (..)
, HasGetTitle (..)
, HasSetPosition (..)
, HasGetPosition (..)
, HasGetText (..)
, HasSetText (..)
, HasSetValue (..)
, HasGetValue (..)
, HasGetChecked (..)
, HasSetChecked (..)
, HasSetChild (..)
, HasAppendChild (..)
, HasRemoveChild (..)
, HasOnPositionChanged (..)
, HasOnClicked (..)
, HasOnChanged (..)
, HasOnClosing (..)
, HasOnShouldQuit (..)
, HasSetPadded (..)
, HasGetPadded (..)
, HasSetMargined (..)
, HasGetMargined (..)
, HasSetReadOnly (..)
, HasGetReadOnly (..)
, HasAppendOption (..)
, ToAppendInput (..)
, appendIOChild
, appendIOChildStretchy
-- * Internal functions
-- ** Ticking the loop manually
, uiMainSteps, uiMainStep, hasMainM, getHasMain, setHasMain
-- ** Other
, boolToNum, numToBool, toCUIAlign, toCUIAt, peekCStringSafe
-- * Raw FFI
, module Graphics.LibUI.FFI.Raw
)
where
import Control.Concurrent
import Control.Monad (when, (>=>))
import Control.Monad.Loops
import Foreign hiding (void)
import Foreign.C
import System.IO.Unsafe
import Graphics.LibUI.FFI.Raw
-- * Basic API
-- | Initialize the UI options. Needs to be called before any UI building
--
-- @
-- main = do
-- uiInit
-- -- ...
-- uiMain
-- @
uiInit :: IO ()
uiInit =
alloca $ \ptr -> do
poke ptr (CSize (fromIntegral (sizeOf (CSize 0))))
c_uiInit ptr
-- | Start the main loop
uiMain :: IO ()
uiMain = do
uiMainSteps
-- TODO Replace with uiMainStepExpire or something
whileM_ getHasMain (uiMainStep 1)
-- | Quit the main loop
uiQuit :: IO ()
uiQuit = do
setHasMain False
c_uiQuit
-- |
-- Actions not run on the main thread (that aren't just callbacks), need to be
queued with @uiQueueMain@
--
-- It calls 'c_uiQueueMain' under the hood
--
-- @
-- main = do
-- -- .. 'uiInit' & create a window
pg < - ' uiNewProgressBar '
-- ^ Create a progressbar
-- 'forkIO' $ do
' forM _ ' [ 0 .. 100 ] $ \i - > do
' threadDelay ' ( 1000 * 100 )
' uiQueueMain ' ( ' setValue ' pg i )
-- ^ Fork a thread
-- .. ' ' & ' uiMain '
-- @
uiQueueMain :: IO () -> IO ()
uiQueueMain a = do
m <- getHasMain
when m $ do
a' <- c_wrap1 $ \_ -> do
r <- a
return ()
c_uiQueueMain a' nullPtr
-- | Add a hook to before quit
uiOnShouldQuit :: IO Int -> IO ()
uiOnShouldQuit a = do
f <- castFunPtr <$> c_wrap1I (\_ -> fromIntegral <$> a)
c_uiOnShouldQuit f nullPtr
-- * Shared API
| Controls with ` ui ... SetTitle ` functions
class HasSetTitle s where
setTitle :: s -> String -> IO ()
-- | Controls with `ui...Title` functions
class HasGetTitle s where
getTitle :: s -> IO String
-- | Controls with `ui...SetPosition` functions
class HasSetPosition s where
setPosition :: s -> (Int, Int) -> IO ()
-- | Controls with `ui...Position` functions
class HasGetPosition s where
getPosition :: s -> IO (Int, Int)
-- | Controls with `ui...Text` functions
class HasGetText s where
getText :: s -> IO String
| Controls with ` ui ... SetText ` functions
class HasSetText s where
setText :: s -> String -> IO ()
-- | Controls with `ui...SetReadOnly` functions
class HasSetReadOnly s where
setReadOnly :: s -> Bool -> IO ()
-- | Controls with `ui...ReadOnly` functions
class HasGetReadOnly s where
getReadOnly :: s -> IO Bool
| Controls with ` ui ... SetValue ` functions
class HasSetValue s where
setValue :: s -> Int -> IO ()
| Controls with ` ui ... ` functions
class HasGetValue s where
getValue :: s -> IO Int
| Controls with ` ui ... ` functions
class HasOnClicked s where
onClick :: s -> IO () -> IO ()
class HasOnPositionChanged s where
onPositionChanged :: s -> IO () -> IO ()
| Controls with ` ui ... ` functions
class HasOnChanged s where
onChange :: s -> IO () -> IO ()
-- | Controls with `ui...SetChecked` functions
class HasSetChecked s where
setChecked :: s -> Bool -> IO ()
-- | Controls with `ui...Checked` functions
class HasGetChecked s where
getChecked :: s -> IO Bool
| Controls with ` ui ... ` functions
class HasSetChild s where
setChild :: ToCUIControlIO a => s -> a -> IO ()
-- | Controls with `ui...Append` functions
class HasAppendChild s where
-- | Append a child to this control
appendChild :: ToCUIControlIO a => s -> a -> IO ()
appendChildStretchy :: ToCUIControlIO a => s -> a -> IO ()
appendChildStretchy = appendChild
-- | Controls with `ui...Delete` functions
class HasRemoveChild s where
-- | Remove the child at index from this control
removeChild :: s -> Int -> IO ()
-- | Append an action returning a child to this control
appendIOChild :: (HasAppendChild s, ToCUIControlIO c) => s -> IO c -> IO ()
appendIOChild container childAction = do
c <- childAction
container `appendChild` c
appendIOChildStretchy :: (HasAppendChild s, ToCUIControlIO c) => s -> IO c -> IO ()
appendIOChildStretchy container childAction = do
c <- childAction
container `appendChildStretchy` c
class HasOnClosing w where
onClosing :: w -> IO () -> IO ()
class HasOnShouldQuit w where
onShouldQuit :: w -> IO () -> IO ()
class HasSetPadded w where
setPadded :: w -> Bool -> IO ()
class HasGetPadded w where
getPadded :: w -> IO Bool
class HasSetMargined w where
setMargined :: w -> Bool -> IO ()
class HasGetMargined w where
getMargined :: w -> IO Bool
-- * CUIControl API
-- | Displays a control ('c_uiControlShow')
uiShow :: ToCUIControl a => a -> IO ()
uiShow c = c_uiControlShow (toCUIControl c)
-- | Hides a control ('c_uiControlHide')
uiHide :: ToCUIControl a => a -> IO ()
uiHide = c_uiControlHide . toCUIControl
-- | Destroys a control ('c_uiControlDestroy')
uiDestroy :: ToCUIControl a => a -> IO ()
uiDestroy = c_uiControlDestroy . toCUIControl
-- | Get a control's parent ('c_uiControlParent')
uiGetParent :: ToCUIControl a => a -> IO CUIControl
uiGetParent = c_uiControlParent . toCUIControl
-- | Set a control's parent ('c_uiControlSetParent')
uiSetParent :: (ToCUIControl a, ToCUIControl b) => a -> b -> IO ()
uiSetParent control parent =
c_uiControlSetParent (toCUIControl control) (toCUIControl parent)
-- | Get if a control is on the top level ('c_uiControlTopLevel')
uiGetTopLevel :: ToCUIControl a => a -> IO Bool
uiGetTopLevel c = numToBool <$> c_uiControlToplevel (toCUIControl c)
-- | Get if a control is visible ('c_uiControlVisible')
uiGetVisible :: ToCUIControl a => a -> IO Bool
uiGetVisible c = numToBool <$> c_uiControlVisible (toCUIControl c)
-- | Get if a control is enabled ('c_uiControlEnabled')
uiGetEnabled :: ToCUIControl a => a -> IO Bool
uiGetEnabled c = numToBool <$> c_uiControlEnabled (toCUIControl c)
-- | Set if a control is enabled ('c_uiControlEnable' & 'c_uiControlDisable')
uiSetEnabled :: ToCUIControl a => a -> Bool -> IO ()
uiSetEnabled c True = c_uiControlEnable (toCUIControl c)
uiSetEnabled c False = c_uiControlDisable (toCUIControl c)
-- * UI Controls
-- ** Windows
-- *** CUIWindow <- uiWindow
-- |
-- Wrapped version of `c_uiNewWindow`
uiNewWindow
:: String
-- ^ Title
-> Int
-- ^ Width
-> Int
-- ^ Height
-> Bool
-- ^ Has menubar
-> IO CUIWindow
uiNewWindow t w h hasMenubar =
withCString t $ \t' -> c_uiNewWindow t' (fromIntegral w) (fromIntegral h) (boolToNum hasMenubar)
setBorderless :: CUIWindow -> Bool -> IO ()
setBorderless w b = c_uiWindowSetBorderless w (boolToNum b)
getBorderless :: CUIWindow -> IO Bool
getBorderless w = numToBool <$> c_uiWindowBorderless w
getContentSize :: CUIWindow -> IO (Int, Int)
getContentSize w = alloca $ \x -> alloca $ \y -> do
c_uiWindowContentSize w x y
x' <- peek x
y' <- peek y
return (fromIntegral x', fromIntegral y')
setContentSize :: CUIWindow -> (Int, Int) -> IO ()
setContentSize w (x, y) =
c_uiWindowSetContentSize w (fromIntegral x) (fromIntegral y)
onContentSizeChange w action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiWindowOnContentSizeChanged w f nullPtr
getFullscreen w = numToBool <$> c_uiWindowFullscreen w
setFullscreen w b = c_uiWindowSetFullscreen w (boolToNum b)
uiWindowGetTitle :: CUIWindow -> IO String
uiWindowGetTitle = c_uiWindowTitle >=> peekCString
instance HasSetTitle CUIWindow where
setTitle w t = withCString t (c_uiWindowSetTitle w)
instance HasGetTitle CUIWindow where
getTitle w = c_uiWindowTitle w >>= peekCString
instance HasOnClosing CUIWindow where
onClosing w a = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> a)
c_uiWindowOnClosing w f nullPtr
instance HasSetChild CUIWindow where
setChild w c = do
c' <- toCUIControlIO c
c_uiWindowSetChild w c'
instance HasGetMargined CUIWindow where
getMargined w = do
m <- c_uiWindowMargined w
return $ numToBool m
instance HasSetMargined CUIWindow where
setMargined w m = c_uiWindowSetMargined w (boolToNum m)
-- ** Labels
-- *** CUILabel <- uiLabel
instance HasGetText CUILabel where
getText c = c_uiLabelText c >>= peekCString
instance HasSetText CUILabel where
setText c s = withCString s (c_uiLabelSetText c)
uiNewLabel s = withCString s c_uiNewLabel
-- ** Layout
-- *** CUIBox <- uiBox
instance HasAppendChild CUIBox where
appendChild b c = do
c' <- toCUIControlIO c
c_uiBoxAppend b c' 0
appendChildStretchy b c = do
c' <- toCUIControlIO c
c_uiBoxAppend b c' 1
instance HasRemoveChild CUIBox where
removeChild b i = c_uiBoxDelete b (fromIntegral i)
instance HasGetPadded CUIBox where
getPadded b = do
p <- c_uiBoxPadded b
return (numToBool p)
instance HasSetPadded CUIBox where
setPadded b p = c_uiBoxSetPadded b (boolToNum p)
uiNewHorizontalBox = c_uiNewHorizontalBox
uiNewVerticalBox = c_uiNewVerticalBox
-- *** CUITabs <- uiTab
appendTab :: ToCUIControlIO c => CUITabs -> (String, c) -> IO ()
appendTab tabs (name, child) = withCString name $ \cname -> do
c <- toCUIControlIO child
c_uiTabAppend tabs cname c
removeTab = c_uiTabDelete
appendTabMargined :: ToCUIControlIO c => CUITabs -> (String, c) -> IO ()
appendTabMargined tabs (name, child) = withCString name $ \cname -> do
c <- toCUIControlIO child
c_uiTabAppend tabs cname c
n <- c_uiTabNumPages tabs
c_uiTabSetMargined tabs (n - 1) 1
instance HasGetMargined (CUITabs, Int) where
getMargined (tabs, nt) = do
c <- c_uiTabMargined tabs (fromIntegral nt)
return $ numToBool c
instance HasSetMargined (CUITabs, Int) where
setMargined (tabs, nt) i =
c_uiTabSetMargined tabs (fromIntegral nt) (boolToNum i)
uiNewTabs :: IO CUITabs
uiNewTabs = c_uiNewTab
-- *** CUIGroup <- uiGroup
instance HasSetChild CUIGroup where
setChild g c = do
c' <- toCUIControlIO c
c_uiGroupSetChild g c'
instance HasSetTitle CUIGroup where
setTitle c t = withCString t (c_uiGroupSetTitle c)
instance HasGetTitle CUIGroup where
getTitle c = c_uiGroupTitle c >>= peekCString
instance HasGetMargined CUIGroup where
getMargined g = do
c <- c_uiGroupMargined g
return $ numToBool c
instance HasSetMargined CUIGroup where
setMargined w m = c_uiGroupSetMargined w (boolToNum m)
uiNewGroup s = withCString s c_uiNewGroup
* * * < - uiGrid
data UIAlign = UIAlignFill
| UIAlignStart
| UIAlignCenter
| UIAlignEnd
toCUIAlign UIAlignFill = CUIAlign 0
toCUIAlign UIAlignStart = CUIAlign 1
toCUIAlign UIAlignCenter = CUIAlign 2
toCUIAlign UIAlignEnd = CUIAlign 3
data UIAt = UIAtLeading
| UIAtTop
| UIAtTrailing
| UIAtBottom
toCUIAt UIAtLeading = CUIAt 0
toCUIAt UIAtTop = CUIAt 1
toCUIAt UIAtTrailing = CUIAt 2
toCUIAt UIAtBottom = CUIAt 3
uiGridAppend
:: ToCUIControlIO c
=> CUIGrid
-> c
-> Int -> Int
-> Int -> Int
-> Int -> UIAlign
-> Int -> UIAlign
-> IO ()
uiGridAppend grid control left top xspan yspan hexpand halign vexpand valign = do
control' <- toCUIControlIO control
c_uiGridAppend
grid
control'
(fromIntegral left)
(fromIntegral top)
(fromIntegral xspan)
(fromIntegral yspan)
(fromIntegral hexpand)
(toCUIAlign halign)
(fromIntegral vexpand)
(toCUIAlign valign)
uiGridInsertAt
:: (ToCUIControlIO oldControl, ToCUIControlIO newControl)
=> CUIGrid
-> oldControl
-> newControl
-> UIAt
-> Int -> Int
-> Int -> UIAlign
-> Int -> UIAlign
-> IO ()
uiGridInsertAt grid ocontrol ncontrol at xspan yspan hexpand halign vexpand valign = do
ocontrol' <- toCUIControlIO ocontrol
ncontrol' <- toCUIControlIO ncontrol
c_uiGridInsertAt
grid
ocontrol'
ncontrol'
(toCUIAt at)
(fromIntegral xspan)
(fromIntegral yspan)
(fromIntegral hexpand)
(toCUIAlign halign)
(fromIntegral vexpand)
(toCUIAlign valign)
instance HasGetPadded CUIGrid where
getPadded g = do
p <- c_uiGridPadded g
return (numToBool p)
instance HasSetPadded CUIGrid where
setPadded g p = c_uiGridSetPadded g (boolToNum p)
uiNewGrid = c_uiNewGrid
* * *
uiNewHorizontalSeparator = c_uiNewHorizontalSeparator
uiNewVerticalSeparator = c_uiNewVerticalSeparator
-- ** Input Types
-- *** Buttons
* * * *
instance HasOnClicked CUIButton where
onClick btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiButtonOnClicked btn f nullPtr
instance HasGetText CUIButton where
getText btn = c_uiButtonText btn >>= peekCString
instance HasSetText CUIButton where
setText btn s = withCString s (c_uiButtonSetText btn)
uiNewButton str = withCString str c_uiNewButton
-- *** CUICheckbox <- uiCheckbox
instance HasSetText CUICheckbox where
setText btn s = withCString s (c_uiCheckboxSetText btn)
instance HasGetText CUICheckbox where
getText btn = c_uiCheckboxText btn >>= peekCString
instance HasSetChecked CUICheckbox where
setChecked c False = c_uiCheckboxSetChecked c 0
setChecked c True = c_uiCheckboxSetChecked c 1
instance HasGetChecked CUICheckbox where
getChecked c = numToBool <$> c_uiCheckboxChecked c
onToggled m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiCheckboxOnToggled m f nullPtr
instance HasOnChanged CUICheckbox where
onChange = onToggled
instance HasOnClicked CUICheckbox where
onClick = onToggled
uiNewCheckbox s = withCString s c_uiNewCheckbox
-- *** CUIEntry <- uiEntry
instance HasSetText CUIEntry where
setText c s = withCString s (c_uiEntrySetText c)
instance HasGetText CUIEntry where
getText c = c_uiEntryText c >>= peekCString
instance HasGetReadOnly CUIEntry where
getReadOnly c = numToBool <$> c_uiEntryReadOnly c
instance HasSetReadOnly CUIEntry where
setReadOnly c b = c_uiEntrySetReadOnly c (boolToNum b)
instance HasOnChanged CUIEntry where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiEntryOnChanged btn f nullPtr
uiNewEntry = c_uiNewEntry
uiNewPasswordEntry = c_uiNewPasswordEntry
uiNewSearchEntry = c_uiNewSearchEntry
-- *** CUISlider <- uiSlider
instance HasGetValue CUISlider where
getValue c = fromIntegral <$> c_uiSliderValue c
instance HasSetValue CUISlider where
setValue c i = c_uiSliderSetValue c (fromIntegral i)
instance HasOnChanged CUISlider where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiSliderOnChanged btn f nullPtr
uiNewSlider low high = c_uiNewSlider (fromIntegral low) (fromIntegral high)
-- *** CUICombobox <- uiCombobox
class HasAppendOption a where
appendOption :: a -> String -> IO ()
appendOptions :: a -> [String] -> IO ()
appendOptions x = mapM_ (appendOption x)
instance HasGetValue CUICombobox where
getValue c = fromIntegral <$> c_uiComboboxSelected c
instance HasSetValue CUICombobox where
setValue c s = c_uiComboboxSetSelected c (fromIntegral s)
instance HasOnChanged CUICombobox where
onChange c action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiComboboxOnSelected c f nullPtr
instance HasAppendOption CUICombobox where
appendOption c s = withCString s (c_uiComboboxAppend c)
uiNewCombobox = c_uiNewCombobox
-- *** CUIEditableCombobox <- uiEditableCombobox
instance HasAppendOption CUIEditableCombobox where
appendOption c s = withCString s (c_uiEditableComboboxAppend c)
instance HasGetText CUIEditableCombobox where
getText c = c_uiEditableComboboxText c >>= peekCString
instance HasSetText CUIEditableCombobox where
setText c s = withCString s (c_uiEditableComboboxSetText c)
instance HasOnChanged CUIEditableCombobox where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiEditableComboboxOnChanged btn f nullPtr
uiNewEditableCombobox = c_uiNewEditableCombobox
-- *** CUIRadioButtons <- uiRadioButtons
instance HasAppendOption CUIRadioButtons where
appendOption c s = withCString s (c_uiRadioButtonsAppend c)
instance HasGetValue CUIRadioButtons where
getValue c = fromIntegral <$> c_uiRadioButtonsSelected c
instance HasSetValue CUIRadioButtons where
setValue c s = c_uiRadioButtonsSetSelected c (fromIntegral s)
instance HasOnChanged CUIRadioButtons where
onChange c action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiRadioButtonsOnSelected c f nullPtr
-- TODO setSelected type-class
uiNewRadioButtons = c_uiNewRadioButtons
-- *** CUIForm <- uiForm
uiFormAppend form name input stretchy = withCString name $ \cname ->
c_uiFormAppend form cname input (boolToNum stretchy)
class ToAppendInput e where
appendInput :: CUIForm -> e -> IO ()
instance ToCUIControlIO c => ToAppendInput (String, c, Bool) where
form `appendInput` (name, input, stretchy) = do
input' <- toCUIControlIO input
uiFormAppend form name input' stretchy
instance ToCUIControlIO c => ToAppendInput (String, c) where
form `appendInput` (name, input) = form `appendInput` (name, input, True)
instance HasRemoveChild CUIForm where
removeChild b i = c_uiFormDelete b (fromIntegral i)
instance HasGetPadded CUIForm where
getPadded b = do
p <- c_uiFormPadded b
return $ numToBool p
instance HasSetPadded CUIForm where
setPadded b p = c_uiFormSetPadded b (boolToNum p)
uiNewForm = c_uiNewForm
-- *** CUIDatePicker <- uiDatePicker
uiNewDatePicker = c_uiNewDatePicker
uiNewTimePicker = c_uiNewTimePicker
uiNewDateTimePicker = c_uiNewDateTimePicker
* * *
uiNewFontButton = c_uiNewFontButton
-- *** CUIColorButton <- uiColorButton
uiNewColorButton = c_uiNewColorButton
-- *** CUIMultilineEntry <- uiMultilineEntry
instance HasGetText CUIMultilineEntry where
getText c = c_uiMultilineEntryText c >>= peekCString
instance HasSetText CUIMultilineEntry where
setText c s = withCString s (c_uiMultilineEntrySetText c)
instance HasOnChanged CUIMultilineEntry where
onChange m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiMultilineEntryOnChanged m f nullPtr
instance HasGetReadOnly CUIMultilineEntry where
getReadOnly e = numToBool <$> c_uiMultilineEntryReadOnly e
instance HasSetReadOnly CUIMultilineEntry where
setReadOnly e b = c_uiMultilineEntrySetReadOnly e (boolToNum b)
appendText :: CUIMultilineEntry -> String -> IO ()
appendText m s = withCString s (c_uiMultilineEntryAppend m)
uiNewMultilineEntry = c_uiNewMultilineEntry
uiNewNonWrappingMultilineEntry = c_uiNewNonWrappingMultilineEntry
-- ** Progress Indicators
* * *
instance HasGetValue CUIProgressBar where
getValue c = fromIntegral <$> c_uiProgressBarValue c
instance HasSetValue CUIProgressBar where
setValue c i = c_uiProgressBarSetValue c (fromIntegral i)
uiNewProgressBar = c_uiNewProgressBar
-- *** CUISpinbox <- uiSpinbox
instance HasGetValue CUISpinbox where
getValue c = fromIntegral <$> c_uiSpinboxValue c
instance HasSetValue CUISpinbox where
setValue c i = c_uiSpinboxSetValue c (fromIntegral i)
instance HasOnChanged CUISpinbox where
onChange m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiSpinboxOnChanged m f nullPtr
uiNewSpinbox low high = c_uiNewSpinbox (fromIntegral low) (fromIntegral high)
* The Menubar
-- ** CUIMenu <- uiMenu
uiNewMenu s = newCString s >>= c_uiNewMenu
uiMenuAppendItem m s = withCString s (c_uiMenuAppendItem m)
uiMenuAppendCheckItem m s = withCString s (c_uiMenuAppendCheckItem m)
uiMenuAppendQuitItem = c_uiMenuAppendQuitItem
uiMenuAppendAboutItem = c_uiMenuAppendAboutItem
uiMenuAppendPreferencesItem = c_uiMenuAppendPreferencesItem
uiMenuAppendSeparator = c_uiMenuAppendSeparator
* *
uiMenuItemEnable = c_uiMenuItemEnable
uiMenuItemDisable = c_uiMenuItemDisable
instance HasOnClicked CUIMenuItem where
onClick itm action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiMenuItemOnClicked itm f nullPtr
instance HasGetChecked CUIMenuItem where
getChecked c = numToBool <$> c_uiMenuItemChecked c
instance HasSetChecked CUIMenuItem where
setChecked c False = c_uiMenuItemSetChecked c 0
setChecked c True = c_uiMenuItemSetChecked c 1
-- * UI Alerts and Dialogs
uiOpenFile :: CUIWindow -> IO (Maybe FilePath)
uiOpenFile wn = do
cstr <- c_uiOpenFile wn
peekCStringSafe cstr
uiSaveFile :: CUIWindow -> IO (Maybe FilePath)
uiSaveFile wn = do
cstr <- c_uiSaveFile wn
peekCStringSafe cstr
uiMsgBox
:: CUIWindow
-> String
-> String
-> IO ()
uiMsgBox w t d = withCString t $ \t' -> withCString d $ \d' ->
c_uiMsgBox w t' d'
uiMsgBoxError
:: CUIWindow
-> String
-> String
-> IO ()
uiMsgBoxError w t d = withCString t $ \t' -> withCString d $ \d' ->
c_uiMsgBoxError w t' d'
-- * Internal functions
-- ** Ticking the loop
-- | Setup the main loop to be ticked manually
uiMainSteps :: IO ()
uiMainSteps = setHasMain True >> c_uiMainSteps
-- | Tick the main loop
uiMainStep :: Int -> IO Int
uiMainStep i = do
ne <- c_uiMainStep (fromIntegral i)
return (fromIntegral ne)
-- | Is the main loop running?
hasMainM :: MVar Bool
hasMainM = unsafePerformIO (newMVar False)
{-# NOINLINE hasMainM #-}
getHasMain :: IO Bool
getHasMain = readMVar hasMainM
setHasMain :: Bool -> IO ()
setHasMain m = modifyMVar_ hasMainM (const (return m))
boolToNum :: Num a => Bool -> a
boolToNum False = 0
boolToNum True = 1
numToBool :: (Num a, Eq a) => a -> Bool
numToBool 0 = False
numToBool _ = True
peekCStringSafe :: CString -> IO (Maybe String)
peekCStringSafe cstr | cstr == nullPtr = return Nothing
peekCStringSafe cstr = do
str <- peekCString cstr
return $ case str of
"" -> Nothing
_ -> Just str
| null | https://raw.githubusercontent.com/beijaflor-io/haskell-libui/4d1fad25e220071c4c977f79f05b482c2c36af84/src/Graphics/LibUI/FFI/Wrapped.hs | haskell | # LANGUAGE CApiFFI #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
|
This module should be enough to match how most imperative languages will
work with the foreign library, if you're ok with building your GUI
* Basic API
* UI Controls
** Windows
** Labels
** Layout Controls
*** Boxes
*** Tabs
*** Named Groups
*** Grids
*** Separators
** Input Types
*** Buttons
*** Text Inputs
*** Sliders
*** Selects
*** Radio Buttons
*** Labeled Forms
*** Date & Time Pickers
*** Color Picker
** Progress Indicators
** UI Alerts and Dialogs
* Type-Classes
* Internal functions
** Ticking the loop manually
** Other
* Raw FFI
* Basic API
| Initialize the UI options. Needs to be called before any UI building
@
main = do
uiInit
-- ...
uiMain
@
| Start the main loop
TODO Replace with uiMainStepExpire or something
| Quit the main loop
|
Actions not run on the main thread (that aren't just callbacks), need to be
It calls 'c_uiQueueMain' under the hood
@
main = do
-- .. 'uiInit' & create a window
^ Create a progressbar
'forkIO' $ do
^ Fork a thread
.. ' ' & ' uiMain '
@
| Add a hook to before quit
* Shared API
| Controls with `ui...Title` functions
| Controls with `ui...SetPosition` functions
| Controls with `ui...Position` functions
| Controls with `ui...Text` functions
| Controls with `ui...SetReadOnly` functions
| Controls with `ui...ReadOnly` functions
| Controls with `ui...SetChecked` functions
| Controls with `ui...Checked` functions
| Controls with `ui...Append` functions
| Append a child to this control
| Controls with `ui...Delete` functions
| Remove the child at index from this control
| Append an action returning a child to this control
* CUIControl API
| Displays a control ('c_uiControlShow')
| Hides a control ('c_uiControlHide')
| Destroys a control ('c_uiControlDestroy')
| Get a control's parent ('c_uiControlParent')
| Set a control's parent ('c_uiControlSetParent')
| Get if a control is on the top level ('c_uiControlTopLevel')
| Get if a control is visible ('c_uiControlVisible')
| Get if a control is enabled ('c_uiControlEnabled')
| Set if a control is enabled ('c_uiControlEnable' & 'c_uiControlDisable')
* UI Controls
** Windows
*** CUIWindow <- uiWindow
|
Wrapped version of `c_uiNewWindow`
^ Title
^ Width
^ Height
^ Has menubar
** Labels
*** CUILabel <- uiLabel
** Layout
*** CUIBox <- uiBox
*** CUITabs <- uiTab
*** CUIGroup <- uiGroup
** Input Types
*** Buttons
*** CUICheckbox <- uiCheckbox
*** CUIEntry <- uiEntry
*** CUISlider <- uiSlider
*** CUICombobox <- uiCombobox
*** CUIEditableCombobox <- uiEditableCombobox
*** CUIRadioButtons <- uiRadioButtons
TODO setSelected type-class
*** CUIForm <- uiForm
*** CUIDatePicker <- uiDatePicker
*** CUIColorButton <- uiColorButton
*** CUIMultilineEntry <- uiMultilineEntry
** Progress Indicators
*** CUISpinbox <- uiSpinbox
** CUIMenu <- uiMenu
* UI Alerts and Dialogs
* Internal functions
** Ticking the loop
| Setup the main loop to be ticked manually
| Tick the main loop
| Is the main loop running?
# NOINLINE hasMainM # | # LANGUAGE FlexibleInstances #
# LANGUAGE InterruptibleFFI #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
Provides wrappers to make the imperative C API nicer to use in Haskell
imperatively on the IO Monad , this should be fine
module Graphics.LibUI.FFI.Wrapped
(
uiInit
, uiMain
, uiQuit
, uiQueueMain
, uiOnShouldQuit
, CUIControl (..)
, ToCUIControl (..)
, ToCUIControlIO (..)
, uiShow
, uiHide
, uiDestroy
, uiGetParent
, uiSetParent
, uiGetTopLevel
, uiGetVisible
, uiGetEnabled
, uiSetEnabled
, CUIWindow (..)
, uiNewWindow
, getBorderless
, setBorderless
, getContentSize
, setContentSize
, onContentSizeChange
, getFullscreen
, setFullscreen
, CUILabel (..)
, uiNewLabel
, CUIBox (..)
, uiNewHorizontalBox
, uiNewVerticalBox
, CUITabs (..)
, uiNewTabs
, appendTab
, appendTabMargined
, removeTab
, CUIGroup (..)
, uiNewGroup
, CUIGrid (..)
, uiNewGrid
, uiGridAppend
, uiGridInsertAt
, UIAlign (..)
, UIAt (..)
, CUISeparator (..)
, uiNewHorizontalSeparator
, uiNewVerticalSeparator
, CUIButton (..)
, uiNewButton
* * *
, CUICheckbox (..)
, uiNewCheckbox
, CUIEntry (..)
, uiNewEntry
, uiNewPasswordEntry
, uiNewSearchEntry
, CUISpinbox (..)
, uiNewSpinbox
, CUISlider (..)
, uiNewSlider
, CUICombobox (..)
, uiNewCombobox
, CUIEditableCombobox (..)
, uiNewEditableCombobox
, CUIRadioButtons (..)
, uiNewRadioButtons
, CUIForm (..)
, uiNewForm
, uiFormAppend
, CUIDateTimePicker (..)
, uiNewDatePicker
, uiNewTimePicker
, uiNewDateTimePicker
* * *
, CUIFontButton (..)
, uiNewFontButton
, CUIColorButton (..)
, uiNewColorButton
* * * Inputs
, CUIMultilineEntry (..)
, appendText
, uiNewMultilineEntry
, uiNewNonWrappingMultilineEntry
, CUIProgressBar (..)
, uiNewProgressBar
* * The Menubar
, CUIMenu (..)
, uiNewMenu
, uiMenuAppendItem
, uiMenuAppendCheckItem
, uiMenuAppendQuitItem
, uiMenuAppendPreferencesItem
, uiMenuAppendAboutItem
, uiMenuAppendSeparator
, CUIMenuItem (..)
, uiMenuItemEnable
, uiMenuItemDisable
, uiOpenFile
, uiSaveFile
, uiMsgBox
, uiMsgBoxError
, HasSetTitle (..)
, HasGetTitle (..)
, HasSetPosition (..)
, HasGetPosition (..)
, HasGetText (..)
, HasSetText (..)
, HasSetValue (..)
, HasGetValue (..)
, HasGetChecked (..)
, HasSetChecked (..)
, HasSetChild (..)
, HasAppendChild (..)
, HasRemoveChild (..)
, HasOnPositionChanged (..)
, HasOnClicked (..)
, HasOnChanged (..)
, HasOnClosing (..)
, HasOnShouldQuit (..)
, HasSetPadded (..)
, HasGetPadded (..)
, HasSetMargined (..)
, HasGetMargined (..)
, HasSetReadOnly (..)
, HasGetReadOnly (..)
, HasAppendOption (..)
, ToAppendInput (..)
, appendIOChild
, appendIOChildStretchy
, uiMainSteps, uiMainStep, hasMainM, getHasMain, setHasMain
, boolToNum, numToBool, toCUIAlign, toCUIAt, peekCStringSafe
, module Graphics.LibUI.FFI.Raw
)
where
import Control.Concurrent
import Control.Monad (when, (>=>))
import Control.Monad.Loops
import Foreign hiding (void)
import Foreign.C
import System.IO.Unsafe
import Graphics.LibUI.FFI.Raw
uiInit :: IO ()
uiInit =
alloca $ \ptr -> do
poke ptr (CSize (fromIntegral (sizeOf (CSize 0))))
c_uiInit ptr
uiMain :: IO ()
uiMain = do
uiMainSteps
whileM_ getHasMain (uiMainStep 1)
uiQuit :: IO ()
uiQuit = do
setHasMain False
c_uiQuit
queued with @uiQueueMain@
pg < - ' uiNewProgressBar '
' forM _ ' [ 0 .. 100 ] $ \i - > do
' threadDelay ' ( 1000 * 100 )
' uiQueueMain ' ( ' setValue ' pg i )
uiQueueMain :: IO () -> IO ()
uiQueueMain a = do
m <- getHasMain
when m $ do
a' <- c_wrap1 $ \_ -> do
r <- a
return ()
c_uiQueueMain a' nullPtr
uiOnShouldQuit :: IO Int -> IO ()
uiOnShouldQuit a = do
f <- castFunPtr <$> c_wrap1I (\_ -> fromIntegral <$> a)
c_uiOnShouldQuit f nullPtr
| Controls with ` ui ... SetTitle ` functions
class HasSetTitle s where
setTitle :: s -> String -> IO ()
class HasGetTitle s where
getTitle :: s -> IO String
class HasSetPosition s where
setPosition :: s -> (Int, Int) -> IO ()
class HasGetPosition s where
getPosition :: s -> IO (Int, Int)
class HasGetText s where
getText :: s -> IO String
| Controls with ` ui ... SetText ` functions
class HasSetText s where
setText :: s -> String -> IO ()
class HasSetReadOnly s where
setReadOnly :: s -> Bool -> IO ()
class HasGetReadOnly s where
getReadOnly :: s -> IO Bool
| Controls with ` ui ... SetValue ` functions
class HasSetValue s where
setValue :: s -> Int -> IO ()
| Controls with ` ui ... ` functions
class HasGetValue s where
getValue :: s -> IO Int
| Controls with ` ui ... ` functions
class HasOnClicked s where
onClick :: s -> IO () -> IO ()
class HasOnPositionChanged s where
onPositionChanged :: s -> IO () -> IO ()
| Controls with ` ui ... ` functions
class HasOnChanged s where
onChange :: s -> IO () -> IO ()
class HasSetChecked s where
setChecked :: s -> Bool -> IO ()
class HasGetChecked s where
getChecked :: s -> IO Bool
| Controls with ` ui ... ` functions
class HasSetChild s where
setChild :: ToCUIControlIO a => s -> a -> IO ()
class HasAppendChild s where
appendChild :: ToCUIControlIO a => s -> a -> IO ()
appendChildStretchy :: ToCUIControlIO a => s -> a -> IO ()
appendChildStretchy = appendChild
class HasRemoveChild s where
removeChild :: s -> Int -> IO ()
appendIOChild :: (HasAppendChild s, ToCUIControlIO c) => s -> IO c -> IO ()
appendIOChild container childAction = do
c <- childAction
container `appendChild` c
appendIOChildStretchy :: (HasAppendChild s, ToCUIControlIO c) => s -> IO c -> IO ()
appendIOChildStretchy container childAction = do
c <- childAction
container `appendChildStretchy` c
class HasOnClosing w where
onClosing :: w -> IO () -> IO ()
class HasOnShouldQuit w where
onShouldQuit :: w -> IO () -> IO ()
class HasSetPadded w where
setPadded :: w -> Bool -> IO ()
class HasGetPadded w where
getPadded :: w -> IO Bool
class HasSetMargined w where
setMargined :: w -> Bool -> IO ()
class HasGetMargined w where
getMargined :: w -> IO Bool
uiShow :: ToCUIControl a => a -> IO ()
uiShow c = c_uiControlShow (toCUIControl c)
uiHide :: ToCUIControl a => a -> IO ()
uiHide = c_uiControlHide . toCUIControl
uiDestroy :: ToCUIControl a => a -> IO ()
uiDestroy = c_uiControlDestroy . toCUIControl
uiGetParent :: ToCUIControl a => a -> IO CUIControl
uiGetParent = c_uiControlParent . toCUIControl
uiSetParent :: (ToCUIControl a, ToCUIControl b) => a -> b -> IO ()
uiSetParent control parent =
c_uiControlSetParent (toCUIControl control) (toCUIControl parent)
uiGetTopLevel :: ToCUIControl a => a -> IO Bool
uiGetTopLevel c = numToBool <$> c_uiControlToplevel (toCUIControl c)
uiGetVisible :: ToCUIControl a => a -> IO Bool
uiGetVisible c = numToBool <$> c_uiControlVisible (toCUIControl c)
uiGetEnabled :: ToCUIControl a => a -> IO Bool
uiGetEnabled c = numToBool <$> c_uiControlEnabled (toCUIControl c)
uiSetEnabled :: ToCUIControl a => a -> Bool -> IO ()
uiSetEnabled c True = c_uiControlEnable (toCUIControl c)
uiSetEnabled c False = c_uiControlDisable (toCUIControl c)
uiNewWindow
:: String
-> Int
-> Int
-> Bool
-> IO CUIWindow
uiNewWindow t w h hasMenubar =
withCString t $ \t' -> c_uiNewWindow t' (fromIntegral w) (fromIntegral h) (boolToNum hasMenubar)
setBorderless :: CUIWindow -> Bool -> IO ()
setBorderless w b = c_uiWindowSetBorderless w (boolToNum b)
getBorderless :: CUIWindow -> IO Bool
getBorderless w = numToBool <$> c_uiWindowBorderless w
getContentSize :: CUIWindow -> IO (Int, Int)
getContentSize w = alloca $ \x -> alloca $ \y -> do
c_uiWindowContentSize w x y
x' <- peek x
y' <- peek y
return (fromIntegral x', fromIntegral y')
setContentSize :: CUIWindow -> (Int, Int) -> IO ()
setContentSize w (x, y) =
c_uiWindowSetContentSize w (fromIntegral x) (fromIntegral y)
onContentSizeChange w action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiWindowOnContentSizeChanged w f nullPtr
getFullscreen w = numToBool <$> c_uiWindowFullscreen w
setFullscreen w b = c_uiWindowSetFullscreen w (boolToNum b)
uiWindowGetTitle :: CUIWindow -> IO String
uiWindowGetTitle = c_uiWindowTitle >=> peekCString
instance HasSetTitle CUIWindow where
setTitle w t = withCString t (c_uiWindowSetTitle w)
instance HasGetTitle CUIWindow where
getTitle w = c_uiWindowTitle w >>= peekCString
instance HasOnClosing CUIWindow where
onClosing w a = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> a)
c_uiWindowOnClosing w f nullPtr
instance HasSetChild CUIWindow where
setChild w c = do
c' <- toCUIControlIO c
c_uiWindowSetChild w c'
instance HasGetMargined CUIWindow where
getMargined w = do
m <- c_uiWindowMargined w
return $ numToBool m
instance HasSetMargined CUIWindow where
setMargined w m = c_uiWindowSetMargined w (boolToNum m)
instance HasGetText CUILabel where
getText c = c_uiLabelText c >>= peekCString
instance HasSetText CUILabel where
setText c s = withCString s (c_uiLabelSetText c)
uiNewLabel s = withCString s c_uiNewLabel
instance HasAppendChild CUIBox where
appendChild b c = do
c' <- toCUIControlIO c
c_uiBoxAppend b c' 0
appendChildStretchy b c = do
c' <- toCUIControlIO c
c_uiBoxAppend b c' 1
instance HasRemoveChild CUIBox where
removeChild b i = c_uiBoxDelete b (fromIntegral i)
instance HasGetPadded CUIBox where
getPadded b = do
p <- c_uiBoxPadded b
return (numToBool p)
instance HasSetPadded CUIBox where
setPadded b p = c_uiBoxSetPadded b (boolToNum p)
uiNewHorizontalBox = c_uiNewHorizontalBox
uiNewVerticalBox = c_uiNewVerticalBox
appendTab :: ToCUIControlIO c => CUITabs -> (String, c) -> IO ()
appendTab tabs (name, child) = withCString name $ \cname -> do
c <- toCUIControlIO child
c_uiTabAppend tabs cname c
removeTab = c_uiTabDelete
appendTabMargined :: ToCUIControlIO c => CUITabs -> (String, c) -> IO ()
appendTabMargined tabs (name, child) = withCString name $ \cname -> do
c <- toCUIControlIO child
c_uiTabAppend tabs cname c
n <- c_uiTabNumPages tabs
c_uiTabSetMargined tabs (n - 1) 1
instance HasGetMargined (CUITabs, Int) where
getMargined (tabs, nt) = do
c <- c_uiTabMargined tabs (fromIntegral nt)
return $ numToBool c
instance HasSetMargined (CUITabs, Int) where
setMargined (tabs, nt) i =
c_uiTabSetMargined tabs (fromIntegral nt) (boolToNum i)
uiNewTabs :: IO CUITabs
uiNewTabs = c_uiNewTab
instance HasSetChild CUIGroup where
setChild g c = do
c' <- toCUIControlIO c
c_uiGroupSetChild g c'
instance HasSetTitle CUIGroup where
setTitle c t = withCString t (c_uiGroupSetTitle c)
instance HasGetTitle CUIGroup where
getTitle c = c_uiGroupTitle c >>= peekCString
instance HasGetMargined CUIGroup where
getMargined g = do
c <- c_uiGroupMargined g
return $ numToBool c
instance HasSetMargined CUIGroup where
setMargined w m = c_uiGroupSetMargined w (boolToNum m)
uiNewGroup s = withCString s c_uiNewGroup
* * * < - uiGrid
data UIAlign = UIAlignFill
| UIAlignStart
| UIAlignCenter
| UIAlignEnd
toCUIAlign UIAlignFill = CUIAlign 0
toCUIAlign UIAlignStart = CUIAlign 1
toCUIAlign UIAlignCenter = CUIAlign 2
toCUIAlign UIAlignEnd = CUIAlign 3
data UIAt = UIAtLeading
| UIAtTop
| UIAtTrailing
| UIAtBottom
toCUIAt UIAtLeading = CUIAt 0
toCUIAt UIAtTop = CUIAt 1
toCUIAt UIAtTrailing = CUIAt 2
toCUIAt UIAtBottom = CUIAt 3
uiGridAppend
:: ToCUIControlIO c
=> CUIGrid
-> c
-> Int -> Int
-> Int -> Int
-> Int -> UIAlign
-> Int -> UIAlign
-> IO ()
uiGridAppend grid control left top xspan yspan hexpand halign vexpand valign = do
control' <- toCUIControlIO control
c_uiGridAppend
grid
control'
(fromIntegral left)
(fromIntegral top)
(fromIntegral xspan)
(fromIntegral yspan)
(fromIntegral hexpand)
(toCUIAlign halign)
(fromIntegral vexpand)
(toCUIAlign valign)
uiGridInsertAt
:: (ToCUIControlIO oldControl, ToCUIControlIO newControl)
=> CUIGrid
-> oldControl
-> newControl
-> UIAt
-> Int -> Int
-> Int -> UIAlign
-> Int -> UIAlign
-> IO ()
uiGridInsertAt grid ocontrol ncontrol at xspan yspan hexpand halign vexpand valign = do
ocontrol' <- toCUIControlIO ocontrol
ncontrol' <- toCUIControlIO ncontrol
c_uiGridInsertAt
grid
ocontrol'
ncontrol'
(toCUIAt at)
(fromIntegral xspan)
(fromIntegral yspan)
(fromIntegral hexpand)
(toCUIAlign halign)
(fromIntegral vexpand)
(toCUIAlign valign)
instance HasGetPadded CUIGrid where
getPadded g = do
p <- c_uiGridPadded g
return (numToBool p)
instance HasSetPadded CUIGrid where
setPadded g p = c_uiGridSetPadded g (boolToNum p)
uiNewGrid = c_uiNewGrid
* * *
uiNewHorizontalSeparator = c_uiNewHorizontalSeparator
uiNewVerticalSeparator = c_uiNewVerticalSeparator
* * * *
instance HasOnClicked CUIButton where
onClick btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiButtonOnClicked btn f nullPtr
instance HasGetText CUIButton where
getText btn = c_uiButtonText btn >>= peekCString
instance HasSetText CUIButton where
setText btn s = withCString s (c_uiButtonSetText btn)
uiNewButton str = withCString str c_uiNewButton
instance HasSetText CUICheckbox where
setText btn s = withCString s (c_uiCheckboxSetText btn)
instance HasGetText CUICheckbox where
getText btn = c_uiCheckboxText btn >>= peekCString
instance HasSetChecked CUICheckbox where
setChecked c False = c_uiCheckboxSetChecked c 0
setChecked c True = c_uiCheckboxSetChecked c 1
instance HasGetChecked CUICheckbox where
getChecked c = numToBool <$> c_uiCheckboxChecked c
onToggled m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiCheckboxOnToggled m f nullPtr
instance HasOnChanged CUICheckbox where
onChange = onToggled
instance HasOnClicked CUICheckbox where
onClick = onToggled
uiNewCheckbox s = withCString s c_uiNewCheckbox
instance HasSetText CUIEntry where
setText c s = withCString s (c_uiEntrySetText c)
instance HasGetText CUIEntry where
getText c = c_uiEntryText c >>= peekCString
instance HasGetReadOnly CUIEntry where
getReadOnly c = numToBool <$> c_uiEntryReadOnly c
instance HasSetReadOnly CUIEntry where
setReadOnly c b = c_uiEntrySetReadOnly c (boolToNum b)
instance HasOnChanged CUIEntry where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiEntryOnChanged btn f nullPtr
uiNewEntry = c_uiNewEntry
uiNewPasswordEntry = c_uiNewPasswordEntry
uiNewSearchEntry = c_uiNewSearchEntry
instance HasGetValue CUISlider where
getValue c = fromIntegral <$> c_uiSliderValue c
instance HasSetValue CUISlider where
setValue c i = c_uiSliderSetValue c (fromIntegral i)
instance HasOnChanged CUISlider where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiSliderOnChanged btn f nullPtr
uiNewSlider low high = c_uiNewSlider (fromIntegral low) (fromIntegral high)
class HasAppendOption a where
appendOption :: a -> String -> IO ()
appendOptions :: a -> [String] -> IO ()
appendOptions x = mapM_ (appendOption x)
instance HasGetValue CUICombobox where
getValue c = fromIntegral <$> c_uiComboboxSelected c
instance HasSetValue CUICombobox where
setValue c s = c_uiComboboxSetSelected c (fromIntegral s)
instance HasOnChanged CUICombobox where
onChange c action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiComboboxOnSelected c f nullPtr
instance HasAppendOption CUICombobox where
appendOption c s = withCString s (c_uiComboboxAppend c)
uiNewCombobox = c_uiNewCombobox
instance HasAppendOption CUIEditableCombobox where
appendOption c s = withCString s (c_uiEditableComboboxAppend c)
instance HasGetText CUIEditableCombobox where
getText c = c_uiEditableComboboxText c >>= peekCString
instance HasSetText CUIEditableCombobox where
setText c s = withCString s (c_uiEditableComboboxSetText c)
instance HasOnChanged CUIEditableCombobox where
onChange btn action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiEditableComboboxOnChanged btn f nullPtr
uiNewEditableCombobox = c_uiNewEditableCombobox
instance HasAppendOption CUIRadioButtons where
appendOption c s = withCString s (c_uiRadioButtonsAppend c)
instance HasGetValue CUIRadioButtons where
getValue c = fromIntegral <$> c_uiRadioButtonsSelected c
instance HasSetValue CUIRadioButtons where
setValue c s = c_uiRadioButtonsSetSelected c (fromIntegral s)
instance HasOnChanged CUIRadioButtons where
onChange c action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiRadioButtonsOnSelected c f nullPtr
uiNewRadioButtons = c_uiNewRadioButtons
uiFormAppend form name input stretchy = withCString name $ \cname ->
c_uiFormAppend form cname input (boolToNum stretchy)
class ToAppendInput e where
appendInput :: CUIForm -> e -> IO ()
instance ToCUIControlIO c => ToAppendInput (String, c, Bool) where
form `appendInput` (name, input, stretchy) = do
input' <- toCUIControlIO input
uiFormAppend form name input' stretchy
instance ToCUIControlIO c => ToAppendInput (String, c) where
form `appendInput` (name, input) = form `appendInput` (name, input, True)
instance HasRemoveChild CUIForm where
removeChild b i = c_uiFormDelete b (fromIntegral i)
instance HasGetPadded CUIForm where
getPadded b = do
p <- c_uiFormPadded b
return $ numToBool p
instance HasSetPadded CUIForm where
setPadded b p = c_uiFormSetPadded b (boolToNum p)
uiNewForm = c_uiNewForm
uiNewDatePicker = c_uiNewDatePicker
uiNewTimePicker = c_uiNewTimePicker
uiNewDateTimePicker = c_uiNewDateTimePicker
* * *
uiNewFontButton = c_uiNewFontButton
uiNewColorButton = c_uiNewColorButton
instance HasGetText CUIMultilineEntry where
getText c = c_uiMultilineEntryText c >>= peekCString
instance HasSetText CUIMultilineEntry where
setText c s = withCString s (c_uiMultilineEntrySetText c)
instance HasOnChanged CUIMultilineEntry where
onChange m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiMultilineEntryOnChanged m f nullPtr
instance HasGetReadOnly CUIMultilineEntry where
getReadOnly e = numToBool <$> c_uiMultilineEntryReadOnly e
instance HasSetReadOnly CUIMultilineEntry where
setReadOnly e b = c_uiMultilineEntrySetReadOnly e (boolToNum b)
appendText :: CUIMultilineEntry -> String -> IO ()
appendText m s = withCString s (c_uiMultilineEntryAppend m)
uiNewMultilineEntry = c_uiNewMultilineEntry
uiNewNonWrappingMultilineEntry = c_uiNewNonWrappingMultilineEntry
* * *
instance HasGetValue CUIProgressBar where
getValue c = fromIntegral <$> c_uiProgressBarValue c
instance HasSetValue CUIProgressBar where
setValue c i = c_uiProgressBarSetValue c (fromIntegral i)
uiNewProgressBar = c_uiNewProgressBar
instance HasGetValue CUISpinbox where
getValue c = fromIntegral <$> c_uiSpinboxValue c
instance HasSetValue CUISpinbox where
setValue c i = c_uiSpinboxSetValue c (fromIntegral i)
instance HasOnChanged CUISpinbox where
onChange m action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiSpinboxOnChanged m f nullPtr
uiNewSpinbox low high = c_uiNewSpinbox (fromIntegral low) (fromIntegral high)
* The Menubar
uiNewMenu s = newCString s >>= c_uiNewMenu
uiMenuAppendItem m s = withCString s (c_uiMenuAppendItem m)
uiMenuAppendCheckItem m s = withCString s (c_uiMenuAppendCheckItem m)
uiMenuAppendQuitItem = c_uiMenuAppendQuitItem
uiMenuAppendAboutItem = c_uiMenuAppendAboutItem
uiMenuAppendPreferencesItem = c_uiMenuAppendPreferencesItem
uiMenuAppendSeparator = c_uiMenuAppendSeparator
* *
uiMenuItemEnable = c_uiMenuItemEnable
uiMenuItemDisable = c_uiMenuItemDisable
instance HasOnClicked CUIMenuItem where
onClick itm action = do
f <- castFunPtr <$> c_wrap2 (\_ _ -> action)
c_uiMenuItemOnClicked itm f nullPtr
instance HasGetChecked CUIMenuItem where
getChecked c = numToBool <$> c_uiMenuItemChecked c
instance HasSetChecked CUIMenuItem where
setChecked c False = c_uiMenuItemSetChecked c 0
setChecked c True = c_uiMenuItemSetChecked c 1
uiOpenFile :: CUIWindow -> IO (Maybe FilePath)
uiOpenFile wn = do
cstr <- c_uiOpenFile wn
peekCStringSafe cstr
uiSaveFile :: CUIWindow -> IO (Maybe FilePath)
uiSaveFile wn = do
cstr <- c_uiSaveFile wn
peekCStringSafe cstr
uiMsgBox
:: CUIWindow
-> String
-> String
-> IO ()
uiMsgBox w t d = withCString t $ \t' -> withCString d $ \d' ->
c_uiMsgBox w t' d'
uiMsgBoxError
:: CUIWindow
-> String
-> String
-> IO ()
uiMsgBoxError w t d = withCString t $ \t' -> withCString d $ \d' ->
c_uiMsgBoxError w t' d'
uiMainSteps :: IO ()
uiMainSteps = setHasMain True >> c_uiMainSteps
uiMainStep :: Int -> IO Int
uiMainStep i = do
ne <- c_uiMainStep (fromIntegral i)
return (fromIntegral ne)
hasMainM :: MVar Bool
hasMainM = unsafePerformIO (newMVar False)
getHasMain :: IO Bool
getHasMain = readMVar hasMainM
setHasMain :: Bool -> IO ()
setHasMain m = modifyMVar_ hasMainM (const (return m))
boolToNum :: Num a => Bool -> a
boolToNum False = 0
boolToNum True = 1
numToBool :: (Num a, Eq a) => a -> Bool
numToBool 0 = False
numToBool _ = True
peekCStringSafe :: CString -> IO (Maybe String)
peekCStringSafe cstr | cstr == nullPtr = return Nothing
peekCStringSafe cstr = do
str <- peekCString cstr
return $ case str of
"" -> Nothing
_ -> Just str
|
efc65ed2502b9813df4e16b1d08418c55240107604d312b37dc73bc8fcd7d722 | pablomarx/Thomas | portable-rep.scm | * Copyright 1992 Digital Equipment Corporation
;* All Rights Reserved
;*
;* Permission to use, copy, and modify this software and its documentation is
;* hereby granted only under the following terms and conditions. Both the
;* above copyright notice and this permission notice must appear in all copies
;* of the software, derivative works or modified versions, and any portions
;* thereof, and both notices must appear in supporting documentation.
;*
;* Users of this software agree to the terms and conditions set forth herein,
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
;* right and license under any changes, enhancements or extensions made to the
;* core functions of the software, including but not limited to those affording
;* compatibility with other hardware or software environments, but excluding
;* applications which incorporate this software. Users further agree to use
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
;*
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
;* Cambridge MA 02139
;*
;* This software may be distributed (but not offered for sale or transferred
* for compensation ) to third parties , provided such third parties agree to
;* abide by the terms and conditions of this notice.
;*
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
;* SOFTWARE.
$ I d : portable - rep.scm , v 1.8 1992/09/21 21:30:56 birkholz Exp $
;;; Just use current (user?) environment and keep a list of known module
variables in thomas - rep - module - variables .
(define thomas-rep-module-variables '())
(define (empty-thomas-environment!)
Just dump thomas - rep - module - variables .
(set! thomas-rep-module-variables '()))
(define (thomas-rep)
(newline)
(display "Entering Thomas read-eval-print-loop.")
(newline)
(display "Exit by typing \"thomas:done\"")
(newline)
(dylan::catch-all-conditions
(lambda ()
(let loop ()
(newline)
(display "? ")
(let ((input (read)))
(newline)
(if (and (eq? input 'thomas:done))
'thomas:done
(compile-expression
input '!MULTIPLE-VALUES thomas-rep-module-variables
(lambda (new-vars preamble compiled-output)
(implementation-specific:eval
`(BEGIN
,@preamble
(LET* ((!MULTIPLE-VALUES (VECTOR '()))
(!RESULT ,compiled-output))
(IF (EQ? !RESULT !MULTIPLE-VALUES)
(LET RESULT-LOOP
((COUNT 1)
(RESULTS (VECTOR-REF !MULTIPLE-VALUES 0)))
(IF (PAIR? RESULTS)
(LET ((RESULT (CAR RESULTS)))
(NEWLINE)
(DISPLAY ";Value[")(DISPLAY COUNT)
(DISPLAY "]: ")(WRITE RESULT)
(RESULT-LOOP (+ 1 COUNT) (CDR RESULTS)))
(NEWLINE)))
(BEGIN
(NEWLINE)(DISPLAY ";Value: ")(WRITE !RESULT)
(NEWLINE))))))
(set! thomas-rep-module-variables
(append new-vars thomas-rep-module-variables))
(loop)))))))))
(display "
Apply thomas-rep to start a Thomas read-eval-print loop.
")
| null | https://raw.githubusercontent.com/pablomarx/Thomas/c8ab3f6fa92a9a39667fe37dfe060b651affb18e/kits/scc/src/portable-rep.scm | scheme | * All Rights Reserved
*
* Permission to use, copy, and modify this software and its documentation is
* hereby granted only under the following terms and conditions. Both the
* above copyright notice and this permission notice must appear in all copies
* of the software, derivative works or modified versions, and any portions
* thereof, and both notices must appear in supporting documentation.
*
* Users of this software agree to the terms and conditions set forth herein,
* right and license under any changes, enhancements or extensions made to the
* core functions of the software, including but not limited to those affording
* compatibility with other hardware or software environments, but excluding
* applications which incorporate this software. Users further agree to use
*
* Cambridge MA 02139
*
* This software may be distributed (but not offered for sale or transferred
* abide by the terms and conditions of this notice.
*
* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
Just use current (user?) environment and keep a list of known module | * Copyright 1992 Digital Equipment Corporation
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
* for compensation ) to third parties , provided such third parties agree to
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
$ I d : portable - rep.scm , v 1.8 1992/09/21 21:30:56 birkholz Exp $
variables in thomas - rep - module - variables .
(define thomas-rep-module-variables '())
(define (empty-thomas-environment!)
Just dump thomas - rep - module - variables .
(set! thomas-rep-module-variables '()))
(define (thomas-rep)
(newline)
(display "Entering Thomas read-eval-print-loop.")
(newline)
(display "Exit by typing \"thomas:done\"")
(newline)
(dylan::catch-all-conditions
(lambda ()
(let loop ()
(newline)
(display "? ")
(let ((input (read)))
(newline)
(if (and (eq? input 'thomas:done))
'thomas:done
(compile-expression
input '!MULTIPLE-VALUES thomas-rep-module-variables
(lambda (new-vars preamble compiled-output)
(implementation-specific:eval
`(BEGIN
,@preamble
(LET* ((!MULTIPLE-VALUES (VECTOR '()))
(!RESULT ,compiled-output))
(IF (EQ? !RESULT !MULTIPLE-VALUES)
(LET RESULT-LOOP
((COUNT 1)
(RESULTS (VECTOR-REF !MULTIPLE-VALUES 0)))
(IF (PAIR? RESULTS)
(LET ((RESULT (CAR RESULTS)))
(NEWLINE)
(DISPLAY ";Value[")(DISPLAY COUNT)
(DISPLAY "]: ")(WRITE RESULT)
(RESULT-LOOP (+ 1 COUNT) (CDR RESULTS)))
(NEWLINE)))
(BEGIN
(NEWLINE)(DISPLAY ";Value: ")(WRITE !RESULT)
(NEWLINE))))))
(set! thomas-rep-module-variables
(append new-vars thomas-rep-module-variables))
(loop)))))))))
(display "
Apply thomas-rep to start a Thomas read-eval-print loop.
")
|
6deb5bf0068aa38b9fc87448df88b0851cff24012d0f971cf59a919ac6b5d1d9 | acl2/acl2 | assert.cpp.ref.ast.lsp |
(funcdef foo (a) (block (assert a foo) (return 1)))
| null | https://raw.githubusercontent.com/acl2/acl2/c2d69bad0ed3132cc19a00cb632de8b73558b1f9/books/projects/rac/tests/yaml_test/control_flow/assert.cpp.ref.ast.lsp | lisp |
(funcdef foo (a) (block (assert a foo) (return 1)))
|
|
b144b8a3ea3584cc950f21ac0c6ebac7997a0ee3515558c0074d058e03600694 | ml-in-barcelona/server-reason-react | webapi.ml | module Dom = struct
type element
type window
end
| null | https://raw.githubusercontent.com/ml-in-barcelona/server-reason-react/a5d22907eb2633bcb8e77808f6c677802062953a/lib/web/webapi.ml | ocaml | module Dom = struct
type element
type window
end
|
|
736f187bce975f95c0c4d1bd0630032514d74411db4e94d92ceb8e3824fc9969 | rtoy/ansi-cl-tests | format-paren.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Oct 17 20:28:24 2004
;;;; Contains: Tests of the ~( format directives
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(def-format-test format.paren.1
"~(XXyy~AuuVV~)" ("ABc dEF ghI") "xxyyabc def ghiuuvv")
Conversion of simple characters to downcase
(deftest format.paren.2
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(upper-case-p c)
(let ((s1 (format nil "~(~c~)" c))
(s2 (string (char-downcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it)
nil)
(deftest formatter.paren.2
(let ((fn (formatter "~(~c~)")))
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(upper-case-p c)
(let ((s1 (formatter-call-to-string fn c))
(s2 (string (char-downcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it))
nil)
(def-format-test format.paren.3
"~@(this is a TEST.~)" nil "This is a test.")
(def-format-test format.paren.4
"~@(!@#$%^&*this is a TEST.~)" nil "!@#$%^&*This is a test.")
(def-format-test format.paren.5
"~:(this is a TEST.~)" nil "This Is A Test.")
(def-format-test format.paren.6
"~:(this is7a TEST.~)" nil "This Is7a Test.")
(def-format-test format.paren.7
"~:@(this is AlSo A teSt~)" nil "THIS IS ALSO A TEST")
(deftest format.paren.8
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(lower-case-p c)
(let ((s1 (format nil "~@:(~c~)" c))
(s2 (string (char-upcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it)
nil)
(deftest formatter.paren.8
(let ((fn (formatter "~@:(~c~)")))
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(lower-case-p c)
(let ((s1 (formatter-call-to-string fn c))
(s2 (string (char-upcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it))
nil)
;;; Nested conversion
(def-format-test format.paren.9
"~(aBc ~:(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.10
"~(aBc ~(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.11
"~@(aBc ~:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.12
"~(aBc ~@(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.13
"~(aBc ~:(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.14
"~:(aBc ~(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.15
"~:(aBc ~:(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.16
"~:(aBc ~@(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.17
"~:(aBc ~@:(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.18
"~@(aBc ~(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.19
"~@(aBc ~:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.20
"~@(aBc ~@(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.21
"~@(aBc ~@:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.22
"~:@(aBc ~(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.23
"~@:(aBc ~:(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.24
"~:@(aBc ~@(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.25
"~@:(aBc ~@:(def~) GHi~)" nil "ABC DEF GHI")
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/format-paren.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of the ~( format directives
Nested conversion | Author :
Created : Sun Oct 17 20:28:24 2004
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(def-format-test format.paren.1
"~(XXyy~AuuVV~)" ("ABc dEF ghI") "xxyyabc def ghiuuvv")
Conversion of simple characters to downcase
(deftest format.paren.2
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(upper-case-p c)
(let ((s1 (format nil "~(~c~)" c))
(s2 (string (char-downcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it)
nil)
(deftest formatter.paren.2
(let ((fn (formatter "~(~c~)")))
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(upper-case-p c)
(let ((s1 (formatter-call-to-string fn c))
(s2 (string (char-downcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it))
nil)
(def-format-test format.paren.3
"~@(this is a TEST.~)" nil "This is a test.")
(def-format-test format.paren.4
"~@(!@#$%^&*this is a TEST.~)" nil "!@#$%^&*This is a test.")
(def-format-test format.paren.5
"~:(this is a TEST.~)" nil "This Is A Test.")
(def-format-test format.paren.6
"~:(this is7a TEST.~)" nil "This Is7a Test.")
(def-format-test format.paren.7
"~:@(this is AlSo A teSt~)" nil "THIS IS ALSO A TEST")
(deftest format.paren.8
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(lower-case-p c)
(let ((s1 (format nil "~@:(~c~)" c))
(s2 (string (char-upcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it)
nil)
(deftest formatter.paren.8
(let ((fn (formatter "~@:(~c~)")))
(loop for i from 0 below (min char-code-limit (ash 1 16))
for c = (code-char i)
when (and c
(eql (char-code c) (char-int c))
(lower-case-p c)
(let ((s1 (formatter-call-to-string fn c))
(s2 (string (char-upcase c))))
(if
(or (not (eql (length s1) 1))
(not (eql (length s2) 1))
(not (eql (elt s1 0)
(elt s2 0))))
(list i c s1 s2)
nil)))
collect it))
nil)
(def-format-test format.paren.9
"~(aBc ~:(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.10
"~(aBc ~(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.11
"~@(aBc ~:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.12
"~(aBc ~@(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.13
"~(aBc ~:(def~) GHi~)" nil "abc def ghi")
(def-format-test format.paren.14
"~:(aBc ~(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.15
"~:(aBc ~:(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.16
"~:(aBc ~@(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.17
"~:(aBc ~@:(def~) GHi~)" nil "Abc Def Ghi")
(def-format-test format.paren.18
"~@(aBc ~(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.19
"~@(aBc ~:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.20
"~@(aBc ~@(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.21
"~@(aBc ~@:(def~) GHi~)" nil "Abc def ghi")
(def-format-test format.paren.22
"~:@(aBc ~(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.23
"~@:(aBc ~:(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.24
"~:@(aBc ~@(def~) GHi~)" nil "ABC DEF GHI")
(def-format-test format.paren.25
"~@:(aBc ~@:(def~) GHi~)" nil "ABC DEF GHI")
|
6e887428de7f78dad31acdcbf3bdd8de970bc25e1748b944a74ee0447ae16553 | manuel-serrano/bigloo | dsssl.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / / runtime / Llib / dsssl.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Sat Jul 3 11:30:29 1997 * /
* Last change : Sun Aug 25 09:08:52 2019 ( serrano ) * /
;* ------------------------------------------------------------- */
* support for Dsssl ( Iso / Iec 10179:1996 ) * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __dsssl
(import __error
__param
__bexit
__object
__thread)
(use __type
__bigloo
__tvector
__bignum
__bit
__r4_output_6_10_3
__r4_ports_6_10_1
__r4_control_features_6_9
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_equivalence_6_2
__r4_characters_6_6
__r4_vectors_6_8
__r4_booleans_6_1
__r4_pairs_and_lists_6_3
__r4_strings_6_7
__r4_symbols_6_4
__evenv)
(export (dsssl-named-constant?::bool ::obj)
(make-dsssl-function-prelude ::obj ::obj ::obj ::procedure)
(dsssl-get-key-arg ::obj ::keyword ::obj)
(dsssl-get-key-rest-arg ::obj ::pair-nil)
(dsssl-check-key-args! ::obj ::obj)
(dsssl-formals->scheme-formals ::obj ::procedure)
(dsssl-formals->scheme-typed-formals ::obj ::procedure ::bool)))
;*---------------------------------------------------------------------*/
* dsssl - named - constant ? ... * /
;* ------------------------------------------------------------- */
;* Is an object a dsssl named constant (#!optional, #!key or */
;* #!rest) ? */
;*---------------------------------------------------------------------*/
(define (dsssl-named-constant? obj)
(and (cnst? obj) (memq obj '(#!rest #!optional #!key))))
;*---------------------------------------------------------------------*/
;* make-dsssl-function-prelude ... */
;* ------------------------------------------------------------- */
* This function decodes a DSSSL formal parameter list and * /
;* produce a header decoding the actual values. */
;* ------------------------------------------------------------- */
;* It implements a finite automata where each state is represented */
;* by a function. */
;*---------------------------------------------------------------------*/
(define (make-dsssl-function-prelude where formals body err)
(define (scheme-state args)
(cond
((not (pair? args))
body)
((and (not (symbol? (car args))) (not (pair? (car args))))
either it is a DSSSL named constant or an error .
( for bootstrapping ease , do n't use CASE that uses the index )
(cond
((eq? (car args) #!optional)
(enter-dsssl-state (cdr args) optional-state))
((eq? (car args) #!rest)
(enter-dsssl-state (cdr args) rest-state))
((eq? (car args) #!key)
(enter-dsssl-state (cdr args) no-rest-key-state))
(else
(err where "Illegal formal list.1" (cons (car args) formals)))))
(else
;; regular Scheme formal, we simply skip
(scheme-state (cdr args)))))
(define (enter-dsssl-state args next-state)
(let loop ((as args))
(cond
((not (pair? as))
(err where "Illegal formal list.2" (cons as formals)))
(else
(match-case (car as)
((? symbol?)
(let ((dsssl-arg (gensym 'dsssl)))
`(let ((,dsssl-arg ,(car as)))
,(next-state args dsssl-arg))))
(((? symbol?) ?-)
(let ((dsssl-arg (gensym 'dsssl)))
`(let ((,dsssl-arg ,(car (car as))))
,(next-state args dsssl-arg))))
(else
(err where "Illegal formal list.3" (cons (car as) formals))))))))
(define (optional-state args dsssl-arg)
(define (get-keyword-arguments args)
(let loop ((args args))
(cond
((not (pair? args))
'())
((eq? (car args) '#!key)
(let loop ((args (cdr args))
(res '()))
(cond
((or (not (pair? args))
(not (or (pair? (car args))
(symbol? (car args))))
(eq? (car args) '#!optional)
(eq? (car args) '#!rest))
res)
((symbol? (car args))
(loop (cdr args)
(cons (symbol->keyword (car args)) res)))
(else
(loop (cdr args)
(cons (symbol->keyword (caar args)) res))))))
(else
(loop (cdr args))))))
(define keyword-arguments (get-keyword-arguments args))
(define (one-optional-arg arg initializer rest)
(let ((tmp (gensym 'tmp)))
`(let ((,arg (if (if (null? ,dsssl-arg)
#t
(memq (car ,dsssl-arg) ',keyword-arguments))
,initializer
(let ((,tmp (car ,dsssl-arg)))
MS : 30 sep 2008
;; Don't forget the explicit begin because
the DSSSL code is no longer post
;; macro-expanded by eval (for avoiding
;; duplicated macro-expansion of all function
;; definitions).
(begin
(set! ,dsssl-arg (cdr ,dsssl-arg))
,tmp)))))
,(optional-args rest))))
(define (optional-args args)
(cond
((null? args)
body)
((not (pair? args))
(err where "Illegal DSSSL formal list (#!optional)" formals))
((and (not (symbol? (car args))) (not (pair? (car args))))
either it is a DSSSL named constant or an error .
;; (for bootstrapping ease, don't use CASE but COND)
(cond
((eq? (car args) #!rest)
(rest-state (cdr args) dsssl-arg))
((eq? (car args) #!key)
(no-rest-key-state (cdr args) dsssl-arg))
(else
(err where "Illegal DSSSL formal list (#!optional)" formals))))
(else
an optional DSSSL formal
(match-case (car args)
(((and (? symbol?) ?arg) ?initializer)
(one-optional-arg arg initializer (cdr args)))
((and (? symbol?) ?arg)
(one-optional-arg arg #f (cdr args)))
(else
(err where "Illegal DSSSL formal list (#!optional)" formals))))))
(optional-args args))
(define (rest-state args dsssl-arg)
(cond
((not (pair? args))
(err where "Illegal DSSSL formal list (#!rest)" formals))
((not (symbol? (car args)))
(err where "Illegal DSSSL formal list (#!rest)" formals))
(else
`(let ((,(car args) ,dsssl-arg))
,(exit-rest-state (cdr args) dsssl-arg)))))
(define (exit-rest-state args dsssl-arg)
(cond
((null? args)
body)
((not (pair? args))
(err where "Illegal DSSSL formal list (#!rest)" formals))
((eq? (car args) #!key)
(rest-key-state (cdr args) dsssl-arg))
(else
(err where "Illegal DSSSL formal list (#!rest)" formals))))
(define (rest-key-state args dsssl-arg)
(define (get-keyword-arguments args)
(map (lambda (x)
(cond
((and (pair? x) (symbol? (car x)))
(symbol->keyword (car x)))
((symbol? x)
(symbol->keyword x))
(else
(err where "Illegal #!keys parameters" formals))))
args))
(cond
((null? args)
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
(let ((keys (get-keyword-arguments args)))
(if (null? keys)
(err where "Illegal DSSSL formal list (#!key)" formals)
(key-state args dsssl-arg '() #f))))))
(define (no-rest-key-state args dsssl-arg)
(define (get-keyword-arguments args)
(let loop ((args args)
(aux '()))
(cond
((null? args)
(reverse! aux))
((eq? (car args) #!rest)
(reverse! aux))
(else
(match-case (car args)
((and (? symbol?) ?arg)
(loop (cdr args) (cons (symbol->keyword arg) aux)))
(((and (? symbol?) ?arg) ?-)
(loop (cdr args) (cons (symbol->keyword arg) aux)))
(else
(err where "Illegal DSSSL formal list (#!key)" formals)))))))
(cond
((null? args)
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
(let ((keys (get-keyword-arguments args)))
(if (null? keys)
(err where "Illegal DSSSL formal list (#!key)" formals)
(key-state args dsssl-arg '() #t))))))
(define (key-state args dsssl-arg collected-keys allow-restp)
(define (one-key-arg arg initializer collected-keys)
`(let ((,arg (dsssl-get-key-arg ,dsssl-arg
,(symbol->keyword arg) ,initializer)))
,(key-state (cdr args)
dsssl-arg
(cons (symbol->keyword arg) collected-keys)
allow-restp)))
(define (rest-key-arg arg body)
`(let ((,arg (dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys)))
,body))
(cond
((null? args)
(if allow-restp
;; no #!rest before the #!key, check that everything is bound
`(if (null? (dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys))
,body
(error "dsssl-get-key-arg"
(apply string-append "Illegal extra key arguments: "
(map (lambda (v)
(format "~a " v))
(dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys)))
,dsssl-arg))
;; a #!rest was found before the #!key, accept everthing
body))
((eq? (car args) #!rest)
(if (or (not allow-restp)
(null? (cdr args))
(not (symbol? (cadr args)))
(pair? (cddr args)))
(err where "Illegal DSSSL formal list (#!rest)" formals)
(rest-key-arg (cadr args) body)))
((not (pair? args))
(err where "Illegal DSSSL formal list (#!key)" formals))
((and (not (symbol? (car args))) (not (pair? (car args))))
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
an optional DSSSL formal
(match-case (car args)
(((and (? symbol?) ?arg) ?initializer)
(one-key-arg arg initializer collected-keys))
((and (? symbol?) ?arg)
(one-key-arg arg #f collected-keys))
(else
(err where "Illegal DSSSL formal list (#!key)" formals))))))
(scheme-state formals))
;*---------------------------------------------------------------------*/
* dsssl - check - key - args ! ... * /
;* ------------------------------------------------------------- */
* This function checks that dsssl args are , at runtime , * /
* correctly formed . That is , the dsssl - args variable must hold * /
* a serie of pairs where the first element is a keyword . * /
;* Furthermore, if key-list is non-nil, we check that for each */
;* pair, if the key is present in key-list. */
;*---------------------------------------------------------------------*/
(define (dsssl-check-key-args! dsssl-args key-list)
(if (null? key-list)
(let loop ((args dsssl-args))
(cond
((null? args)
dsssl-args)
((or (not (pair? args))
(null? (cdr args))
(not (keyword? (car args))))
(error "dsssl formal parsing"
"Unexpected #!keys parameters"
args))
(else
(loop (cddr args)))))
(let loop ((args dsssl-args)
(armed #f)
(opts '()))
(cond
((null? args)
(reverse! opts))
((or (not (pair? args))
(null? (cdr args))
(not (keyword? (car args)))
(not (memq (car args) key-list)))
(if (not armed)
(loop (cdr args) armed opts)
(loop (cdr args)
#f
(cons (car args) opts))))
(else
(loop (cddr args) #t opts))))))
;*---------------------------------------------------------------------*/
* dsssl - get - key - arg ... * /
;* ------------------------------------------------------------- */
;* dsssl args have already been tested. We know for sure that */
* it is a serie of pairs where first elements are keywords . * /
;*---------------------------------------------------------------------*/
(define (dsssl-get-key-arg dsssl-args keyword initializer)
(let loop ((args dsssl-args))
(cond
((not (pair? args))
(if (null? args)
initializer
(error "dsssl-get-key-arg"
"Illegal DSSSL arguments" dsssl-args)))
((not (keyword? (car args)))
(loop (cdr args)))
((eq? (car args) keyword)
(if (not (pair? (cdr args)))
(error "dsssl-get-key-arg"
"Keyword argument misses value"
(car args))
(cadr args)))
((not (keyword? (car args)))
(error "dsssl-get-key-arg"
"Illegal keyword actual value"
(car args)))
(else
(if (not (pair? (cdr args)))
(error "dsssl-get-key-arg"
"Keyword argument misses value"
(car args))
(loop (cddr args)))))))
;*---------------------------------------------------------------------*/
* dsssl - get - key - rest - arg ... * /
;*---------------------------------------------------------------------*/
(define (dsssl-get-key-rest-arg dsssl-args keys)
(let loop ((args dsssl-args))
(cond
((null? args)
'())
((or (not (keyword? (car args)))
(null? (cdr args))
(not (memq (car args) keys)))
(cons (car args) (loop (cdr args))))
(else
(loop (cddr args))))))
;*---------------------------------------------------------------------*/
;* id-sans-type ... */
;* ------------------------------------------------------------- */
;* This function remove the type from an identifier. Thas is, */
;* provided the symbol `id::type', it returns `id'. */
;*---------------------------------------------------------------------*/
(define (id-sans-type::symbol id::symbol)
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
id)
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(string->symbol (substring string 0 walker)))
(else
(loop (+fx walker 1)))))))
;*---------------------------------------------------------------------*/
* dsssl - formals->scheme - formals ... * /
;*---------------------------------------------------------------------*/
(define (dsssl-formals->scheme-formals formals err)
(dsssl-formals->scheme-typed-formals formals err #f))
;*---------------------------------------------------------------------*/
* dsssl - formals->scheme - formals ... * /
;* ------------------------------------------------------------- */
;* This function parses a formal arguments list and removes */
* the DSSSL named constant in order to construct a regular Scheme * /
;* formal parameter list. */
;* eg: x y #!optional z #!rest r #!key k -> x y . z */
;* If the argument typed is true, fixed argument are left typed. */
;* Otherwise, they are untyped. */
;* ------------------------------------------------------------- */
;* This function does not check the whole correctness of the */
* formal parameters list . It only checks until the first * /
* DSSSL formal parameter is found . * /
;*---------------------------------------------------------------------*/
(define (dsssl-formals->scheme-typed-formals formals err typed)
(define (dsssl-named-constant? obj)
(memq obj '(#!optional #!rest #!key)))
(define (dsssl-defaulted-formal? obj)
(and (pair? obj)
(pair? (cdr obj))
(null? (cddr obj))))
(define (dsssl-default-formal obj)
(car obj))
(let loop ((args formals)
(dsssl #f))
(cond
((null? args)
'())
((not (pair? args))
(cond
(dsssl
(err "Can't use both DSSSL named constant"
"and `.' notation"
formals))
((not (symbol? args))
(err "Illegal formal parameter" "symbol expected" formals))
(else
(id-sans-type args))))
((not (symbol? (car args)))
(cond
((dsssl-named-constant? (car args))
(loop (cdr args) #t))
((not dsssl)
(err "Illegal formal parameter" "symbol expected" formals))
((dsssl-defaulted-formal? (car args))
(id-sans-type (dsssl-default-formal (car args))))
(else
(err "Illegal formal parameter"
"symbol or named constant expected"
formals))))
(dsssl
(id-sans-type (car args)))
(else
(cons (if typed (car args) (id-sans-type (car args)))
(loop (cdr args) #f))))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/runtime/Llib/dsssl.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* Is an object a dsssl named constant (#!optional, #!key or */
* #!rest) ? */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-dsssl-function-prelude ... */
* ------------------------------------------------------------- */
* produce a header decoding the actual values. */
* ------------------------------------------------------------- */
* It implements a finite automata where each state is represented */
* by a function. */
*---------------------------------------------------------------------*/
regular Scheme formal, we simply skip
Don't forget the explicit begin because
macro-expanded by eval (for avoiding
duplicated macro-expansion of all function
definitions).
(for bootstrapping ease, don't use CASE but COND)
no #!rest before the #!key, check that everything is bound
a #!rest was found before the #!key, accept everthing
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* Furthermore, if key-list is non-nil, we check that for each */
* pair, if the key is present in key-list. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* dsssl args have already been tested. We know for sure that */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* id-sans-type ... */
* ------------------------------------------------------------- */
* This function remove the type from an identifier. Thas is, */
* provided the symbol `id::type', it returns `id'. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* ------------------------------------------------------------- */
* This function parses a formal arguments list and removes */
* formal parameter list. */
* eg: x y #!optional z #!rest r #!key k -> x y . z */
* If the argument typed is true, fixed argument are left typed. */
* Otherwise, they are untyped. */
* ------------------------------------------------------------- */
* This function does not check the whole correctness of the */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / / runtime / Llib / dsssl.scm * /
* Author : * /
* Creation : Sat Jul 3 11:30:29 1997 * /
* Last change : Sun Aug 25 09:08:52 2019 ( serrano ) * /
* support for Dsssl ( Iso / Iec 10179:1996 ) * /
(module __dsssl
(import __error
__param
__bexit
__object
__thread)
(use __type
__bigloo
__tvector
__bignum
__bit
__r4_output_6_10_3
__r4_ports_6_10_1
__r4_control_features_6_9
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_equivalence_6_2
__r4_characters_6_6
__r4_vectors_6_8
__r4_booleans_6_1
__r4_pairs_and_lists_6_3
__r4_strings_6_7
__r4_symbols_6_4
__evenv)
(export (dsssl-named-constant?::bool ::obj)
(make-dsssl-function-prelude ::obj ::obj ::obj ::procedure)
(dsssl-get-key-arg ::obj ::keyword ::obj)
(dsssl-get-key-rest-arg ::obj ::pair-nil)
(dsssl-check-key-args! ::obj ::obj)
(dsssl-formals->scheme-formals ::obj ::procedure)
(dsssl-formals->scheme-typed-formals ::obj ::procedure ::bool)))
* dsssl - named - constant ? ... * /
(define (dsssl-named-constant? obj)
(and (cnst? obj) (memq obj '(#!rest #!optional #!key))))
* This function decodes a DSSSL formal parameter list and * /
(define (make-dsssl-function-prelude where formals body err)
(define (scheme-state args)
(cond
((not (pair? args))
body)
((and (not (symbol? (car args))) (not (pair? (car args))))
either it is a DSSSL named constant or an error .
( for bootstrapping ease , do n't use CASE that uses the index )
(cond
((eq? (car args) #!optional)
(enter-dsssl-state (cdr args) optional-state))
((eq? (car args) #!rest)
(enter-dsssl-state (cdr args) rest-state))
((eq? (car args) #!key)
(enter-dsssl-state (cdr args) no-rest-key-state))
(else
(err where "Illegal formal list.1" (cons (car args) formals)))))
(else
(scheme-state (cdr args)))))
(define (enter-dsssl-state args next-state)
(let loop ((as args))
(cond
((not (pair? as))
(err where "Illegal formal list.2" (cons as formals)))
(else
(match-case (car as)
((? symbol?)
(let ((dsssl-arg (gensym 'dsssl)))
`(let ((,dsssl-arg ,(car as)))
,(next-state args dsssl-arg))))
(((? symbol?) ?-)
(let ((dsssl-arg (gensym 'dsssl)))
`(let ((,dsssl-arg ,(car (car as))))
,(next-state args dsssl-arg))))
(else
(err where "Illegal formal list.3" (cons (car as) formals))))))))
(define (optional-state args dsssl-arg)
(define (get-keyword-arguments args)
(let loop ((args args))
(cond
((not (pair? args))
'())
((eq? (car args) '#!key)
(let loop ((args (cdr args))
(res '()))
(cond
((or (not (pair? args))
(not (or (pair? (car args))
(symbol? (car args))))
(eq? (car args) '#!optional)
(eq? (car args) '#!rest))
res)
((symbol? (car args))
(loop (cdr args)
(cons (symbol->keyword (car args)) res)))
(else
(loop (cdr args)
(cons (symbol->keyword (caar args)) res))))))
(else
(loop (cdr args))))))
(define keyword-arguments (get-keyword-arguments args))
(define (one-optional-arg arg initializer rest)
(let ((tmp (gensym 'tmp)))
`(let ((,arg (if (if (null? ,dsssl-arg)
#t
(memq (car ,dsssl-arg) ',keyword-arguments))
,initializer
(let ((,tmp (car ,dsssl-arg)))
MS : 30 sep 2008
the DSSSL code is no longer post
(begin
(set! ,dsssl-arg (cdr ,dsssl-arg))
,tmp)))))
,(optional-args rest))))
(define (optional-args args)
(cond
((null? args)
body)
((not (pair? args))
(err where "Illegal DSSSL formal list (#!optional)" formals))
((and (not (symbol? (car args))) (not (pair? (car args))))
either it is a DSSSL named constant or an error .
(cond
((eq? (car args) #!rest)
(rest-state (cdr args) dsssl-arg))
((eq? (car args) #!key)
(no-rest-key-state (cdr args) dsssl-arg))
(else
(err where "Illegal DSSSL formal list (#!optional)" formals))))
(else
an optional DSSSL formal
(match-case (car args)
(((and (? symbol?) ?arg) ?initializer)
(one-optional-arg arg initializer (cdr args)))
((and (? symbol?) ?arg)
(one-optional-arg arg #f (cdr args)))
(else
(err where "Illegal DSSSL formal list (#!optional)" formals))))))
(optional-args args))
(define (rest-state args dsssl-arg)
(cond
((not (pair? args))
(err where "Illegal DSSSL formal list (#!rest)" formals))
((not (symbol? (car args)))
(err where "Illegal DSSSL formal list (#!rest)" formals))
(else
`(let ((,(car args) ,dsssl-arg))
,(exit-rest-state (cdr args) dsssl-arg)))))
(define (exit-rest-state args dsssl-arg)
(cond
((null? args)
body)
((not (pair? args))
(err where "Illegal DSSSL formal list (#!rest)" formals))
((eq? (car args) #!key)
(rest-key-state (cdr args) dsssl-arg))
(else
(err where "Illegal DSSSL formal list (#!rest)" formals))))
(define (rest-key-state args dsssl-arg)
(define (get-keyword-arguments args)
(map (lambda (x)
(cond
((and (pair? x) (symbol? (car x)))
(symbol->keyword (car x)))
((symbol? x)
(symbol->keyword x))
(else
(err where "Illegal #!keys parameters" formals))))
args))
(cond
((null? args)
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
(let ((keys (get-keyword-arguments args)))
(if (null? keys)
(err where "Illegal DSSSL formal list (#!key)" formals)
(key-state args dsssl-arg '() #f))))))
(define (no-rest-key-state args dsssl-arg)
(define (get-keyword-arguments args)
(let loop ((args args)
(aux '()))
(cond
((null? args)
(reverse! aux))
((eq? (car args) #!rest)
(reverse! aux))
(else
(match-case (car args)
((and (? symbol?) ?arg)
(loop (cdr args) (cons (symbol->keyword arg) aux)))
(((and (? symbol?) ?arg) ?-)
(loop (cdr args) (cons (symbol->keyword arg) aux)))
(else
(err where "Illegal DSSSL formal list (#!key)" formals)))))))
(cond
((null? args)
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
(let ((keys (get-keyword-arguments args)))
(if (null? keys)
(err where "Illegal DSSSL formal list (#!key)" formals)
(key-state args dsssl-arg '() #t))))))
(define (key-state args dsssl-arg collected-keys allow-restp)
(define (one-key-arg arg initializer collected-keys)
`(let ((,arg (dsssl-get-key-arg ,dsssl-arg
,(symbol->keyword arg) ,initializer)))
,(key-state (cdr args)
dsssl-arg
(cons (symbol->keyword arg) collected-keys)
allow-restp)))
(define (rest-key-arg arg body)
`(let ((,arg (dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys)))
,body))
(cond
((null? args)
(if allow-restp
`(if (null? (dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys))
,body
(error "dsssl-get-key-arg"
(apply string-append "Illegal extra key arguments: "
(map (lambda (v)
(format "~a " v))
(dsssl-get-key-rest-arg ,dsssl-arg ',collected-keys)))
,dsssl-arg))
body))
((eq? (car args) #!rest)
(if (or (not allow-restp)
(null? (cdr args))
(not (symbol? (cadr args)))
(pair? (cddr args)))
(err where "Illegal DSSSL formal list (#!rest)" formals)
(rest-key-arg (cadr args) body)))
((not (pair? args))
(err where "Illegal DSSSL formal list (#!key)" formals))
((and (not (symbol? (car args))) (not (pair? (car args))))
(err where "Illegal DSSSL formal list (#!key)" formals))
(else
an optional DSSSL formal
(match-case (car args)
(((and (? symbol?) ?arg) ?initializer)
(one-key-arg arg initializer collected-keys))
((and (? symbol?) ?arg)
(one-key-arg arg #f collected-keys))
(else
(err where "Illegal DSSSL formal list (#!key)" formals))))))
(scheme-state formals))
* dsssl - check - key - args ! ... * /
* This function checks that dsssl args are , at runtime , * /
* correctly formed . That is , the dsssl - args variable must hold * /
* a serie of pairs where the first element is a keyword . * /
(define (dsssl-check-key-args! dsssl-args key-list)
(if (null? key-list)
(let loop ((args dsssl-args))
(cond
((null? args)
dsssl-args)
((or (not (pair? args))
(null? (cdr args))
(not (keyword? (car args))))
(error "dsssl formal parsing"
"Unexpected #!keys parameters"
args))
(else
(loop (cddr args)))))
(let loop ((args dsssl-args)
(armed #f)
(opts '()))
(cond
((null? args)
(reverse! opts))
((or (not (pair? args))
(null? (cdr args))
(not (keyword? (car args)))
(not (memq (car args) key-list)))
(if (not armed)
(loop (cdr args) armed opts)
(loop (cdr args)
#f
(cons (car args) opts))))
(else
(loop (cddr args) #t opts))))))
* dsssl - get - key - arg ... * /
* it is a serie of pairs where first elements are keywords . * /
(define (dsssl-get-key-arg dsssl-args keyword initializer)
(let loop ((args dsssl-args))
(cond
((not (pair? args))
(if (null? args)
initializer
(error "dsssl-get-key-arg"
"Illegal DSSSL arguments" dsssl-args)))
((not (keyword? (car args)))
(loop (cdr args)))
((eq? (car args) keyword)
(if (not (pair? (cdr args)))
(error "dsssl-get-key-arg"
"Keyword argument misses value"
(car args))
(cadr args)))
((not (keyword? (car args)))
(error "dsssl-get-key-arg"
"Illegal keyword actual value"
(car args)))
(else
(if (not (pair? (cdr args)))
(error "dsssl-get-key-arg"
"Keyword argument misses value"
(car args))
(loop (cddr args)))))))
* dsssl - get - key - rest - arg ... * /
(define (dsssl-get-key-rest-arg dsssl-args keys)
(let loop ((args dsssl-args))
(cond
((null? args)
'())
((or (not (keyword? (car args)))
(null? (cdr args))
(not (memq (car args) keys)))
(cons (car args) (loop (cdr args))))
(else
(loop (cddr args))))))
(define (id-sans-type::symbol id::symbol)
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
id)
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(string->symbol (substring string 0 walker)))
(else
(loop (+fx walker 1)))))))
* dsssl - formals->scheme - formals ... * /
(define (dsssl-formals->scheme-formals formals err)
(dsssl-formals->scheme-typed-formals formals err #f))
* dsssl - formals->scheme - formals ... * /
* the DSSSL named constant in order to construct a regular Scheme * /
* formal parameters list . It only checks until the first * /
* DSSSL formal parameter is found . * /
(define (dsssl-formals->scheme-typed-formals formals err typed)
(define (dsssl-named-constant? obj)
(memq obj '(#!optional #!rest #!key)))
(define (dsssl-defaulted-formal? obj)
(and (pair? obj)
(pair? (cdr obj))
(null? (cddr obj))))
(define (dsssl-default-formal obj)
(car obj))
(let loop ((args formals)
(dsssl #f))
(cond
((null? args)
'())
((not (pair? args))
(cond
(dsssl
(err "Can't use both DSSSL named constant"
"and `.' notation"
formals))
((not (symbol? args))
(err "Illegal formal parameter" "symbol expected" formals))
(else
(id-sans-type args))))
((not (symbol? (car args)))
(cond
((dsssl-named-constant? (car args))
(loop (cdr args) #t))
((not dsssl)
(err "Illegal formal parameter" "symbol expected" formals))
((dsssl-defaulted-formal? (car args))
(id-sans-type (dsssl-default-formal (car args))))
(else
(err "Illegal formal parameter"
"symbol or named constant expected"
formals))))
(dsssl
(id-sans-type (car args)))
(else
(cons (if typed (car args) (id-sans-type (car args)))
(loop (cdr args) #f))))))
|
56acb73620d4bd546d494820e4f3ebde2b99cc8f8b6b11568a5183289d986ae6 | guardian/content-api-haskell-client | ContentApi.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE RecordWildCards #
module Network.Guardian.ContentApi
(
ContentApi
, runContentApi
, ApiConfig(..)
, defaultApiConfig
, ContentApiError
, contentSearch
, tagSearch
) where
import Network.Guardian.ContentApi.Content
import Network.Guardian.ContentApi.Tag
import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Resource
import Data.Aeson (FromJSON, decode)
import Data.Maybe (maybeToList)
import Data.Monoid
import Data.Typeable (Typeable)
import Data.Text (Text)
import Network.HTTP.Conduit
import Network.HTTP.Types
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T
type ContentApi a = ReaderT ApiConfig (ResourceT IO) a
runContentApi :: MonadIO f => ApiConfig -> ContentApi a -> f a
runContentApi config action = liftIO . runResourceT $ runReaderT action config
type ApiKey = Text
data ApiConfig = ApiConfig {
endpoint :: Builder
, apiKey :: Maybe ApiKey
, manager :: Manager
}
data ContentApiError = InvalidApiKey
| ParseError
| OtherContentApiError Int Text
deriving (Typeable, Show, Eq)
instance Exception ContentApiError
contentSearch :: ContentSearchQuery -> ContentApi ContentSearchResult
contentSearch = search <=< contentSearchUrl
tagSearch :: TagSearchQuery -> ContentApi TagSearchResult
tagSearch = search <=< tagSearchUrl
search :: (FromJSON r) => String -> ContentApi r
search url = do
ApiConfig _ _ mgr <- ask
httpReq <- parseUrl url
response <- catch (httpLbs httpReq mgr)
(\e -> case e :: HttpException of
StatusCodeException _ headers _ ->
maybe (throwIO e) throwIO (contentApiError headers)
_ -> throwIO e)
let searchResult = decode $ responseBody response
maybe (throwIO ParseError) return searchResult
contentSearchUrl :: ContentSearchQuery -> ContentApi String
contentSearchUrl ContentSearchQuery {..} =
mkUrl ["search"] $ param "q" csQueryText
<> sectionParam csSection
<> fieldsParam csShowFields
tagSearchUrl :: TagSearchQuery -> ContentApi String
tagSearchUrl TagSearchQuery {..} =
mkUrl ["tags"] $ param "q" tsQueryText
<> sectionParam tsSection
<> param "type" tsTagType
mkUrl :: [Text] -> QueryText -> ContentApi String
mkUrl path query = do
ApiConfig endpoint key _ <- ask
let query' = queryTextToQuery $ param "api-key" key <> query
return $ BC.unpack . toByteString $ endpoint <> encodePath path query'
fieldsParam :: [Text] -> QueryText
fieldsParam = multiParam "show-fields" ","
sectionParam :: [Text] -> QueryText
sectionParam = multiParam "section" "|"
param :: Text -> Maybe Text -> QueryText
param k = maybeToList . fmap (\v -> (k, Just v))
multiParam :: Text -> Text -> [Text] -> QueryText
multiParam _ _ [] = []
multiParam k sep vs = [(k, Just $ T.intercalate sep vs)]
contentApiError :: ResponseHeaders -> Maybe ContentApiError
contentApiError headers = case lookup "X-Mashery-Error-Code" headers of
Just "ERR_403_DEVELOPER_INACTIVE" -> Just InvalidApiKey
_ -> Nothing
defaultApiConfig :: MonadIO f => Maybe ApiKey -> f ApiConfig
defaultApiConfig key = do
man <- liftIO $ newManager conduitManagerSettings
return $ ApiConfig defaultEndpoint key man
where
defaultEndpoint = fromByteString ""
| null | https://raw.githubusercontent.com/guardian/content-api-haskell-client/f80195c4117570bc3013cbe93ceb9c5d3f5e17bd/guardian-content-api-client/Network/Guardian/ContentApi.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable # | # LANGUAGE RecordWildCards #
module Network.Guardian.ContentApi
(
ContentApi
, runContentApi
, ApiConfig(..)
, defaultApiConfig
, ContentApiError
, contentSearch
, tagSearch
) where
import Network.Guardian.ContentApi.Content
import Network.Guardian.ContentApi.Tag
import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Resource
import Data.Aeson (FromJSON, decode)
import Data.Maybe (maybeToList)
import Data.Monoid
import Data.Typeable (Typeable)
import Data.Text (Text)
import Network.HTTP.Conduit
import Network.HTTP.Types
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T
type ContentApi a = ReaderT ApiConfig (ResourceT IO) a
runContentApi :: MonadIO f => ApiConfig -> ContentApi a -> f a
runContentApi config action = liftIO . runResourceT $ runReaderT action config
type ApiKey = Text
data ApiConfig = ApiConfig {
endpoint :: Builder
, apiKey :: Maybe ApiKey
, manager :: Manager
}
data ContentApiError = InvalidApiKey
| ParseError
| OtherContentApiError Int Text
deriving (Typeable, Show, Eq)
instance Exception ContentApiError
contentSearch :: ContentSearchQuery -> ContentApi ContentSearchResult
contentSearch = search <=< contentSearchUrl
tagSearch :: TagSearchQuery -> ContentApi TagSearchResult
tagSearch = search <=< tagSearchUrl
search :: (FromJSON r) => String -> ContentApi r
search url = do
ApiConfig _ _ mgr <- ask
httpReq <- parseUrl url
response <- catch (httpLbs httpReq mgr)
(\e -> case e :: HttpException of
StatusCodeException _ headers _ ->
maybe (throwIO e) throwIO (contentApiError headers)
_ -> throwIO e)
let searchResult = decode $ responseBody response
maybe (throwIO ParseError) return searchResult
contentSearchUrl :: ContentSearchQuery -> ContentApi String
contentSearchUrl ContentSearchQuery {..} =
mkUrl ["search"] $ param "q" csQueryText
<> sectionParam csSection
<> fieldsParam csShowFields
tagSearchUrl :: TagSearchQuery -> ContentApi String
tagSearchUrl TagSearchQuery {..} =
mkUrl ["tags"] $ param "q" tsQueryText
<> sectionParam tsSection
<> param "type" tsTagType
mkUrl :: [Text] -> QueryText -> ContentApi String
mkUrl path query = do
ApiConfig endpoint key _ <- ask
let query' = queryTextToQuery $ param "api-key" key <> query
return $ BC.unpack . toByteString $ endpoint <> encodePath path query'
fieldsParam :: [Text] -> QueryText
fieldsParam = multiParam "show-fields" ","
sectionParam :: [Text] -> QueryText
sectionParam = multiParam "section" "|"
param :: Text -> Maybe Text -> QueryText
param k = maybeToList . fmap (\v -> (k, Just v))
multiParam :: Text -> Text -> [Text] -> QueryText
multiParam _ _ [] = []
multiParam k sep vs = [(k, Just $ T.intercalate sep vs)]
contentApiError :: ResponseHeaders -> Maybe ContentApiError
contentApiError headers = case lookup "X-Mashery-Error-Code" headers of
Just "ERR_403_DEVELOPER_INACTIVE" -> Just InvalidApiKey
_ -> Nothing
defaultApiConfig :: MonadIO f => Maybe ApiKey -> f ApiConfig
defaultApiConfig key = do
man <- liftIO $ newManager conduitManagerSettings
return $ ApiConfig defaultEndpoint key man
where
defaultEndpoint = fromByteString ""
|
82f7bc5417def3ae571cc39255cdf5d202284b8c3fbbf354c57646a395400a64 | bloomberg/blpapi-hs | PrettyPrint.hs | {-# LANGUAGE OverloadedStrings #-}
|
Module : Finance . Blpapi . PrettyPrint
Description : Printing Utility for Blpapi types
Copyright : Bloomberg Finance L.P.
License : MIT
Maintainer :
Stability : experimental
Portability : * nix , windows
A pretty printer for ' Element ' and ' Message ' .
Module : Finance.Blpapi.PrettyPrint
Description : Printing Utility for Blpapi types
Copyright : Bloomberg Finance L.P.
License : MIT
Maintainer :
Stability : experimental
Portability : *nix, windows
A pretty printer for 'Element' and 'Message'.
-}
module Finance.Blpapi.PrettyPrint (
Config(..),
defConfig,
BlpPretty(..),
prettyPrint,
prettyPrint'
) where
import Data.List (intersperse)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (mappend, mconcat, mempty)
import qualified Data.Text as T
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder, fromText, toLazyText)
import qualified Data.Text.Lazy.IO as TIO
import Finance.Blpapi.Event
data PState = PState { pstIndent :: Int
, pstLevel :: Int
}
-- | Configuration that can be passed to pretty print routines
data Config = Config {
confIndent :: Int
-- ^ Indentation spaces per level of nesting
}
-- | Class which determines what BLPAPI types can be pretty printed
class BlpPretty a where
pretty' :: Config -> a -> Text
pretty :: a -> Text
pretty = pretty' defConfig
instance BlpPretty Element where
pretty' = encodePrettyElement'
instance BlpPretty Message where
pretty' config m = pretty' config (messageData m)
-- |Pretty print an 'Finance.Blpapi.Element' or 'Finance.Blpapi.Message'
--with the default configuration
prettyPrint :: (BlpPretty a) => a -> IO ()
prettyPrint = TIO.putStrLn . pretty
-- |Pretty print an 'Finance.Blpapi.Element' or 'Finance.Blpapi.Message'
--with the provided configuration
prettyPrint' :: (BlpPretty a) => Config -> a -> IO ()
prettyPrint' c = TIO.putStrLn . pretty' c
| The default configuration : indent by four spaces per level of nesting
defConfig :: Config
defConfig = Config { confIndent = 4 }
pStateFromConfig :: Config -> PState
pStateFromConfig (Config ind) = PState ind 0
encodePrettyElement' :: Config -> Element -> Text
encodePrettyElement' c
= toLazyText . fromValue (pStateFromConfig c)
fromValue :: PState -> Element -> Builder
fromValue st = go
where
go (ElementArray v) = fromCompound st ("[","]") fromValue v
go (ElementSequence m) = fromCompound st ("{","}") fromPair $ getPair m
go (ElementChoice m) = fromCompound st ("{","}") fromPair $ getPair m
go v = fromText $ fromMaybe "" $ blpConvert v
getPair = Map.toList
fromCompound :: PState
-> (Builder, Builder)
-> (PState -> a -> Builder)
-> [a]
-> Builder
fromCompound st (delimL,delimR) fromItem items = mconcat
[ delimL
, if null items then mempty
else "\n" <> items' <> "\n" <> fromIndent st
, delimR
]
where
items' = mconcat . intersperse ",\n" $
map (\item -> fromIndent st' <> fromItem st' item)
items
st' = st { pstLevel = pstLevel st + 1 }
fromPair :: PState -> (T.Text, ElementWithDefinition) -> Builder
fromPair st (name, o)
= fromText name <> ": " <> fromValue st (elementWithDefinitionContent o)
fromIndent :: PState -> Builder
fromIndent (PState ind lvl) = mconcat $ replicate (ind * lvl) " "
(<>) :: Builder -> Builder -> Builder
(<>) = mappend
infixr 6 <>
| null | https://raw.githubusercontent.com/bloomberg/blpapi-hs/a4bdff86f3febcf8b06cbc70466c8abc177b973a/src/Finance/Blpapi/PrettyPrint.hs | haskell | # LANGUAGE OverloadedStrings #
| Configuration that can be passed to pretty print routines
^ Indentation spaces per level of nesting
| Class which determines what BLPAPI types can be pretty printed
|Pretty print an 'Finance.Blpapi.Element' or 'Finance.Blpapi.Message'
with the default configuration
|Pretty print an 'Finance.Blpapi.Element' or 'Finance.Blpapi.Message'
with the provided configuration | |
Module : Finance . Blpapi . PrettyPrint
Description : Printing Utility for Blpapi types
Copyright : Bloomberg Finance L.P.
License : MIT
Maintainer :
Stability : experimental
Portability : * nix , windows
A pretty printer for ' Element ' and ' Message ' .
Module : Finance.Blpapi.PrettyPrint
Description : Printing Utility for Blpapi types
Copyright : Bloomberg Finance L.P.
License : MIT
Maintainer :
Stability : experimental
Portability : *nix, windows
A pretty printer for 'Element' and 'Message'.
-}
module Finance.Blpapi.PrettyPrint (
Config(..),
defConfig,
BlpPretty(..),
prettyPrint,
prettyPrint'
) where
import Data.List (intersperse)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (mappend, mconcat, mempty)
import qualified Data.Text as T
import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder, fromText, toLazyText)
import qualified Data.Text.Lazy.IO as TIO
import Finance.Blpapi.Event
data PState = PState { pstIndent :: Int
, pstLevel :: Int
}
data Config = Config {
confIndent :: Int
}
class BlpPretty a where
pretty' :: Config -> a -> Text
pretty :: a -> Text
pretty = pretty' defConfig
instance BlpPretty Element where
pretty' = encodePrettyElement'
instance BlpPretty Message where
pretty' config m = pretty' config (messageData m)
prettyPrint :: (BlpPretty a) => a -> IO ()
prettyPrint = TIO.putStrLn . pretty
prettyPrint' :: (BlpPretty a) => Config -> a -> IO ()
prettyPrint' c = TIO.putStrLn . pretty' c
| The default configuration : indent by four spaces per level of nesting
defConfig :: Config
defConfig = Config { confIndent = 4 }
pStateFromConfig :: Config -> PState
pStateFromConfig (Config ind) = PState ind 0
encodePrettyElement' :: Config -> Element -> Text
encodePrettyElement' c
= toLazyText . fromValue (pStateFromConfig c)
fromValue :: PState -> Element -> Builder
fromValue st = go
where
go (ElementArray v) = fromCompound st ("[","]") fromValue v
go (ElementSequence m) = fromCompound st ("{","}") fromPair $ getPair m
go (ElementChoice m) = fromCompound st ("{","}") fromPair $ getPair m
go v = fromText $ fromMaybe "" $ blpConvert v
getPair = Map.toList
fromCompound :: PState
-> (Builder, Builder)
-> (PState -> a -> Builder)
-> [a]
-> Builder
fromCompound st (delimL,delimR) fromItem items = mconcat
[ delimL
, if null items then mempty
else "\n" <> items' <> "\n" <> fromIndent st
, delimR
]
where
items' = mconcat . intersperse ",\n" $
map (\item -> fromIndent st' <> fromItem st' item)
items
st' = st { pstLevel = pstLevel st + 1 }
fromPair :: PState -> (T.Text, ElementWithDefinition) -> Builder
fromPair st (name, o)
= fromText name <> ": " <> fromValue st (elementWithDefinitionContent o)
fromIndent :: PState -> Builder
fromIndent (PState ind lvl) = mconcat $ replicate (ind * lvl) " "
(<>) :: Builder -> Builder -> Builder
(<>) = mappend
infixr 6 <>
|
220b863709c765ac8298b4f1e9e4abf425e7b2260a5e76318fa27e1e830976a0 | static-analysis-engineering/codehawk | bCHARMSumTypeSerializer.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2021 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2021-2023 Aarno Labs, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHPretty
(* chutil *)
open CHPrettyUtil
open CHSumTypeSerializer
(* bchlib *)
open BCHBasicTypes
open BCHLibTypes
(* bchlibarm32 *)
open BCHARMTypes
let dmb_option_mfts: dmb_option_t mfts_int =
mk_mfts
"dmb_option_t"
[ (FullSystemRW, "SY");
(FullSystemW, "ST");
(InnerShareableRW, "ISH");
(InnerShareableW, "ISHST");
(NonShareableRW, "NSH");
(NonShareableW, "NSHST");
(OuterShareableRW, "OSH");
(OuterShareableW, "OSHST") ]
let shift_rotate_type_mfts: shift_rotate_type_t mfts_int =
mk_mfts
"shift_rotate_type_t"
[ (SRType_LSL, "LSL");
(SRType_LSR, "LSR");
(SRType_ASR, "ASR");
(SRType_ROR, "ROR");
(SRType_RRX, "RRX") ]
class vfp_datatype_mcts_t: [vfp_datatype_t] mfts_int =
object
inherit [vfp_datatype_t] mcts_t "vfp_datatype_t"
method ts (t:vfp_datatype_t) =
match t with
| VfpNone -> "n"
| VfpSize _ -> "z"
| VfpFloat _ -> "f"
| VfpInt _ -> "i"
| VfpPolynomial _ -> "p"
| VfpSignedInt _ -> "s"
| VfpUnsignedInt _ -> "u"
method tags = ["f"; "i"; "n"; "p"; "s"; "u"; "z"]
end
let vfp_datatype_mcts: vfp_datatype_t mfts_int =
new vfp_datatype_mcts_t
class register_shift_rotate_mcts_t: [ register_shift_rotate_t ] mfts_int =
object
inherit [ register_shift_rotate_t ] mcts_t "register_shift_rotate_t"
method ts (r:register_shift_rotate_t) =
match r with
| ARMImmSRT _ -> "i"
| ARMRegSRT _ -> "r"
method tags = [ "i"; "r" ]
end
let register_shift_rotate_mcts:register_shift_rotate_t mfts_int =
new register_shift_rotate_mcts_t
class arm_memory_offset_mcts_t: [ arm_memory_offset_t ] mfts_int =
object
inherit [ arm_memory_offset_t ] mcts_t "arm_memory_offset_t"
method ts (f:arm_memory_offset_t) =
match f with
| ARMImmOffset _ -> "i"
| ARMIndexOffset _ -> "x"
| ARMShiftedIndexOffset _ -> "s"
method tags = [ "i"; "s"; "x" ]
end
let arm_memory_offset_mcts:arm_memory_offset_t mfts_int =
new arm_memory_offset_mcts_t
class arm_simd_writeback_mcts_t: [arm_simd_writeback_t] mfts_int =
object
inherit [arm_simd_writeback_t] mcts_t "arm_simd_writeback_t"
method ts (f: arm_simd_writeback_t) =
match f with
| SIMDNoWriteback -> "n"
| SIMDBytesTransferred _ -> "b"
| SIMDAddressOffsetRegister _ -> "r"
method tags = ["b"; "n"; "r"]
end
let arm_simd_writeback_mcts: arm_simd_writeback_t mfts_int =
new arm_simd_writeback_mcts_t
class arm_simd_list_element_mcts_t: [arm_simd_list_element_t] mfts_int =
object
inherit [arm_simd_list_element_t] mcts_t "arm_simd_list_element_t"
method ts (f: arm_simd_list_element_t) =
match f with
| SIMDReg _ -> "r"
| SIMDRegElement _ -> "e"
| SIMDRegRepElement _ -> "re"
method tags = ["e"; "r"; "re"]
end
let arm_simd_list_element_mcts: arm_simd_list_element_t mfts_int =
new arm_simd_list_element_mcts_t
class arm_opkind_mcts_t: [ arm_operand_kind_t ] mfts_int =
object
inherit [ arm_operand_kind_t ] mcts_t "arm_operand_kind_t"
method ts (k:arm_operand_kind_t) =
match k with
| ARMDMBOption _ -> "d"
| ARMReg _ -> "r"
| ARMWritebackReg _ -> "wr"
| ARMSpecialReg _ -> "sr"
| ARMExtensionReg _ -> "xr"
| ARMExtensionRegElement _ -> "xre"
| ARMRegList _ -> "l"
| ARMExtensionRegList _ -> "xl"
| ARMRegBitSequence _ -> "b"
| ARMShiftedReg _ -> "s"
| ARMImmediate _ -> "i"
| ARMFPConstant _ -> "c"
| ARMAbsolute _ -> "a"
| ARMLiteralAddress _ -> "p"
| ARMMemMultiple _ -> "m"
| ARMOffsetAddress _ -> "o"
| ARMSIMDAddress _ -> "simda"
| ARMSIMDList _ -> "simdl"
method tags =
["a"; "b"; "c"; "d"; "i"; "l"; "m"; "o"; "p"; "r"; "r"; "s";
"simda"; "simdl"; "sr"; "wr"; "xr"]
end
let arm_opkind_mcts:arm_operand_kind_t mfts_int = new arm_opkind_mcts_t
let arm_opcode_cc_mfts: arm_opcode_cc_t mfts_int =
mk_mfts
"arm_opcode_cc_t"
[ (ACCEqual, "eq");
(ACCNotEqual, "ne");
(ACCCarrySet, "cs");
(ACCCarryClear, "cc");
(ACCNegative, "neg");
(ACCNonNegative, "nneg");
(ACCOverflow, "ov");
(ACCNoOverflow, "nov");
(ACCUnsignedHigher, "uh");
(ACCNotUnsignedHigher, "nuh");
(ACCSignedGE, "ge");
(ACCSignedLT, "lt");
(ACCSignedGT, "gt");
(ACCSignedLE, "le");
(ACCAlways, "a");
(ACCUnconditional,"unc")]
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/e8fed9f226abe38578768968279c8242eb21fea9/CodeHawk/CHB/bchlibarm32/bCHARMSumTypeSerializer.ml | ocaml | chutil
bchlib
bchlibarm32 | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2021 - 2023 Aarno Labs , LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2021-2023 Aarno Labs, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
chlib
open CHLanguage
open CHPretty
open CHPrettyUtil
open CHSumTypeSerializer
open BCHBasicTypes
open BCHLibTypes
open BCHARMTypes
let dmb_option_mfts: dmb_option_t mfts_int =
mk_mfts
"dmb_option_t"
[ (FullSystemRW, "SY");
(FullSystemW, "ST");
(InnerShareableRW, "ISH");
(InnerShareableW, "ISHST");
(NonShareableRW, "NSH");
(NonShareableW, "NSHST");
(OuterShareableRW, "OSH");
(OuterShareableW, "OSHST") ]
let shift_rotate_type_mfts: shift_rotate_type_t mfts_int =
mk_mfts
"shift_rotate_type_t"
[ (SRType_LSL, "LSL");
(SRType_LSR, "LSR");
(SRType_ASR, "ASR");
(SRType_ROR, "ROR");
(SRType_RRX, "RRX") ]
class vfp_datatype_mcts_t: [vfp_datatype_t] mfts_int =
object
inherit [vfp_datatype_t] mcts_t "vfp_datatype_t"
method ts (t:vfp_datatype_t) =
match t with
| VfpNone -> "n"
| VfpSize _ -> "z"
| VfpFloat _ -> "f"
| VfpInt _ -> "i"
| VfpPolynomial _ -> "p"
| VfpSignedInt _ -> "s"
| VfpUnsignedInt _ -> "u"
method tags = ["f"; "i"; "n"; "p"; "s"; "u"; "z"]
end
let vfp_datatype_mcts: vfp_datatype_t mfts_int =
new vfp_datatype_mcts_t
class register_shift_rotate_mcts_t: [ register_shift_rotate_t ] mfts_int =
object
inherit [ register_shift_rotate_t ] mcts_t "register_shift_rotate_t"
method ts (r:register_shift_rotate_t) =
match r with
| ARMImmSRT _ -> "i"
| ARMRegSRT _ -> "r"
method tags = [ "i"; "r" ]
end
let register_shift_rotate_mcts:register_shift_rotate_t mfts_int =
new register_shift_rotate_mcts_t
class arm_memory_offset_mcts_t: [ arm_memory_offset_t ] mfts_int =
object
inherit [ arm_memory_offset_t ] mcts_t "arm_memory_offset_t"
method ts (f:arm_memory_offset_t) =
match f with
| ARMImmOffset _ -> "i"
| ARMIndexOffset _ -> "x"
| ARMShiftedIndexOffset _ -> "s"
method tags = [ "i"; "s"; "x" ]
end
let arm_memory_offset_mcts:arm_memory_offset_t mfts_int =
new arm_memory_offset_mcts_t
class arm_simd_writeback_mcts_t: [arm_simd_writeback_t] mfts_int =
object
inherit [arm_simd_writeback_t] mcts_t "arm_simd_writeback_t"
method ts (f: arm_simd_writeback_t) =
match f with
| SIMDNoWriteback -> "n"
| SIMDBytesTransferred _ -> "b"
| SIMDAddressOffsetRegister _ -> "r"
method tags = ["b"; "n"; "r"]
end
let arm_simd_writeback_mcts: arm_simd_writeback_t mfts_int =
new arm_simd_writeback_mcts_t
class arm_simd_list_element_mcts_t: [arm_simd_list_element_t] mfts_int =
object
inherit [arm_simd_list_element_t] mcts_t "arm_simd_list_element_t"
method ts (f: arm_simd_list_element_t) =
match f with
| SIMDReg _ -> "r"
| SIMDRegElement _ -> "e"
| SIMDRegRepElement _ -> "re"
method tags = ["e"; "r"; "re"]
end
let arm_simd_list_element_mcts: arm_simd_list_element_t mfts_int =
new arm_simd_list_element_mcts_t
class arm_opkind_mcts_t: [ arm_operand_kind_t ] mfts_int =
object
inherit [ arm_operand_kind_t ] mcts_t "arm_operand_kind_t"
method ts (k:arm_operand_kind_t) =
match k with
| ARMDMBOption _ -> "d"
| ARMReg _ -> "r"
| ARMWritebackReg _ -> "wr"
| ARMSpecialReg _ -> "sr"
| ARMExtensionReg _ -> "xr"
| ARMExtensionRegElement _ -> "xre"
| ARMRegList _ -> "l"
| ARMExtensionRegList _ -> "xl"
| ARMRegBitSequence _ -> "b"
| ARMShiftedReg _ -> "s"
| ARMImmediate _ -> "i"
| ARMFPConstant _ -> "c"
| ARMAbsolute _ -> "a"
| ARMLiteralAddress _ -> "p"
| ARMMemMultiple _ -> "m"
| ARMOffsetAddress _ -> "o"
| ARMSIMDAddress _ -> "simda"
| ARMSIMDList _ -> "simdl"
method tags =
["a"; "b"; "c"; "d"; "i"; "l"; "m"; "o"; "p"; "r"; "r"; "s";
"simda"; "simdl"; "sr"; "wr"; "xr"]
end
let arm_opkind_mcts:arm_operand_kind_t mfts_int = new arm_opkind_mcts_t
let arm_opcode_cc_mfts: arm_opcode_cc_t mfts_int =
mk_mfts
"arm_opcode_cc_t"
[ (ACCEqual, "eq");
(ACCNotEqual, "ne");
(ACCCarrySet, "cs");
(ACCCarryClear, "cc");
(ACCNegative, "neg");
(ACCNonNegative, "nneg");
(ACCOverflow, "ov");
(ACCNoOverflow, "nov");
(ACCUnsignedHigher, "uh");
(ACCNotUnsignedHigher, "nuh");
(ACCSignedGE, "ge");
(ACCSignedLT, "lt");
(ACCSignedGT, "gt");
(ACCSignedLE, "le");
(ACCAlways, "a");
(ACCUnconditional,"unc")]
|
66c9fd88aff7bf0227a8cc6a77dee8a0303f4610a756e963db0c11672dfc811a | phadej/cabal-extras | NixSingle.hs | module CabalBundler.NixSingle (
generateDerivationNix,
) where
import Peura
import qualified Cabal.Index as I
import qualified Cabal.Plan as P
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Distribution.Package as C
import qualified Distribution.Types.UnqualComponentName as C
import qualified Topograph as TG
import CabalBundler.ExeOption
import CabalBundler.NixBase32
import CabalBundler.NixSingle.Input
import CabalBundler.NixSingle.Template
-------------------------------------------------------------------------------
-- generating output
-------------------------------------------------------------------------------
generateDerivationNix
:: TracerPeu r w
-> PackageName
-> ExeOption C.UnqualComponentName
-> P.PlanJson
-> Map PackageName I.PackageInfo
-> Peu r String
generateDerivationNix tracer packageName exeName' plan meta = do
exeName <- case exeName' of
ExeOptionPkg x -> return $ C.unUnqualComponentName x
ExeOption x -> return $ C.unUnqualComponentName x
ExeOptionAll -> die tracer "--exe-all isn't supported for openbsd output"
let units :: Map P.UnitId P.Unit
units = P.pjUnits plan
let pkgs :: Map P.PkgId (Set P.UnitId)
pkgs = M.fromListWith S.union
[ (P.uPId unit, S.singleton (P.uId unit))
| unit <- M.elems units
]
pkgIds <- packageGranularity units pkgs
zhsdeps <- for (NE.sort pkgIds) $ \pkgId' -> do
let PackageIdentifier pn ver = toCabal pkgId'
pi <- strictLookup pn UnknownPackageName meta
ri <- strictLookup ver (UnknownPackageVersion pn) (I.piVersions pi)
return ZDep
{ zdepName = prettyShow pn
, zdepVersion = prettyShow ver
, zdepSha256 = encodeHash (I.riTarballHash ri)
, zdepRevision = case I.riRevision ri of
0 -> "{}"
r -> "{ rev = " ++ show r ++ "; sha256 = \"" ++ encodeHash (I.riCabalHash ri) ++ "\"; }"
}
return $ render ZZ
{ zDerivationName = exeName
, zComponentName = C.unPackageName packageName ++ ":exe:" ++ exeName
, zExecutableName = exeName
, zCdeps = ["zlib", "zlib.dev"]
, zHsdeps = zhsdeps
}
where
encodeHash = encodeBase32 . I.getSHA256
-------------------------------------------------------------------------------
-- Exceptions
-------------------------------------------------------------------------------
data MetadataException
= UnknownPackageName PackageName
| UnknownPackageVersion PackageName Version
deriving Show
instance Exception MetadataException
-------------------------------------------------------------------------------
-- package granularity
-------------------------------------------------------------------------------
packageGranularity
:: Map P.UnitId P.Unit
-> Map P.PkgId (Set P.UnitId)
-> Peu r (NonEmpty P.PkgId)
packageGranularity units pkgs = do
let am' :: Map P.PkgId (Set P.PkgId)
am' = planJsonPkgGraph units pkgs
nonLocal' :: P.PkgId -> Bool
nonLocal' pid
| Just uids <- M.lookup pid pkgs
= all (\uid -> fmap P.uType (M.lookup uid units) == Just P.UnitTypeGlobal) uids
| otherwise
= False
nonLocal :: P.PkgId -> Set P.PkgId -> Maybe (Set P.PkgId)
nonLocal pid vs
| nonLocal' pid
= Just (S.filter nonLocal' vs)
| otherwise
= Nothing
am :: Map P.PkgId (Set P.PkgId)
am = M.mapMaybeWithKey nonLocal am'
either (throwM . PackageLoop . fmap toCabal) id $ TG.runG am $ \g ->
case TG.gVertices g of
[] -> throwM EmptyGraph
x:xs -> return (TG.gFromVertex g x :| map (TG.gFromVertex g) xs)
data PlanConstructionException
= PackageLoop [PackageIdentifier]
| EmptyGraph
deriving Show
instance Exception PlanConstructionException
-------------------------------------------------------------------------------
-- Graph stuff
-------------------------------------------------------------------------------
planJsonPkgGraph
:: Map P.UnitId P.Unit
-> Map P.PkgId (Set P.UnitId)
-> Map P.PkgId (Set P.PkgId)
planJsonPkgGraph units = M.mapWithKey $ \pid uids ->
-- remove package from own depss (e.g. exe depending on lib)
S.delete pid $ S.fromList
[ P.uPId depUnit
| uid <- S.toList uids
, unit <- maybeToList (M.lookup uid units)
, ci <- M.elems (P.uComps unit)
, depUid <- S.toList (P.ciLibDeps ci)
, depUnit <- maybeToList (M.lookup depUid units)
]
-------------------------------------------------------------------------------
Utilities
-------------------------------------------------------------------------------
strictLookup :: (Exception e, Ord k) => k -> (k -> e) -> Map k v -> Peu r v
strictLookup k mkExc = maybe (throwM (mkExc k)) return . M.lookup k
| null | https://raw.githubusercontent.com/phadej/cabal-extras/0cb96d2cf6c390555937fbb57fbe42b299aeb596/cabal-bundler/src/CabalBundler/NixSingle.hs | haskell | -----------------------------------------------------------------------------
generating output
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Exceptions
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
package granularity
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Graph stuff
-----------------------------------------------------------------------------
remove package from own depss (e.g. exe depending on lib)
-----------------------------------------------------------------------------
----------------------------------------------------------------------------- | module CabalBundler.NixSingle (
generateDerivationNix,
) where
import Peura
import qualified Cabal.Index as I
import qualified Cabal.Plan as P
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Distribution.Package as C
import qualified Distribution.Types.UnqualComponentName as C
import qualified Topograph as TG
import CabalBundler.ExeOption
import CabalBundler.NixBase32
import CabalBundler.NixSingle.Input
import CabalBundler.NixSingle.Template
generateDerivationNix
:: TracerPeu r w
-> PackageName
-> ExeOption C.UnqualComponentName
-> P.PlanJson
-> Map PackageName I.PackageInfo
-> Peu r String
generateDerivationNix tracer packageName exeName' plan meta = do
exeName <- case exeName' of
ExeOptionPkg x -> return $ C.unUnqualComponentName x
ExeOption x -> return $ C.unUnqualComponentName x
ExeOptionAll -> die tracer "--exe-all isn't supported for openbsd output"
let units :: Map P.UnitId P.Unit
units = P.pjUnits plan
let pkgs :: Map P.PkgId (Set P.UnitId)
pkgs = M.fromListWith S.union
[ (P.uPId unit, S.singleton (P.uId unit))
| unit <- M.elems units
]
pkgIds <- packageGranularity units pkgs
zhsdeps <- for (NE.sort pkgIds) $ \pkgId' -> do
let PackageIdentifier pn ver = toCabal pkgId'
pi <- strictLookup pn UnknownPackageName meta
ri <- strictLookup ver (UnknownPackageVersion pn) (I.piVersions pi)
return ZDep
{ zdepName = prettyShow pn
, zdepVersion = prettyShow ver
, zdepSha256 = encodeHash (I.riTarballHash ri)
, zdepRevision = case I.riRevision ri of
0 -> "{}"
r -> "{ rev = " ++ show r ++ "; sha256 = \"" ++ encodeHash (I.riCabalHash ri) ++ "\"; }"
}
return $ render ZZ
{ zDerivationName = exeName
, zComponentName = C.unPackageName packageName ++ ":exe:" ++ exeName
, zExecutableName = exeName
, zCdeps = ["zlib", "zlib.dev"]
, zHsdeps = zhsdeps
}
where
encodeHash = encodeBase32 . I.getSHA256
data MetadataException
= UnknownPackageName PackageName
| UnknownPackageVersion PackageName Version
deriving Show
instance Exception MetadataException
packageGranularity
:: Map P.UnitId P.Unit
-> Map P.PkgId (Set P.UnitId)
-> Peu r (NonEmpty P.PkgId)
packageGranularity units pkgs = do
let am' :: Map P.PkgId (Set P.PkgId)
am' = planJsonPkgGraph units pkgs
nonLocal' :: P.PkgId -> Bool
nonLocal' pid
| Just uids <- M.lookup pid pkgs
= all (\uid -> fmap P.uType (M.lookup uid units) == Just P.UnitTypeGlobal) uids
| otherwise
= False
nonLocal :: P.PkgId -> Set P.PkgId -> Maybe (Set P.PkgId)
nonLocal pid vs
| nonLocal' pid
= Just (S.filter nonLocal' vs)
| otherwise
= Nothing
am :: Map P.PkgId (Set P.PkgId)
am = M.mapMaybeWithKey nonLocal am'
either (throwM . PackageLoop . fmap toCabal) id $ TG.runG am $ \g ->
case TG.gVertices g of
[] -> throwM EmptyGraph
x:xs -> return (TG.gFromVertex g x :| map (TG.gFromVertex g) xs)
data PlanConstructionException
= PackageLoop [PackageIdentifier]
| EmptyGraph
deriving Show
instance Exception PlanConstructionException
planJsonPkgGraph
:: Map P.UnitId P.Unit
-> Map P.PkgId (Set P.UnitId)
-> Map P.PkgId (Set P.PkgId)
planJsonPkgGraph units = M.mapWithKey $ \pid uids ->
S.delete pid $ S.fromList
[ P.uPId depUnit
| uid <- S.toList uids
, unit <- maybeToList (M.lookup uid units)
, ci <- M.elems (P.uComps unit)
, depUid <- S.toList (P.ciLibDeps ci)
, depUnit <- maybeToList (M.lookup depUid units)
]
Utilities
strictLookup :: (Exception e, Ord k) => k -> (k -> e) -> Map k v -> Peu r v
strictLookup k mkExc = maybe (throwM (mkExc k)) return . M.lookup k
|
00823ee467e68e1f0800e3f47f24bba8563918498e7f3b6c84a1b57641441492 | NetASM/NetASM-haskell | Run.hs | ---------------------------------------------------------------------------------
--
--
--
-- File:
-- TTLDecrement/Run.hs
--
-- Project:
: A Network Assembly for Orchestrating Programmable Network Devices
--
-- Author:
--
-- Copyright notice:
Copyright ( C ) 2014 Georgia Institute of Technology
Network Operations and Internet Security Lab
--
-- Licence:
This file is a part of the development base package .
--
-- This file is free code: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 2.1 as
published by the Free Software Foundation .
--
-- This package is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
You should have received a copy of the GNU Lesser General Public
License along with the source package . If not , see
-- /.
module Apps.TTLDecrement.Run where
import Utils.Map
import Core.Language
import Core.PacketParser
import Apps.TTLDecrement.Code
--------------------
-- TTL Decrement ---
--------------------
-- Test header (a.k.a packet) stream
h0 = genHdr([("ttl", 1)])
h1 = genHdr([("ttl", 2)])
-- Input sequence
is = [HDR(h0),
HDR(h1)]
-- Emulate the code
emulateEx :: [Hdr]
emulateEx = emulate([], is, c)
-- Profile the code
profileEx :: String
profileEx = profile([], is, c)
-- Main
main = do
putStrLn $ prettyPrint $ emulateEx
putStrLn profileEx
| null | https://raw.githubusercontent.com/NetASM/NetASM-haskell/08e102691e4f343148b6cc270d89bbf0b97cac96/Apps/TTLDecrement/Run.hs | haskell | -------------------------------------------------------------------------------
File:
TTLDecrement/Run.hs
Project:
Author:
Copyright notice:
Licence:
This file is free code: you can redistribute it and/or modify it under
This package is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
/.
------------------
TTL Decrement ---
------------------
Test header (a.k.a packet) stream
Input sequence
Emulate the code
Profile the code
Main | : A Network Assembly for Orchestrating Programmable Network Devices
Copyright ( C ) 2014 Georgia Institute of Technology
Network Operations and Internet Security Lab
This file is a part of the development base package .
the terms of the GNU Lesser General Public License version 2.1 as
published by the Free Software Foundation .
You should have received a copy of the GNU Lesser General Public
License along with the source package . If not , see
module Apps.TTLDecrement.Run where
import Utils.Map
import Core.Language
import Core.PacketParser
import Apps.TTLDecrement.Code
h0 = genHdr([("ttl", 1)])
h1 = genHdr([("ttl", 2)])
is = [HDR(h0),
HDR(h1)]
emulateEx :: [Hdr]
emulateEx = emulate([], is, c)
profileEx :: String
profileEx = profile([], is, c)
main = do
putStrLn $ prettyPrint $ emulateEx
putStrLn profileEx
|
918286de8f31ce497d17ef40ae2426504c69ce19b74e057154eace43d563069c | tek/ribosome | Error.hs | module Ribosome.Host.Error where
import Ribosome.Host.Data.BootError (BootError (BootError))
import Ribosome.Host.Data.RpcError (RpcError)
import Ribosome.Host.Effect.Rpc (Rpc)
|Run a ' Sem ' that uses ' Rpc ' and discard ' RpcError 's , interpreting ' Rpc ' to @'Rpc ' ' ! ! ' ' RpcError'@.
ignoreRpcError ::
Member (Rpc !! RpcError) r =>
Sem (Rpc : r) a ->
Sem r ()
ignoreRpcError =
resume_ . void
|Run a ' Sem ' that uses ' Rpc ' and catch ' RpcError 's with the supplied function , interpreting ' Rpc ' to @'Rpc ' ' ! ! '
-- 'RpcError'@.
onRpcError ::
Member (Rpc !! RpcError) r =>
(RpcError -> Sem r a) ->
Sem (Rpc : r) a ->
Sem r a
onRpcError =
resuming
|Resume an error by transforming it to @'Error ' ' BootError'@.
resumeBootError ::
∀ eff err r .
Show err =>
Members [eff !! err, Error BootError] r =>
InterpreterFor eff r
resumeBootError =
resumeHoistError @_ @eff (BootError . show @Text)
| null | https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/host/lib/Ribosome/Host/Error.hs | haskell | 'RpcError'@. | module Ribosome.Host.Error where
import Ribosome.Host.Data.BootError (BootError (BootError))
import Ribosome.Host.Data.RpcError (RpcError)
import Ribosome.Host.Effect.Rpc (Rpc)
|Run a ' Sem ' that uses ' Rpc ' and discard ' RpcError 's , interpreting ' Rpc ' to @'Rpc ' ' ! ! ' ' RpcError'@.
ignoreRpcError ::
Member (Rpc !! RpcError) r =>
Sem (Rpc : r) a ->
Sem r ()
ignoreRpcError =
resume_ . void
|Run a ' Sem ' that uses ' Rpc ' and catch ' RpcError 's with the supplied function , interpreting ' Rpc ' to @'Rpc ' ' ! ! '
onRpcError ::
Member (Rpc !! RpcError) r =>
(RpcError -> Sem r a) ->
Sem (Rpc : r) a ->
Sem r a
onRpcError =
resuming
|Resume an error by transforming it to @'Error ' ' BootError'@.
resumeBootError ::
∀ eff err r .
Show err =>
Members [eff !! err, Error BootError] r =>
InterpreterFor eff r
resumeBootError =
resumeHoistError @_ @eff (BootError . show @Text)
|
b271ef5f8b69525b67fb44c292791a817011c77b68bb52e6a8de2781d592d7dc | realworldocaml/book | coq_lib_name.ml | open! Import
(* This file is licensed under The MIT License *)
( c ) MINES ParisTech 2018 - 2019
(* (c) INRIA 2020 *)
Written by :
(* Coq Directory Path *)
type t = string list
let compare = List.compare ~compare:String.compare
let to_string x = String.concat ~sep:"." x
let to_dir x = String.concat ~sep:"/" x
let wrapper x = to_string x
let dir x = to_dir x
We should add some further validation to Coq library names ; the rules in Coq
itself have been tweaked due to Unicode , etc ... so this is not trivial
itself have been tweaked due to Unicode, etc... so this is not trivial *)
let decode : (Loc.t * t) Dune_lang.Decoder.t =
Dune_lang.Decoder.plain_string (fun ~loc s -> (loc, String.split ~on:'.' s))
let encode : t Dune_lang.Encoder.t =
fun lib -> Dune_lang.Encoder.string (to_string lib)
let pp x = Pp.text (to_string x)
let to_dyn = Dyn.(list string)
module Rep = struct
type nonrec t = t
let compare = List.compare ~compare:String.compare
let to_dyn = to_dyn
end
module Map = Map.Make (Rep)
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/coq_lib_name.ml | ocaml | This file is licensed under The MIT License
(c) INRIA 2020
Coq Directory Path | open! Import
( c ) MINES ParisTech 2018 - 2019
Written by :
type t = string list
let compare = List.compare ~compare:String.compare
let to_string x = String.concat ~sep:"." x
let to_dir x = String.concat ~sep:"/" x
let wrapper x = to_string x
let dir x = to_dir x
We should add some further validation to Coq library names ; the rules in Coq
itself have been tweaked due to Unicode , etc ... so this is not trivial
itself have been tweaked due to Unicode, etc... so this is not trivial *)
let decode : (Loc.t * t) Dune_lang.Decoder.t =
Dune_lang.Decoder.plain_string (fun ~loc s -> (loc, String.split ~on:'.' s))
let encode : t Dune_lang.Encoder.t =
fun lib -> Dune_lang.Encoder.string (to_string lib)
let pp x = Pp.text (to_string x)
let to_dyn = Dyn.(list string)
module Rep = struct
type nonrec t = t
let compare = List.compare ~compare:String.compare
let to_dyn = to_dyn
end
module Map = Map.Make (Rep)
|
fdad53af597a96317bfab5a1a8ef5737f44b6fa19e256312da4f1814507a73a1 | ucsd-progsys/mist | ticktock2.hs | tick and tock with session types in Mist
undefined as rforall a. a
undefined = 0
assert :: {v:Bool | v} -> Unit
assert = \tru -> Unit
-----------------------------------------------------------------------------
-- | The ST Monad -----------------------------------------------------------
-----------------------------------------------------------------------------
bind :: rforall a, b, p, q, r.
ST <p >q >a ->
(x:a -> ST <q >r >b) ->
ST <p >r >b
bind = undefined
pure :: rforall a, p, q. x:a -> ST <p >q >a
pure = undefined
thenn :: rforall a, b, p, q, r.
ST <p >q >a
-> ST <q >r >b
-> ST <p >r >b
thenn = \f g -> bind f (\underscore -> g)
fmap :: rforall a, b, p, q.
(underscore:a -> b) ->
ST <p >q >a ->
ST <p >q >b
fmap = \f x -> bind x (\xx -> pure (f xx))
-----------------------------------------------------------------------------
-- | Primitive Connection Interface
-----------------------------------------------------------------------------
new as forall a. init:(Map <Int >Int) ~>
underscore:Int ->
(exists channel:Int.
ST <{v:Map <Int >Int | v = init}
>{v:Map <Int >Int | v = init}
>{v:Int | v = channel})
new = undefined
read as hg:(Map <Int >Int) ~> p:Int -> ST <{h:Map <Int >Int | h == hg} >{h:Map <Int >Int | h == hg} >{v:Int| v == select hg p}
read = undefined
write as h:(Map <Int >Int) ~> p:Int -> v:Int -> ST <{hg:Map <Int >Int | h == hg} >{hg:Map <Int >Int | store h p v == hg} >Unit
write = undefined
-----------------------------------------------------------------------------
-- | State Space
-----------------------------------------------------------------------------
ticked as Int
ticked = 0
tocked as Int
tocked = 0
-----------------------------------------------------------------------------
-- | Sessions
-----------------------------------------------------------------------------
channelStart :: {v:Int| v == tocked}
channelStart = tocked
startChannel :: init:(Map <Int >Int) ~>
underscore:Int ->
(exists channel:Int.
ST <{v:Map <Int >Int | v == init}
>{v:Map <Int >Int | v == store init channel channelStart}
>{v:Int | v == channel})
startChannel = \underscore ->
bind (new 0) (\v -> (thenn (write v channelStart) (pure v)))
-----------------------------------------------------------------------------
-- | Typed Session Wrappers
-----------------------------------------------------------------------------
tick ::
m : (Map <Int >Int) ~>
channel : {v: Int | select m v == tocked} ->
(ST <{v:Map <Int >Int | v == m}
>{v:Map <Int >Int | v = store m channel ticked}
>{v:Int | v = channel})
tick = \c -> thenn (write c tocked) (pure c)
tock ::
m : (Map <Int >Int) ~>
channel : {v: Int | select m v == ticked} ->
(ST <{v:Map <Int >Int | v == m}
>{v:Map <Int >Int | v = store m channel tocked}
>{v:Int | v = channel})
tock = \c -> thenn (write c ticked) (pure c)
-----------------------------------------------------------------------------
-- pos
main :: empty:(Map <Int >Int) ~> ST <{v:Map <Int >Int| v == empty} >(Map <Int >Int) >Int
main = bind (startChannel 0) (\c ->
bind (tick c) (\c ->
tock c))
-- neg
main = withChannel ( \c - > bind c ( \c - > tick c ( \c - > bind c ( \c - > tock c ( \c - > c ) ) ) ) )
| null | https://raw.githubusercontent.com/ucsd-progsys/mist/0a9345e73dc53ff8e8adb8bed78d0e3e0cdc6af0/tests/Tests/Integration/pos/ticktock2.hs | haskell | ---------------------------------------------------------------------------
| The ST Monad -----------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
| Primitive Connection Interface
---------------------------------------------------------------------------
---------------------------------------------------------------------------
| State Space
---------------------------------------------------------------------------
---------------------------------------------------------------------------
| Sessions
---------------------------------------------------------------------------
---------------------------------------------------------------------------
| Typed Session Wrappers
---------------------------------------------------------------------------
---------------------------------------------------------------------------
pos
neg | tick and tock with session types in Mist
undefined as rforall a. a
undefined = 0
assert :: {v:Bool | v} -> Unit
assert = \tru -> Unit
bind :: rforall a, b, p, q, r.
ST <p >q >a ->
(x:a -> ST <q >r >b) ->
ST <p >r >b
bind = undefined
pure :: rforall a, p, q. x:a -> ST <p >q >a
pure = undefined
thenn :: rforall a, b, p, q, r.
ST <p >q >a
-> ST <q >r >b
-> ST <p >r >b
thenn = \f g -> bind f (\underscore -> g)
fmap :: rforall a, b, p, q.
(underscore:a -> b) ->
ST <p >q >a ->
ST <p >q >b
fmap = \f x -> bind x (\xx -> pure (f xx))
new as forall a. init:(Map <Int >Int) ~>
underscore:Int ->
(exists channel:Int.
ST <{v:Map <Int >Int | v = init}
>{v:Map <Int >Int | v = init}
>{v:Int | v = channel})
new = undefined
read as hg:(Map <Int >Int) ~> p:Int -> ST <{h:Map <Int >Int | h == hg} >{h:Map <Int >Int | h == hg} >{v:Int| v == select hg p}
read = undefined
write as h:(Map <Int >Int) ~> p:Int -> v:Int -> ST <{hg:Map <Int >Int | h == hg} >{hg:Map <Int >Int | store h p v == hg} >Unit
write = undefined
ticked as Int
ticked = 0
tocked as Int
tocked = 0
channelStart :: {v:Int| v == tocked}
channelStart = tocked
startChannel :: init:(Map <Int >Int) ~>
underscore:Int ->
(exists channel:Int.
ST <{v:Map <Int >Int | v == init}
>{v:Map <Int >Int | v == store init channel channelStart}
>{v:Int | v == channel})
startChannel = \underscore ->
bind (new 0) (\v -> (thenn (write v channelStart) (pure v)))
tick ::
m : (Map <Int >Int) ~>
channel : {v: Int | select m v == tocked} ->
(ST <{v:Map <Int >Int | v == m}
>{v:Map <Int >Int | v = store m channel ticked}
>{v:Int | v = channel})
tick = \c -> thenn (write c tocked) (pure c)
tock ::
m : (Map <Int >Int) ~>
channel : {v: Int | select m v == ticked} ->
(ST <{v:Map <Int >Int | v == m}
>{v:Map <Int >Int | v = store m channel tocked}
>{v:Int | v = channel})
tock = \c -> thenn (write c ticked) (pure c)
main :: empty:(Map <Int >Int) ~> ST <{v:Map <Int >Int| v == empty} >(Map <Int >Int) >Int
main = bind (startChannel 0) (\c ->
bind (tick c) (\c ->
tock c))
main = withChannel ( \c - > bind c ( \c - > tick c ( \c - > bind c ( \c - > tock c ( \c - > c ) ) ) ) )
|
f7cb6fcdbe9a645cb1bc9b5af52fc351e19540f5cc10083a6a82202b0edffebb | chetmurthy/ensemble | route.ml | (**************************************************************)
Author : , 12/95
(**************************************************************)
open Trans
open Buf
open Util
(**************************************************************)
let name = Trace.file "ROUTE"
let failwith = Trace.make_failwith name
(**************************************************************)
let drop = Trace.log "ROUTED"
let info = Trace.log "ROUTEI"
(**************************************************************)
type pre_processor =
| Unsigned of (rank -> Obj.t option -> seqno -> Iovecl.t -> unit)
| Signed of (bool -> rank -> Obj.t option -> seqno -> Iovecl.t -> unit)
(**************************************************************)
type id =
| UnsignedId
| SignedId
(**************************************************************)
(* [merge] is the type of a combined receive function that is
* called once on behalf of a set of stacks that all need to
* receive a packet.
*
* [data] is the actual array of stack receive functions.
*
* [key] contains an extra integer to improve the hash function.
*)
type key = Conn.id * Conn.key * int
type merge = Buf.t -> Buf.ofs -> Buf.len -> Iovecl.t -> unit
type data = Conn.id * Buf.t * Security.key * pre_processor *
((Conn.id * Buf.t * Security.key * pre_processor) Arrayf.t ->
merge Arrayf.t)
type handlers = (key,data,merge) Handler.t
(* The type of a packet sending function. It so happens that
* the type of sending and receiving functions is nearly same.
*)
type xmitf = Buf.t -> Buf.ofs -> Buf.len -> Iovecl.t -> unit
(* Type of routers.
*)
type 'xf t = {
debug : debug ;
secure : bool ;
proc_hdlr : ((bool -> 'xf) -> pre_processor) ;
pack_of_conn : (Conn.id -> Buf.t) ;
merge : ((Conn.id * digest * Security.key * pre_processor) Arrayf.t ->
merge Arrayf.t) ;
blast : (xmitf -> Security.key -> digest -> Conn.id -> 'xf)
}
(**************************************************************)
let id_of_pre_processor = function
| Unsigned _ -> UnsignedId
| Signed _ -> SignedId
(**************************************************************)
let create debug secure proc_hdlr pack_of_conn merge blast = {
debug = debug ;
secure = secure ;
proc_hdlr = proc_hdlr ;
pack_of_conn = pack_of_conn ;
merge = merge ;
blast = blast
}
let debug r = r.debug
let secure r = r.secure
let hash_help p =
Hashtbl.hash_param 100 1000 p
let install r handlers ck all_recv key handler =
List.iter (fun (conn,kind) ->
let pack = r.pack_of_conn conn in
let pack0 = Buf.int16_of_substring pack (Buf.length pack -|| len4) in
info (fun () -> sprintf "Install: pack0=%d conn=%s"
pack0 (Conn.string_of_id conn)) ;
We put in an extra integer to make the hashing less
* likely to result in collisions . Note that this
* integer has to go last in order to be effective
* ( see ocaml / byterun / ) . .
* likely to result in collisions. Note that this
* integer has to go last in order to be effective
* (see ocaml/byterun/hash.c). Yuck.
*)
let hash_help = hash_help (conn,ck) in
let hdlr = r.proc_hdlr (handler kind) in
Handler.add handlers pack0 (conn,ck,hash_help) (conn,pack,key,hdlr,r.merge)
) all_recv
; " ltimes=%s\n " ( string_of_int_list ( Sort.list ( > =) ( ( List.map ( fun ( ( c , _ , _ ) , _ ) - > Conn.ltime c ) ( Handler.to_list handlers ) ) ) ) )
let remove r handlers ck all_recv =
List.iter (fun (conn,_) ->
let pack = r.pack_of_conn conn in
let pack0 = Buf.int16_of_substring pack (Buf.length pack -|| len4) in
let hash_help = hash_help (conn,ck) in
Handler.remove handlers pack0 (conn,ck,hash_help)
) all_recv
let blast r xmits key conn =
let pack = r.pack_of_conn conn in
info ( fun ( ) - > sprintf " blast pack=%s conn=%s "
( Util.hex_of_string ( Buf.string_of pack ) )
( Conn.string_of_id conn ) ) ;
(Util.hex_of_string (Buf.string_of pack))
(Conn.string_of_id conn)) ;*)
r.blast xmits key pack conn
(**************************************************************)
(* Security stuff.
*)
let secure_ref = ref false
let insecure_warned = ref false
let set_secure () =
eprintf "ROUTE:security enabled\n" ;
secure_ref := true
let security_check router =
(* Check for security problems.
*)
if !secure_ref && not router.secure then (
eprintf "ROUTE:enabling transport with insecure router (%s)\n" router.debug ;
eprintf " -secure flag is set, exiting\n" ;
exit 1
)
(* ;
if router.secure & (not !secure) & (not !insecure_warned) then (
insecure_warned := true ;
eprintf "ROUTE:warning:enabling secure transport but -secure flag not set\n" ;
eprintf " (an insecure transport may be enabled)\n"
)
*)
(**************************************************************)
This function takes an array of pairs and returns an
* array of pairs , where the fst 's are unique , and snd'd are
* grouped as the snd 's of the return value . [ group
* [ |(1,2);(3,4);(1,5)| ] ] evaluates to
* [ |(1,[|2;5|]);(3,[|4|])| ] , where ( 1,2 ) and ( 1,5 ) are
* merged into a single entry in the return value .
* array of pairs, where the fst's are unique, and snd'd are
* grouped as the snd's of the return value. [group
* [|(1,2);(3,4);(1,5)|]] evaluates to
* [|(1,[|2;5|]);(3,[|4|])|], where (1,2) and (1,5) are
* merged into a single entry in the return value.
*)
let group_cmp i j = compare (fst i) (fst j)
let group a =
let len = Arrayf.length a in
match len with
(* Handle simple cases quickly.
*)
| 0 -> Arrayf.empty
| 1 ->
let a = Arrayf.get a 0 in
Arrayf.singleton ((fst a),(Arrayf.singleton (snd a)))
| _ ->
(* General case.
*)
(* Sort by the fst of the pairs in the array.
*)
let a = Arrayf.sort group_cmp a in
Initialize result state .
*)
let key = ref (fst (Arrayf.get a 0)) in
let b = Arraye.create len (!key,Arrayf.empty) in
let lasta = ref 0 in
let lastb = ref 0 in
(* Collect items with equivalent fsts into
* lists.
*)
for i = 1 to len do
if i = len || fst (Arrayf.get a i) <> !key then (
let sub = Arrayf.sub a !lasta (i - !lasta) in
let sub = Arrayf.map snd sub in
Arraye.set b !lastb (!key,sub) ;
incr lastb ;
lasta := i ;
if i < len then (
key := fst (Arrayf.get a i)
)
) ;
done ;
(* Clean up the result state.
*)
let b = Arraye.sub b 0 !lastb in
let b = Arrayf.of_arraye b in
b
(**************************************************************)
(* Test code for 'group'
*)
let _ = Trace.test_declare "group" (fun () ->
let group_simple a =
let len = Arrayf.length a in
if len = 0 then Arrayf.empty else (
(* Sort by the fst of the pairs in the array.
*)
let a = Arrayf.sort group_cmp a in
Initialize result state .
*)
let k0,d0 = Arrayf.get a 0 in
let k = Arraye.create len k0 in
let d = Arraye.create len [] in
let j = ref 0 in
Arraye.set d 0 [d0] ;
(* Collect items with equivalent fsts into
* lists.
*)
for i = 1 to pred len do
if fst (Arrayf.get a i) <> Arraye.get k !j then (
incr j ;
assert (!j < len) ;
Arraye.set k !j (fst (Arrayf.get a i))
) ;
Arraye.set d !j (snd (Arrayf.get a i) :: (Arraye.get d !j))
done ;
(* Clean up the result state.
*)
incr j ;
let d = Arraye.sub d 0 !j in
let k = Arraye.sub k 0 !j in
let d = Arraye.map Arrayf.of_list d in
let d = Arrayf.of_arraye d in
let k = Arrayf.of_arraye k in
Arrayf.combine k d
)
in
let expand a =
let a = Arrayf.map (fun (i,b) ->
Arrayf.map (fun j -> (i,j)) b
) a in
Arrayf.flatten a
in
for c = 1 to 100000 do
if (c mod 1000) = 0 then
eprintf "test:%d\n" c ;
let a = Arrayf.init (Random.int 50) (fun _ ->
(Random.int 5, Random.int 15))
in
let b = group_simple a in
let c = group a in
let a = Arrayf.sort compare a in
let b = Arrayf.map (fun (i,a) -> (i,(Arrayf.sort compare a))) b in
let c = Arrayf.map (fun (i,a) -> (i,(Arrayf.sort compare a))) c in
let d = Arrayf.sort compare (expand c) in
if b <> c || a <> d then (
eprintf "inp=%s\n" ((Arrayf.to_string (string_of_pair string_of_int string_of_int)) a) ;
eprintf "old=%s\n" ((Arrayf.to_string (string_of_pair string_of_int Arrayf.int_to_string)) b) ;
eprintf "new=%s\n" ((Arrayf.to_string (string_of_pair string_of_int Arrayf.int_to_string)) c) ;
assert (b = c) ;
) ;
done
)
(**************************************************************)
let no_handler () = "no upcalls for message"
let empty1 _ _ = drop no_handler
let empty2 _ _ = drop no_handler
let empty3 _ _ _ = drop no_handler
let empty4 _ _ _ _ = drop no_handler
(**************************************************************)
(* The new support stuff.
*
* The point is to increment the ref-count for each xmit call
* on an iovec.
*)
let merge1 a = ident (fun a1 -> Arrayf.iter (fun f -> f a1) a)
let merge2 a =
match (Arrayf.to_array a) with
| [||] -> empty2
| [|f1|] -> f1
| [|f1;f2|] ->
fun a1 a2 ->
f1 a1 a2 ; f2 a1 a2
| _ ->
let n = pred (Arrayf.length a) in
fun a1 a2 ->
for i = 0 to n do
(Arrayf.get a i) a1 a2
done
let merge3 a =
match (Arrayf.to_array a) with
| [||] -> empty3
| [|f1|] -> f1
| [|f1;f2|] ->
fun a1 a2 a3 ->
f1 a1 a2 a3 ; f2 a1 a2 a3
| _ ->
let n = pred (Arrayf.length a) in
fun a1 a2 a3 ->
for i = 0 to n do
(Arrayf.get a i) a1 a2 a3
done
let merge4 a = ident (fun a1 a2 a3 a4 -> Arrayf.iter (fun f -> f a1 a2 a3 a4) a)
(**************************************************************)
let empty3rc r o l = drop no_handler ; Iovecl.free r
let merge3rc a =
match Arrayf.to_array a with
| [||] -> empty3rc
| [|f1|] -> f1
| [|f1;f2|] ->
fun r o l ->
f1 (Iovecl.copy r) o l ; f2 r o l
| _ ->
let n = pred (Arrayf.length a) in
fun r o l ->
for i = 1 to n do
(Arrayf.get a i) (Iovecl.copy r) o l
done ;
(Arrayf.get a 0) r o l
(**************************************************************)
Handle the reference counting . The idea here is that in
* the code we allocate an iovec array with one reference .
* Here we want to increment that reference count if there
* is more than 1 destination and decrement it if there are
* none . Note that we do the operations that increment the
* reference counts first so that the count does not get
* zeroed on us .
* the code we allocate an iovec array with one reference.
* Here we want to increment that reference count if there
* is more than 1 destination and decrement it if there are
* none. Note that we do the operations that increment the
* reference counts first so that the count does not get
* zeroed on us.
*)
let empty1iov argv = drop no_handler ; Iovecl.free argv
let merge1iov a =
match Arrayf.to_array a with
| [||] -> empty1iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun argv ->
f1 (Iovecl.copy argv) ; f2 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun argv ->
for i = 1 to pred_len do
(Arrayf.get a i) (Iovecl.copy argv)
done ;
(Arrayf.get a 0) argv
let empty2iov arg1 argv = drop no_handler ; Iovecl.free argv
let merge2iov a =
match Arrayf.to_array a with
| [||] -> empty2iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun arg1 argv ->
f1 arg1 (Iovecl.copy argv) ; f2 arg1 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 argv
let empty2iovr argv arg2 = drop no_handler ; Iovecl.free argv
let merge2iovr a =
match Arrayf.to_array a with
| [||] -> empty2iovr
| [|f1|] -> f1
| [|f1;f2|] ->
fun argv arg2 ->
f1 (Iovecl.copy argv) arg2 ; f2 argv arg2
| _ ->
let pred_len = pred (Arrayf.length a) in
fun argv arg2 ->
for i = 1 to pred_len do
(Arrayf.get a i) (Iovecl.copy argv) arg2
done ;
(Arrayf.get a 0) argv arg2
let empty3iov arg1 arg2 argv = drop no_handler ; Iovecl.free argv
let merge3iov a =
match Arrayf.to_array a with
| [||] -> empty3iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun arg1 arg2 argv ->
f1 arg1 arg2 (Iovecl.copy argv) ; f2 arg1 arg2 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 arg2 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 arg2 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 arg2 argv
let empty4iov arg1 arg2 arg3 argv = drop no_handler ; Iovecl.free argv
let merge4iov a =
match Arrayf.to_array a with
| [||] -> empty4iov
| [|f1|] -> f1
| [|f1;f2|] -> fun arg1 arg2 arg3 argv ->
f1 arg1 arg2 arg3 (Iovecl.copy argv) ; f2 arg1 arg2 arg3 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 arg2 arg3 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 arg2 arg3 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 arg2 arg3 argv
let pack_of_conn = Conn.hash_of_id
(**************************************************************)
(*type merge = (Conn.id * Security.key * Conn.kind * rank * message) array
-> (Iovec.t -> unit)*)
let merge info =
let info = Arrayf.map (fun (c,p,k,h,m) ->
((id_of_pre_processor h),(m,(c,p,k,h)))) info in
let info = group info in
let info =
Arrayf.map (fun (_,i) ->
assert (Arrayf.length i > 0) ;
(fst (Arrayf.get i 0)) (Arrayf.map snd i)
) info
in
let info = Arrayf.flatten info in
merge4iov info
let delay f =
let delayed a b c d =
(f ()) a b c d
in
delayed
let handlers () =
let table = Handler.create merge delay in
(*
Trace.install_root (fun () -> [
sprintf "ROUTE:#enabled=%d" (Handler.size table) ;
sprintf "ROUTE:table:%s" (Handler.info table)
]) ;
*)
table
let deliver handlers buf ofs len iovl =
Buf.int16_of_substring pack ( Buf.length pack -|| len4 ) in
(*raise (Invalid_argument "deliver");*)
let pack0 = int16_of_substring buf (ofs +|| md5len -|| len4) in
if Iovecl.len iovl >|| len0 then
info (fun () -> sprintf "deliver pack0=%d pack=%s (mo=%d iovl=%d)"
pack0
(Util.hex_of_string (Buf.string_of (Buf.sub buf ofs len16)))
(int_of_len len) (int_of_len (Iovecl.len iovl))
);
let handler = Handler.find handlers pack0 in
handler buf ofs len iovl
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/route/route.ml | ocaml | ************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
[merge] is the type of a combined receive function that is
* called once on behalf of a set of stacks that all need to
* receive a packet.
*
* [data] is the actual array of stack receive functions.
*
* [key] contains an extra integer to improve the hash function.
The type of a packet sending function. It so happens that
* the type of sending and receiving functions is nearly same.
Type of routers.
************************************************************
************************************************************
************************************************************
Security stuff.
Check for security problems.
;
if router.secure & (not !secure) & (not !insecure_warned) then (
insecure_warned := true ;
eprintf "ROUTE:warning:enabling secure transport but -secure flag not set\n" ;
eprintf " (an insecure transport may be enabled)\n"
)
************************************************************
Handle simple cases quickly.
General case.
Sort by the fst of the pairs in the array.
Collect items with equivalent fsts into
* lists.
Clean up the result state.
************************************************************
Test code for 'group'
Sort by the fst of the pairs in the array.
Collect items with equivalent fsts into
* lists.
Clean up the result state.
************************************************************
************************************************************
The new support stuff.
*
* The point is to increment the ref-count for each xmit call
* on an iovec.
************************************************************
************************************************************
************************************************************
type merge = (Conn.id * Security.key * Conn.kind * rank * message) array
-> (Iovec.t -> unit)
Trace.install_root (fun () -> [
sprintf "ROUTE:#enabled=%d" (Handler.size table) ;
sprintf "ROUTE:table:%s" (Handler.info table)
]) ;
raise (Invalid_argument "deliver");
************************************************************ |
Author : , 12/95
open Trans
open Buf
open Util
let name = Trace.file "ROUTE"
let failwith = Trace.make_failwith name
let drop = Trace.log "ROUTED"
let info = Trace.log "ROUTEI"
type pre_processor =
| Unsigned of (rank -> Obj.t option -> seqno -> Iovecl.t -> unit)
| Signed of (bool -> rank -> Obj.t option -> seqno -> Iovecl.t -> unit)
type id =
| UnsignedId
| SignedId
type key = Conn.id * Conn.key * int
type merge = Buf.t -> Buf.ofs -> Buf.len -> Iovecl.t -> unit
type data = Conn.id * Buf.t * Security.key * pre_processor *
((Conn.id * Buf.t * Security.key * pre_processor) Arrayf.t ->
merge Arrayf.t)
type handlers = (key,data,merge) Handler.t
type xmitf = Buf.t -> Buf.ofs -> Buf.len -> Iovecl.t -> unit
type 'xf t = {
debug : debug ;
secure : bool ;
proc_hdlr : ((bool -> 'xf) -> pre_processor) ;
pack_of_conn : (Conn.id -> Buf.t) ;
merge : ((Conn.id * digest * Security.key * pre_processor) Arrayf.t ->
merge Arrayf.t) ;
blast : (xmitf -> Security.key -> digest -> Conn.id -> 'xf)
}
let id_of_pre_processor = function
| Unsigned _ -> UnsignedId
| Signed _ -> SignedId
let create debug secure proc_hdlr pack_of_conn merge blast = {
debug = debug ;
secure = secure ;
proc_hdlr = proc_hdlr ;
pack_of_conn = pack_of_conn ;
merge = merge ;
blast = blast
}
let debug r = r.debug
let secure r = r.secure
let hash_help p =
Hashtbl.hash_param 100 1000 p
let install r handlers ck all_recv key handler =
List.iter (fun (conn,kind) ->
let pack = r.pack_of_conn conn in
let pack0 = Buf.int16_of_substring pack (Buf.length pack -|| len4) in
info (fun () -> sprintf "Install: pack0=%d conn=%s"
pack0 (Conn.string_of_id conn)) ;
We put in an extra integer to make the hashing less
* likely to result in collisions . Note that this
* integer has to go last in order to be effective
* ( see ocaml / byterun / ) . .
* likely to result in collisions. Note that this
* integer has to go last in order to be effective
* (see ocaml/byterun/hash.c). Yuck.
*)
let hash_help = hash_help (conn,ck) in
let hdlr = r.proc_hdlr (handler kind) in
Handler.add handlers pack0 (conn,ck,hash_help) (conn,pack,key,hdlr,r.merge)
) all_recv
; " ltimes=%s\n " ( string_of_int_list ( Sort.list ( > =) ( ( List.map ( fun ( ( c , _ , _ ) , _ ) - > Conn.ltime c ) ( Handler.to_list handlers ) ) ) ) )
let remove r handlers ck all_recv =
List.iter (fun (conn,_) ->
let pack = r.pack_of_conn conn in
let pack0 = Buf.int16_of_substring pack (Buf.length pack -|| len4) in
let hash_help = hash_help (conn,ck) in
Handler.remove handlers pack0 (conn,ck,hash_help)
) all_recv
let blast r xmits key conn =
let pack = r.pack_of_conn conn in
info ( fun ( ) - > sprintf " blast pack=%s conn=%s "
( Util.hex_of_string ( Buf.string_of pack ) )
( Conn.string_of_id conn ) ) ;
(Util.hex_of_string (Buf.string_of pack))
(Conn.string_of_id conn)) ;*)
r.blast xmits key pack conn
let secure_ref = ref false
let insecure_warned = ref false
let set_secure () =
eprintf "ROUTE:security enabled\n" ;
secure_ref := true
let security_check router =
if !secure_ref && not router.secure then (
eprintf "ROUTE:enabling transport with insecure router (%s)\n" router.debug ;
eprintf " -secure flag is set, exiting\n" ;
exit 1
)
This function takes an array of pairs and returns an
* array of pairs , where the fst 's are unique , and snd'd are
* grouped as the snd 's of the return value . [ group
* [ |(1,2);(3,4);(1,5)| ] ] evaluates to
* [ |(1,[|2;5|]);(3,[|4|])| ] , where ( 1,2 ) and ( 1,5 ) are
* merged into a single entry in the return value .
* array of pairs, where the fst's are unique, and snd'd are
* grouped as the snd's of the return value. [group
* [|(1,2);(3,4);(1,5)|]] evaluates to
* [|(1,[|2;5|]);(3,[|4|])|], where (1,2) and (1,5) are
* merged into a single entry in the return value.
*)
let group_cmp i j = compare (fst i) (fst j)
let group a =
let len = Arrayf.length a in
match len with
| 0 -> Arrayf.empty
| 1 ->
let a = Arrayf.get a 0 in
Arrayf.singleton ((fst a),(Arrayf.singleton (snd a)))
| _ ->
let a = Arrayf.sort group_cmp a in
Initialize result state .
*)
let key = ref (fst (Arrayf.get a 0)) in
let b = Arraye.create len (!key,Arrayf.empty) in
let lasta = ref 0 in
let lastb = ref 0 in
for i = 1 to len do
if i = len || fst (Arrayf.get a i) <> !key then (
let sub = Arrayf.sub a !lasta (i - !lasta) in
let sub = Arrayf.map snd sub in
Arraye.set b !lastb (!key,sub) ;
incr lastb ;
lasta := i ;
if i < len then (
key := fst (Arrayf.get a i)
)
) ;
done ;
let b = Arraye.sub b 0 !lastb in
let b = Arrayf.of_arraye b in
b
let _ = Trace.test_declare "group" (fun () ->
let group_simple a =
let len = Arrayf.length a in
if len = 0 then Arrayf.empty else (
let a = Arrayf.sort group_cmp a in
Initialize result state .
*)
let k0,d0 = Arrayf.get a 0 in
let k = Arraye.create len k0 in
let d = Arraye.create len [] in
let j = ref 0 in
Arraye.set d 0 [d0] ;
for i = 1 to pred len do
if fst (Arrayf.get a i) <> Arraye.get k !j then (
incr j ;
assert (!j < len) ;
Arraye.set k !j (fst (Arrayf.get a i))
) ;
Arraye.set d !j (snd (Arrayf.get a i) :: (Arraye.get d !j))
done ;
incr j ;
let d = Arraye.sub d 0 !j in
let k = Arraye.sub k 0 !j in
let d = Arraye.map Arrayf.of_list d in
let d = Arrayf.of_arraye d in
let k = Arrayf.of_arraye k in
Arrayf.combine k d
)
in
let expand a =
let a = Arrayf.map (fun (i,b) ->
Arrayf.map (fun j -> (i,j)) b
) a in
Arrayf.flatten a
in
for c = 1 to 100000 do
if (c mod 1000) = 0 then
eprintf "test:%d\n" c ;
let a = Arrayf.init (Random.int 50) (fun _ ->
(Random.int 5, Random.int 15))
in
let b = group_simple a in
let c = group a in
let a = Arrayf.sort compare a in
let b = Arrayf.map (fun (i,a) -> (i,(Arrayf.sort compare a))) b in
let c = Arrayf.map (fun (i,a) -> (i,(Arrayf.sort compare a))) c in
let d = Arrayf.sort compare (expand c) in
if b <> c || a <> d then (
eprintf "inp=%s\n" ((Arrayf.to_string (string_of_pair string_of_int string_of_int)) a) ;
eprintf "old=%s\n" ((Arrayf.to_string (string_of_pair string_of_int Arrayf.int_to_string)) b) ;
eprintf "new=%s\n" ((Arrayf.to_string (string_of_pair string_of_int Arrayf.int_to_string)) c) ;
assert (b = c) ;
) ;
done
)
let no_handler () = "no upcalls for message"
let empty1 _ _ = drop no_handler
let empty2 _ _ = drop no_handler
let empty3 _ _ _ = drop no_handler
let empty4 _ _ _ _ = drop no_handler
let merge1 a = ident (fun a1 -> Arrayf.iter (fun f -> f a1) a)
let merge2 a =
match (Arrayf.to_array a) with
| [||] -> empty2
| [|f1|] -> f1
| [|f1;f2|] ->
fun a1 a2 ->
f1 a1 a2 ; f2 a1 a2
| _ ->
let n = pred (Arrayf.length a) in
fun a1 a2 ->
for i = 0 to n do
(Arrayf.get a i) a1 a2
done
let merge3 a =
match (Arrayf.to_array a) with
| [||] -> empty3
| [|f1|] -> f1
| [|f1;f2|] ->
fun a1 a2 a3 ->
f1 a1 a2 a3 ; f2 a1 a2 a3
| _ ->
let n = pred (Arrayf.length a) in
fun a1 a2 a3 ->
for i = 0 to n do
(Arrayf.get a i) a1 a2 a3
done
let merge4 a = ident (fun a1 a2 a3 a4 -> Arrayf.iter (fun f -> f a1 a2 a3 a4) a)
let empty3rc r o l = drop no_handler ; Iovecl.free r
let merge3rc a =
match Arrayf.to_array a with
| [||] -> empty3rc
| [|f1|] -> f1
| [|f1;f2|] ->
fun r o l ->
f1 (Iovecl.copy r) o l ; f2 r o l
| _ ->
let n = pred (Arrayf.length a) in
fun r o l ->
for i = 1 to n do
(Arrayf.get a i) (Iovecl.copy r) o l
done ;
(Arrayf.get a 0) r o l
Handle the reference counting . The idea here is that in
* the code we allocate an iovec array with one reference .
* Here we want to increment that reference count if there
* is more than 1 destination and decrement it if there are
* none . Note that we do the operations that increment the
* reference counts first so that the count does not get
* zeroed on us .
* the code we allocate an iovec array with one reference.
* Here we want to increment that reference count if there
* is more than 1 destination and decrement it if there are
* none. Note that we do the operations that increment the
* reference counts first so that the count does not get
* zeroed on us.
*)
let empty1iov argv = drop no_handler ; Iovecl.free argv
let merge1iov a =
match Arrayf.to_array a with
| [||] -> empty1iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun argv ->
f1 (Iovecl.copy argv) ; f2 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun argv ->
for i = 1 to pred_len do
(Arrayf.get a i) (Iovecl.copy argv)
done ;
(Arrayf.get a 0) argv
let empty2iov arg1 argv = drop no_handler ; Iovecl.free argv
let merge2iov a =
match Arrayf.to_array a with
| [||] -> empty2iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun arg1 argv ->
f1 arg1 (Iovecl.copy argv) ; f2 arg1 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 argv
let empty2iovr argv arg2 = drop no_handler ; Iovecl.free argv
let merge2iovr a =
match Arrayf.to_array a with
| [||] -> empty2iovr
| [|f1|] -> f1
| [|f1;f2|] ->
fun argv arg2 ->
f1 (Iovecl.copy argv) arg2 ; f2 argv arg2
| _ ->
let pred_len = pred (Arrayf.length a) in
fun argv arg2 ->
for i = 1 to pred_len do
(Arrayf.get a i) (Iovecl.copy argv) arg2
done ;
(Arrayf.get a 0) argv arg2
let empty3iov arg1 arg2 argv = drop no_handler ; Iovecl.free argv
let merge3iov a =
match Arrayf.to_array a with
| [||] -> empty3iov
| [|f1|] -> f1
| [|f1;f2|] ->
fun arg1 arg2 argv ->
f1 arg1 arg2 (Iovecl.copy argv) ; f2 arg1 arg2 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 arg2 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 arg2 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 arg2 argv
let empty4iov arg1 arg2 arg3 argv = drop no_handler ; Iovecl.free argv
let merge4iov a =
match Arrayf.to_array a with
| [||] -> empty4iov
| [|f1|] -> f1
| [|f1;f2|] -> fun arg1 arg2 arg3 argv ->
f1 arg1 arg2 arg3 (Iovecl.copy argv) ; f2 arg1 arg2 arg3 argv
| _ ->
let pred_len = pred (Arrayf.length a) in
fun arg1 arg2 arg3 argv ->
for i = 1 to pred_len do
(Arrayf.get a i) arg1 arg2 arg3 (Iovecl.copy argv)
done ;
(Arrayf.get a 0) arg1 arg2 arg3 argv
let pack_of_conn = Conn.hash_of_id
let merge info =
let info = Arrayf.map (fun (c,p,k,h,m) ->
((id_of_pre_processor h),(m,(c,p,k,h)))) info in
let info = group info in
let info =
Arrayf.map (fun (_,i) ->
assert (Arrayf.length i > 0) ;
(fst (Arrayf.get i 0)) (Arrayf.map snd i)
) info
in
let info = Arrayf.flatten info in
merge4iov info
let delay f =
let delayed a b c d =
(f ()) a b c d
in
delayed
let handlers () =
let table = Handler.create merge delay in
table
let deliver handlers buf ofs len iovl =
Buf.int16_of_substring pack ( Buf.length pack -|| len4 ) in
let pack0 = int16_of_substring buf (ofs +|| md5len -|| len4) in
if Iovecl.len iovl >|| len0 then
info (fun () -> sprintf "deliver pack0=%d pack=%s (mo=%d iovl=%d)"
pack0
(Util.hex_of_string (Buf.string_of (Buf.sub buf ofs len16)))
(int_of_len len) (int_of_len (Iovecl.len iovl))
);
let handler = Handler.find handlers pack0 in
handler buf ofs len iovl
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.