_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 |
|---|---|---|---|---|---|---|---|---|
538d8610b71c07e62e94157944252e00d5f58f3c9a5093142e0b49c4f3f3d25a | rvantonder/CryptOSS | record.ml | open Core
type t =
{ date : Date.t
; cryptocurrency_name : string
; repo_name : string
; is_forked : string
; language : string
; last_updated : string
; commits_24h : int
; commits_7d : int
; changes_24h_loc_added : int
; changes_24h_loc_removed : int
; changes_7d_loc_added : int
; changes_7d_loc_removed : int
; contributors_7d : int
; contributors_all_time : int
; commits_1y : int
; changes_1y_loc_added : int
; changes_1y_loc_removed : int
; stars : int
; forks : int
; watchers : int
; symbol : string
; market_cap_rank : string
; price_usd : string
; market_cap_usd : string
}
let (!!) date =
let year = Date.year date in
let month = Date.month date |> Month.to_int in
let day = Date.day date in
Format.sprintf "%d-%02d-%02d" year month day
let to_int s =
try
Int.of_string s
with _ ->
-1
let create date cryptocurrency_name repo_name rest =
match rest with
(* with fin data *)
| is_forked :: language :: last_updated :: commits_24h :: commits_7d :: changes_24h_loc_added :: changes_24h_loc_removed :: changes_7d_loc_added :: changes_7d_loc_removed :: contributors_7d :: contributors_all_time :: commits_1y :: changes_1y_loc_added :: changes_1y_loc_removed :: stars :: forks :: watchers :: symbol :: market_cap_rank :: price_usd :: market_cap_usd :: [] ->
{ date
; cryptocurrency_name
; repo_name
; is_forked
; language
; last_updated
; commits_24h = to_int commits_24h
; commits_7d = to_int commits_7d
; changes_24h_loc_added = to_int changes_24h_loc_added
; changes_24h_loc_removed = to_int changes_24h_loc_removed
; changes_7d_loc_added = to_int changes_7d_loc_added
; changes_7d_loc_removed = to_int changes_7d_loc_removed
; contributors_7d = to_int contributors_7d
; contributors_all_time = to_int contributors_all_time
; commits_1y = to_int commits_1y
; changes_1y_loc_added = to_int changes_1y_loc_added
; changes_1y_loc_removed = to_int changes_1y_loc_removed
; stars = to_int stars
; forks = to_int forks
; watchers = to_int watchers
; symbol
; market_cap_rank
; price_usd
; market_cap_usd
}
|> Option.some
(* without fin data *)
| is_forked :: language :: last_updated :: commits_24h :: commits_7d :: changes_24h_loc_added :: changes_24h_loc_removed :: changes_7d_loc_added :: changes_7d_loc_removed :: contributors_7d :: contributors_all_time :: commits_1y :: changes_1y_loc_added :: changes_1y_loc_removed :: stars :: forks :: watchers :: [] ->
{ date
; cryptocurrency_name
; repo_name
; is_forked
; language
; last_updated
; commits_24h = to_int commits_24h
; commits_7d = to_int commits_7d
; changes_24h_loc_added = to_int changes_24h_loc_added
; changes_24h_loc_removed = to_int changes_24h_loc_removed
; changes_7d_loc_added = to_int changes_7d_loc_added
; changes_7d_loc_removed = to_int changes_7d_loc_removed
; contributors_7d = to_int contributors_7d
; contributors_all_time = to_int contributors_all_time
; commits_1y = to_int commits_1y
; changes_1y_loc_added = to_int changes_1y_loc_added
; changes_1y_loc_removed = to_int changes_1y_loc_removed
; stars = to_int stars
; forks = to_int forks
; watchers = to_int watchers
; symbol = "null"
; market_cap_rank = "null"
; price_usd = "null"
; market_cap_usd = "null"
}
|> fun record ->
Format.eprintf "No fin data For %s,%s@." !!date cryptocurrency_name;
Some record
| s ->
Format.eprintf "Short record: %d fields, expected 17 (without fin data) or 21 (with fin data).@." (List.length s);
Format.eprintf "For %s,%s,%s" !!date cryptocurrency_name repo_name;
None
let null ?ranks_data date cryptocurrency_name repo_name =
let symbol, market_cap_rank, price_usd, market_cap_usd =
match ranks_data with
| Some (a,b,c,d) -> a, b, c, d
| None -> "null", "null", "null", "null"
in
{ date
; cryptocurrency_name
; repo_name
; is_forked = "null"
; language = "null"
; last_updated = "null"
; commits_24h = -1
; commits_7d = -1
; changes_24h_loc_added = -1
; changes_24h_loc_removed = -1
; changes_7d_loc_added = -1
; changes_7d_loc_removed = -1
; contributors_7d = -1
; contributors_all_time = -1
; commits_1y = -1
; changes_1y_loc_added = -1
; changes_1y_loc_removed = -1
; stars = -1
; forks = -1
; watchers = -1
; symbol
; market_cap_rank
; price_usd
; market_cap_usd
}
let to_string
{ date : Date.t
; cryptocurrency_name : string
; repo_name : string
; is_forked : string
; language : string
; last_updated : string
; commits_24h : int
; commits_7d : int
; changes_24h_loc_added : int
; changes_24h_loc_removed : int
; changes_7d_loc_added : int
; changes_7d_loc_removed : int
; contributors_7d : int
; contributors_all_time : int
; commits_1y : int
; changes_1y_loc_added : int
; changes_1y_loc_removed : int
; stars : int
; forks : int
; watchers : int
; symbol : string
; market_cap_rank : string
; price_usd : string
; market_cap_usd : string
}
=
let (!) v = if v < 0 then "null" else Int.to_string v in
Format.sprintf "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"
!!date cryptocurrency_name repo_name is_forked language last_updated !commits_24h !commits_7d !changes_24h_loc_added !changes_24h_loc_removed !changes_7d_loc_added !changes_7d_loc_removed !contributors_7d !contributors_all_time !commits_1y !changes_1y_loc_added !changes_1y_loc_removed !stars !forks !watchers symbol market_cap_rank price_usd market_cap_usd
| null | https://raw.githubusercontent.com/rvantonder/CryptOSS/acd931433f70fd097930b2e62a294af6d31a2a77/xsanitizer/record.ml | ocaml | with fin data
without fin data | open Core
type t =
{ date : Date.t
; cryptocurrency_name : string
; repo_name : string
; is_forked : string
; language : string
; last_updated : string
; commits_24h : int
; commits_7d : int
; changes_24h_loc_added : int
; changes_24h_loc_removed : int
; changes_7d_loc_added : int
; changes_7d_loc_removed : int
; contributors_7d : int
; contributors_all_time : int
; commits_1y : int
; changes_1y_loc_added : int
; changes_1y_loc_removed : int
; stars : int
; forks : int
; watchers : int
; symbol : string
; market_cap_rank : string
; price_usd : string
; market_cap_usd : string
}
let (!!) date =
let year = Date.year date in
let month = Date.month date |> Month.to_int in
let day = Date.day date in
Format.sprintf "%d-%02d-%02d" year month day
let to_int s =
try
Int.of_string s
with _ ->
-1
let create date cryptocurrency_name repo_name rest =
match rest with
| is_forked :: language :: last_updated :: commits_24h :: commits_7d :: changes_24h_loc_added :: changes_24h_loc_removed :: changes_7d_loc_added :: changes_7d_loc_removed :: contributors_7d :: contributors_all_time :: commits_1y :: changes_1y_loc_added :: changes_1y_loc_removed :: stars :: forks :: watchers :: symbol :: market_cap_rank :: price_usd :: market_cap_usd :: [] ->
{ date
; cryptocurrency_name
; repo_name
; is_forked
; language
; last_updated
; commits_24h = to_int commits_24h
; commits_7d = to_int commits_7d
; changes_24h_loc_added = to_int changes_24h_loc_added
; changes_24h_loc_removed = to_int changes_24h_loc_removed
; changes_7d_loc_added = to_int changes_7d_loc_added
; changes_7d_loc_removed = to_int changes_7d_loc_removed
; contributors_7d = to_int contributors_7d
; contributors_all_time = to_int contributors_all_time
; commits_1y = to_int commits_1y
; changes_1y_loc_added = to_int changes_1y_loc_added
; changes_1y_loc_removed = to_int changes_1y_loc_removed
; stars = to_int stars
; forks = to_int forks
; watchers = to_int watchers
; symbol
; market_cap_rank
; price_usd
; market_cap_usd
}
|> Option.some
| is_forked :: language :: last_updated :: commits_24h :: commits_7d :: changes_24h_loc_added :: changes_24h_loc_removed :: changes_7d_loc_added :: changes_7d_loc_removed :: contributors_7d :: contributors_all_time :: commits_1y :: changes_1y_loc_added :: changes_1y_loc_removed :: stars :: forks :: watchers :: [] ->
{ date
; cryptocurrency_name
; repo_name
; is_forked
; language
; last_updated
; commits_24h = to_int commits_24h
; commits_7d = to_int commits_7d
; changes_24h_loc_added = to_int changes_24h_loc_added
; changes_24h_loc_removed = to_int changes_24h_loc_removed
; changes_7d_loc_added = to_int changes_7d_loc_added
; changes_7d_loc_removed = to_int changes_7d_loc_removed
; contributors_7d = to_int contributors_7d
; contributors_all_time = to_int contributors_all_time
; commits_1y = to_int commits_1y
; changes_1y_loc_added = to_int changes_1y_loc_added
; changes_1y_loc_removed = to_int changes_1y_loc_removed
; stars = to_int stars
; forks = to_int forks
; watchers = to_int watchers
; symbol = "null"
; market_cap_rank = "null"
; price_usd = "null"
; market_cap_usd = "null"
}
|> fun record ->
Format.eprintf "No fin data For %s,%s@." !!date cryptocurrency_name;
Some record
| s ->
Format.eprintf "Short record: %d fields, expected 17 (without fin data) or 21 (with fin data).@." (List.length s);
Format.eprintf "For %s,%s,%s" !!date cryptocurrency_name repo_name;
None
let null ?ranks_data date cryptocurrency_name repo_name =
let symbol, market_cap_rank, price_usd, market_cap_usd =
match ranks_data with
| Some (a,b,c,d) -> a, b, c, d
| None -> "null", "null", "null", "null"
in
{ date
; cryptocurrency_name
; repo_name
; is_forked = "null"
; language = "null"
; last_updated = "null"
; commits_24h = -1
; commits_7d = -1
; changes_24h_loc_added = -1
; changes_24h_loc_removed = -1
; changes_7d_loc_added = -1
; changes_7d_loc_removed = -1
; contributors_7d = -1
; contributors_all_time = -1
; commits_1y = -1
; changes_1y_loc_added = -1
; changes_1y_loc_removed = -1
; stars = -1
; forks = -1
; watchers = -1
; symbol
; market_cap_rank
; price_usd
; market_cap_usd
}
let to_string
{ date : Date.t
; cryptocurrency_name : string
; repo_name : string
; is_forked : string
; language : string
; last_updated : string
; commits_24h : int
; commits_7d : int
; changes_24h_loc_added : int
; changes_24h_loc_removed : int
; changes_7d_loc_added : int
; changes_7d_loc_removed : int
; contributors_7d : int
; contributors_all_time : int
; commits_1y : int
; changes_1y_loc_added : int
; changes_1y_loc_removed : int
; stars : int
; forks : int
; watchers : int
; symbol : string
; market_cap_rank : string
; price_usd : string
; market_cap_usd : string
}
=
let (!) v = if v < 0 then "null" else Int.to_string v in
Format.sprintf "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s"
!!date cryptocurrency_name repo_name is_forked language last_updated !commits_24h !commits_7d !changes_24h_loc_added !changes_24h_loc_removed !changes_7d_loc_added !changes_7d_loc_removed !contributors_7d !contributors_all_time !commits_1y !changes_1y_loc_added !changes_1y_loc_removed !stars !forks !watchers symbol market_cap_rank price_usd market_cap_usd
|
14250aa41d0966e0658ac5c85f2b790ccbcc1970e5b3b7fcc439bc61ea107170 | hodur-org/hodur-example-app | visualizer.cljs | (ns hodur-example-app.visualizer
(:require [hodur-engine.core :as engine]
[hodur-example-app.schemas :as schemas]
[hodur-visualizer-schema.core :as visualizer]))
(def meta-db
(engine/init-schema schemas/shared
schemas/lacinia-pagination
schemas/lacinia-query))
(-> meta-db
visualizer/schema
visualizer/apply-diagram!)
| null | https://raw.githubusercontent.com/hodur-org/hodur-example-app/e327080de31ecbd32319794eec84b38f0bd5ec41/src/hodur_example_app/visualizer.cljs | clojure | (ns hodur-example-app.visualizer
(:require [hodur-engine.core :as engine]
[hodur-example-app.schemas :as schemas]
[hodur-visualizer-schema.core :as visualizer]))
(def meta-db
(engine/init-schema schemas/shared
schemas/lacinia-pagination
schemas/lacinia-query))
(-> meta-db
visualizer/schema
visualizer/apply-diagram!)
| |
72415c6698500dfa1d0078c6d804d051a2d3c6e97a16071694f8d0f66a2e5370 | triffon/fp-2022-23 | 17-shortest-path.rkt | #lang racket
;; TODO: решение от лекции | null | https://raw.githubusercontent.com/triffon/fp-2022-23/c6f5ed7264fcd8988cf29f2d04fda64faa8c8562/exercises/inf2/08/17-shortest-path.rkt | racket | TODO: решение от лекции | #lang racket
|
da868c2d982c52dee2440e395d26276067d1dc3118a886334614c60fb10e1d8f | bcc32/projecteuler-ocaml | sol_205.ml | open! Core
open! Import
type dist = Percent.t Map.M(Int).t
let empty_dist : dist = Map.of_alist_exn (module Int) [ 0, Percent.of_mult 1.0 ]
let shift_n dist ~n : dist =
let comparator = Map.comparator dist in
Map.to_alist dist
|> List.map ~f:(Tuple2.map_fst ~f:(( + ) n))
|> Map.Using_comparator.of_alist_exn ~comparator
;;
let scale_div_n dist ~n : dist =
Map.map dist ~f:(fun p -> Percent.scale p (1. /. float n))
;;
let merge_dist ~key:_ data =
let prob =
match data with
| `Both (p1, p2) -> Percent.(p1 + p2)
| `Left p1 -> p1
| `Right p2 -> p2
in
Some prob
;;
let add_die dist die : dist =
Sequence.range 1 die ~stop:`inclusive
|> Sequence.map ~f:(fun n -> dist |> shift_n ~n |> scale_div_n ~n:die)
|> Sequence.fold ~init:(Map.empty (module Int)) ~f:(Map.merge ~f:merge_dist)
;;
let dice_set ~faces ~len : dist =
Sequence.range 0 len
|> Sequence.fold ~init:empty_dist ~f:(fun dist _ -> add_die dist faces)
;;
let win_prob winner loser : Percent.t =
Map.mapi winner ~f:(fun ~key:roll_w ~data:prob_w ->
Map.mapi loser ~f:(fun ~key:roll_l ~data:prob_l ->
if roll_w > roll_l then Percent.(prob_w * prob_l) else Percent.zero)
|> Map.data
|> List.sum (module Percent) ~f:Fn.id)
|> Map.data
|> List.sum (module Percent) ~f:Fn.id
;;
let main () =
let peter = dice_set ~faces:4 ~len:9 in
let colin = dice_set ~faces:6 ~len:6 in
win_prob peter colin |> Percent.to_mult |> printf "%.07f\n"
;;
0.168ms
let%expect_test "answer" =
main ();
[%expect {| 0.5731441 |}]
;;
include (val Solution.make ~problem:(Number 205) ~main)
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/sol/sol_205.ml | ocaml | open! Core
open! Import
type dist = Percent.t Map.M(Int).t
let empty_dist : dist = Map.of_alist_exn (module Int) [ 0, Percent.of_mult 1.0 ]
let shift_n dist ~n : dist =
let comparator = Map.comparator dist in
Map.to_alist dist
|> List.map ~f:(Tuple2.map_fst ~f:(( + ) n))
|> Map.Using_comparator.of_alist_exn ~comparator
;;
let scale_div_n dist ~n : dist =
Map.map dist ~f:(fun p -> Percent.scale p (1. /. float n))
;;
let merge_dist ~key:_ data =
let prob =
match data with
| `Both (p1, p2) -> Percent.(p1 + p2)
| `Left p1 -> p1
| `Right p2 -> p2
in
Some prob
;;
let add_die dist die : dist =
Sequence.range 1 die ~stop:`inclusive
|> Sequence.map ~f:(fun n -> dist |> shift_n ~n |> scale_div_n ~n:die)
|> Sequence.fold ~init:(Map.empty (module Int)) ~f:(Map.merge ~f:merge_dist)
;;
let dice_set ~faces ~len : dist =
Sequence.range 0 len
|> Sequence.fold ~init:empty_dist ~f:(fun dist _ -> add_die dist faces)
;;
let win_prob winner loser : Percent.t =
Map.mapi winner ~f:(fun ~key:roll_w ~data:prob_w ->
Map.mapi loser ~f:(fun ~key:roll_l ~data:prob_l ->
if roll_w > roll_l then Percent.(prob_w * prob_l) else Percent.zero)
|> Map.data
|> List.sum (module Percent) ~f:Fn.id)
|> Map.data
|> List.sum (module Percent) ~f:Fn.id
;;
let main () =
let peter = dice_set ~faces:4 ~len:9 in
let colin = dice_set ~faces:6 ~len:6 in
win_prob peter colin |> Percent.to_mult |> printf "%.07f\n"
;;
0.168ms
let%expect_test "answer" =
main ();
[%expect {| 0.5731441 |}]
;;
include (val Solution.make ~problem:(Number 205) ~main)
| |
4422b30de7ca6445fce452891f4392bccbd6dfed7c8d5beb70b0b31e24dcde80 | FreeProving/language-coq | FreeVars.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
For TypeError
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Language.Coq.FreeVars
( -- * Constraint synonyms
FreeVars
-- * Main query functions
, getFreeVars
, getFreeVars'
, definedBy
, NoBinding(..)
) where
import Prelude hiding ( Num )
import Data.List.NonEmpty ( (<|), NonEmpty(), partition )
import Data.List.NonEmpty.Extra ( appendl )
import Data.Set ( Set )
import qualified Data.Set as Set
import GHC.TypeLits
import Language.Coq.Gallina
import Language.Coq.Util.FVs
type FreeVars = HasFV Qualid
instance TypeError
('Text "Use binder if this is a binder, use fvOf if this is an occurrence")
=> HasBV Qualid Qualid where
bvOf _ = undefined
instance HasBV Qualid FixBody where
bvOf (FixBody f args order oty def) = binder f
`telescope` bindsNothing
(foldScopes bvOf args (fvOf order <> fvOf oty <> fvOf def))
instance HasBV Qualid FixBodies where
bvOf (FixOne fb) = bvOf fb
bvOf (FixMany fb1 fbs qid) = binder qid
<> bindsNothing (forgetBinders (scopesMutually bvOf (fb1 <| fbs)))
instance HasBV Qualid IndBody where
bvOf (IndBody tyName params indicesUniverse consDecls) = binder tyName
`telescope` (bindsNothing (foldScopes bvOf params $ fvOf indicesUniverse)
<> mconcat
[binder conName
<> bindsNothing
(foldScopes bvOf params $ foldScopes bvOf args $ fvOf oty)
| (conName, args, oty) <- consDecls
])
instance HasBV Qualid Name where
bvOf (Ident x) = binder x
bvOf UnderscoreName = mempty
instance HasBV Qualid Binder where
bvOf (Inferred _ex x) = bvOf x
bvOf (Typed _gen _ex xs ty) = foldMap bvOf xs <> fvOf' ty
bvOf (Generalized _ex ty) = fvOf' ty
instance HasBV Qualid MatchItem where
bvOf (MatchItem scrut oas oin) = fvOf' scrut <> bvOf oas <> bvOf oin
instance HasBV Qualid MultPattern where
bvOf (MultPattern pats) = foldMap bvOf pats
-- Note [Bound variables in patterns]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- We cannot quite capture /all/ the free variables that occur in patterns. The
ambiguous case is that a zero - ary constructor used unqualified looks exactly
-- like a variable used as a binder in a pattern. So what do we do? The answer
is that we treat is as a binder . This is the right behavior : Coq has the
-- same problem, and it manages because it treats all unknown variables as
-- binders, as otherwise they'd be in scope. What's more, treating all
-- variables as binders gives the right result in the body: even if it /wasn't/
-- a binder, it must have been bound already, so at least it will be bound in
-- the body!
--
-- We don't have to worry about module-qualified names, as they must be
-- references to existing terms; and we don't have to worry about constructors
-- /applied/ to arguments, as binders cannot be so applied.
-- See Note [Bound variables in patterns]
instance HasBV Qualid Pattern where
bvOf (ArgsPat con xs) = fvOf' con <> foldMap bvOf xs
bvOf (ExplicitArgsPat con xs) = fvOf' con <> foldMap bvOf xs
bvOf (InfixPat l op r) = bvOf l <> fvOf' (Bare op) <> bvOf r
bvOf (AsPat pat x) = bvOf pat <> binder x
bvOf (InScopePat pat _scp) = bvOf pat
bvOf (QualidPat qid@(Bare _)) = binder qid
-- See [Note Bound variables in patterns]
bvOf (QualidPat qid) = fvOf' qid
bvOf UnderscorePat = mempty
bvOf (NumPat _num) = mempty
bvOf (StringPat _str) = mempty
bvOf (OrPats ors) =
-- We don't check that all the or-patterns bind the same variables
foldMap bvOf ors
instance HasBV Qualid OrPattern where
bvOf (OrPattern pats) = foldMap bvOf pats
-- An @in@-annotation, as found in 'MatchItem'.
instance HasBV Qualid (Qualid, [Pattern]) where
bvOf (con, pats) = fvOf' con <> foldMap bvOf pats
instance HasBV Qualid Sentence where
bvOf (AssumptionSentence assum) = bvOf assum
bvOf (ContextSentence binds) = foldMap bvOf binds
bvOf (DefinitionSentence def) = bvOf def
bvOf (InductiveSentence ind) = bvOf ind
bvOf (FixpointSentence fix) = bvOf fix
bvOf (ProgramSentence sen _) = bvOf sen
bvOf (AssertionSentence assert _pf) = bvOf assert
bvOf (ModuleSentence _mod) = mempty
bvOf (ClassSentence cls) = bvOf cls
bvOf (ExistingClassSentence name) = fvOf' name
bvOf (RecordSentence rcd) = bvOf rcd
bvOf (InstanceSentence ins) = bvOf ins
bvOf (NotationSentence notation) = bvOf notation
bvOf (LocalModuleSentence lmd) = bvOf lmd
bvOf (SectionSentence sec) = bvOf sec
bvOf (ArgumentsSentence _arg) = mempty
bvOf (CommentSentence com) = fvOf' com
bvOf (HintSentence hint) = bvOf hint
bvOf (OptionSentence _option) = mempty
instance HasBV Qualid Assumption where
bvOf (Assumption _kwd assumptions) = bvOf assumptions
instance HasBV Qualid Assums where
bvOf (Assums xs ty) = fvOf' ty <> binders xs
instance HasBV Qualid Definition where
bvOf (DefinitionDef _locality x args oty def) = binder x
<> bindsNothing (foldScopes bvOf args $ fvOf oty <> fvOf def)
bvOf (LetDef x args oty def) = binder x
<> bindsNothing (foldScopes bvOf args $ fvOf oty <> fvOf def)
instance HasBV Qualid Inductive where
bvOf (Inductive ibs nots) = scopesMutually id
$ (bvOf <$> ibs) `appendl` (bvOf <$> nots)
bvOf (CoInductive cbs nots) = scopesMutually id
$ (bvOf <$> cbs) `appendl` (bvOf <$> nots)
instance HasBV Qualid Fixpoint where
bvOf (Fixpoint fbs nots) = scopesMutually id
$ (bvOf <$> fbs) `appendl` (bvOf <$> nots)
bvOf (CoFixpoint cbs nots) = scopesMutually id
$ (bvOf <$> cbs) `appendl` (bvOf <$> nots)
instance HasBV Qualid Assertion where
bvOf (Assertion _kwd name args ty) = binder name
<> bindsNothing (foldScopes bvOf args $ fvOf ty)
instance HasBV Qualid ClassDefinition where
bvOf (ClassDefinition cl params _osort fields) = binder cl
<> foldTelescope bvOf params
`telescope` mconcat [binder field <> fvOf' ty | (field, ty) <- fields]
instance HasBV Qualid RecordDefinition where
bvOf (RecordDefinition name params _osort build fields) =
-- TODO: If build is Nothing, we could synthesize the expected build name
binder name
<> foldMap binder build
<> foldTelescope bvOf params
`telescope` mconcat [binder field <> fvOf' ty | (field, ty) <- fields]
instance HasBV Qualid InstanceDefinition where
bvOf (InstanceDefinition inst params cl defns _mpf) = binder inst
<> bindsNothing (foldScopes bvOf params $ fvOf cl <> fvOf defns)
bvOf (InstanceTerm inst params cl term _mpf) = binder inst
<> bindsNothing (foldScopes bvOf params $ fvOf cl <> fvOf term)
instance HasBV Qualid NotationToken where
bvOf (NSymbol sym) = binder (Bare sym)
bvOf (NIdent nid) = binder (Bare nid)
instance HasBV Qualid Notation where
bvOf (ReservedNotationIdent _) = mempty
bvOf (NotationBinding nb) = bvOf nb
bvOf (NotationDefinition ts def mods)
= let isSymbol (NSymbol _) = True
isSymbol (NIdent _) = False
(symbols, vars) = partition isSymbol ts
freeVars
= foldScopes bvOf vars $ fvOf def <> foldMap fvOf mods
in foldMap bvOf symbols <> bindsNothing freeVars
bvOf (InfixDefinition op defn _ _) = binder (Bare op) <> fvOf' defn
instance HasBV Qualid NotationBinding where
bvOf (NotationIdentBinding op def) = binder (Bare op) <> fvOf' def
instance HasBV Qualid Hint where
bvOf (Hint _locality hint_definition _databases) = bvOf hint_definition
instance HasBV Qualid HintDefinition where
bvOf (HintResolve _ _ (Just pat)) = bvOf pat
bvOf (HintExtern _ (Just pat) _) = bvOf pat
bvOf _ = mempty
instance HasBV Qualid LocalModule where
bvOf (LocalModule _name sentences) = foldTelescope bvOf sentences
instance HasBV Qualid Section where
bvOf (Section _name sentences) = foldTelescope bvOf sentences
-- TODO Not all sequences of bindings should be telescopes!
bindingTelescope : : ( HasBV b , Monoid d , Foldable f )
= > ( - > d )
- > f b
- > Variables Qualid d a
- > Variables Qualid d a
bindingTelescope f xs rest = foldr ( bvOf ) rest xs
bindingTelescope :: (HasBV b, Monoid d, Foldable f)
=> (Qualid -> d)
-> f b
-> Variables Qualid d a
-> Variables Qualid d a
bindingTelescope f xs rest = foldr (bvOf) rest xs
-}
instance HasBV Qualid b => HasBV Qualid (Maybe b) where
bvOf = foldMap bvOf
instance TypeError
('Text "A sequence of binders could be a telescope (use foldTelescope or foldScopes) or not (use foldMap)")
=> HasBV Qualid [b] where
bvOf = undefined
instance TypeError
('Text "A sequence of binders could be a telescope (use foldTelescope or foldScopes) or not (use foldMap)")
=> HasBV Qualid (NonEmpty b) where
bvOf = undefined
getFreeVars :: HasFV Qualid t => t -> Set Qualid
getFreeVars = getFVs . fvOf
getFreeVars' :: HasBV Qualid t => t -> Set Qualid
getFreeVars' = getFVs . forgetBinders . bvOf
definedBy :: HasBV Qualid x => x -> [Qualid]
definedBy = Set.toList . getBVars . bvOf
instance HasFV Qualid Qualid where
fvOf = occurrence
instance HasFV Qualid Term where
fvOf (Forall xs t) = foldScopes bvOf xs $ fvOf t
fvOf (Fun xs t) = foldScopes bvOf xs $ fvOf t
The fixpoint name stays local
fvOf (Cofix cbs) = forgetBinders $ bvOf cbs
fvOf (Let x args oty val body) = foldScopes bvOf args (fvOf oty <> fvOf val)
<> binder x `scopesOver` fvOf body
fvOf (LetTuple xs oret val body)
= fvOf oret <> fvOf val <> foldScopes bvOf xs (fvOf body)
fvOf (LetTick pat def body)
= fvOf def <> bvOf pat `scopesOver` fvOf body
fvOf (If _ c oret t f) = fvOf c <> fvOf oret <> fvOf t <> fvOf f
fvOf (HasType tm ty) = fvOf tm <> fvOf ty
fvOf (CheckType tm ty) = fvOf tm <> fvOf ty
fvOf (ToSupportType tm) = fvOf tm
fvOf (Arrow ty1 ty2) = fvOf ty1 <> fvOf ty2
fvOf (App f xs) = fvOf f <> fvOf xs
fvOf (ExplicitApp qid xs) = fvOf qid <> fvOf xs
fvOf (InScope t _scope) = fvOf t
fvOf (Match items oret eqns) = foldMap bvOf items
`scopesOver` (fvOf oret <> fvOf eqns)
fvOf (Qualid qid) = fvOf qid
fvOf (RawQualid qid) = fvOf qid
fvOf (Sort _sort) = mempty
fvOf (Num _num) = mempty
fvOf (String _str) = mempty
fvOf (HsString _str) = mempty
fvOf (HsChar _char) = mempty
fvOf Underscore = mempty
fvOf (Parens t) = fvOf t
fvOf (Bang t) = fvOf t
fvOf (Record defns) = fvOf defns
instance HasFV Qualid Arg where
fvOf (PosArg t) = fvOf t
fvOf (NamedArg _x t) =
-- The name here is the name of a function parameter; it's not an occurrence
of a Gallina - level variable .
fvOf t
instance HasFV Qualid Order where
fvOf (StructOrder qid) = fvOf qid
fvOf (MeasureOrder expr rel) = fvOf expr <> fvOf rel
fvOf (WFOrder rel qid) = fvOf rel <> fvOf qid
instance HasFV Qualid DepRetType where
fvOf (DepRetType oas ret) = bvOf oas `scopesOver` fvOf ret
instance HasFV Qualid ReturnType where
fvOf (ReturnType ty) = fvOf ty
instance HasFV Qualid Equation where
fvOf (Equation mpats body) = foldMap bvOf mpats `scopesOver` fvOf body
instance HasFV Qualid Comment where
fvOf (Comment _) = mempty
instance HasFV Qualid AssumptionKeyword where
fvOf Axiom = mempty
fvOf Axioms = mempty
fvOf Conjecture = mempty
fvOf Parameter = mempty
fvOf Parameters = mempty
fvOf Variable = mempty
fvOf Variables = mempty
fvOf Hypothesis = mempty
fvOf Hypotheses = mempty
instance HasFV Qualid Locality where
fvOf Global = mempty
fvOf Local = mempty
instance HasFV Qualid AssertionKeyword where
fvOf Theorem = mempty
fvOf Lemma = mempty
fvOf Remark = mempty
fvOf Fact = mempty
fvOf Corollary = mempty
fvOf Proposition = mempty
fvOf Definition = mempty
fvOf Example = mempty
instance HasFV Qualid SyntaxModifier where
fvOf (SModLevel _) = mempty
fvOf (SModIdentLevel ids _) = foldMap (occurrence . Bare) ids
fvOf (SModAssociativity _) = mempty
fvOf SModOnlyParsing = mempty
fvOf SModOnlyPrinting = mempty
instance HasFV Qualid t => HasFV Qualid (Maybe t) where
fvOf = foldMap fvOf
instance HasFV Qualid t => HasFV Qualid [t] where
fvOf = foldMap fvOf
instance HasFV Qualid t => HasFV Qualid (NonEmpty t) where
fvOf = foldMap fvOf
instance (HasFV Qualid t1, HasFV Qualid t2) => HasFV Qualid (t1, t2) where
fvOf (x, y) = fvOf x <> fvOf y
newtype NoBinding a = NoBinding a
instance HasBV i a => HasFV i (NoBinding a) where
fvOf (NoBinding x) = forgetBinders (bvOf x)
| null | https://raw.githubusercontent.com/FreeProving/language-coq/99877c7f3596cd86bbec1b2a8af960252a5402f5/src/lib/Language/Coq/FreeVars.hs | haskell | # LANGUAGE ConstraintKinds #
* Constraint synonyms
* Main query functions
Note [Bound variables in patterns]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We cannot quite capture /all/ the free variables that occur in patterns. The
like a variable used as a binder in a pattern. So what do we do? The answer
same problem, and it manages because it treats all unknown variables as
binders, as otherwise they'd be in scope. What's more, treating all
variables as binders gives the right result in the body: even if it /wasn't/
a binder, it must have been bound already, so at least it will be bound in
the body!
We don't have to worry about module-qualified names, as they must be
references to existing terms; and we don't have to worry about constructors
/applied/ to arguments, as binders cannot be so applied.
See Note [Bound variables in patterns]
See [Note Bound variables in patterns]
We don't check that all the or-patterns bind the same variables
An @in@-annotation, as found in 'MatchItem'.
TODO: If build is Nothing, we could synthesize the expected build name
TODO Not all sequences of bindings should be telescopes!
The name here is the name of a function parameter; it's not an occurrence | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
For TypeError
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Language.Coq.FreeVars
FreeVars
, getFreeVars
, getFreeVars'
, definedBy
, NoBinding(..)
) where
import Prelude hiding ( Num )
import Data.List.NonEmpty ( (<|), NonEmpty(), partition )
import Data.List.NonEmpty.Extra ( appendl )
import Data.Set ( Set )
import qualified Data.Set as Set
import GHC.TypeLits
import Language.Coq.Gallina
import Language.Coq.Util.FVs
type FreeVars = HasFV Qualid
instance TypeError
('Text "Use binder if this is a binder, use fvOf if this is an occurrence")
=> HasBV Qualid Qualid where
bvOf _ = undefined
instance HasBV Qualid FixBody where
bvOf (FixBody f args order oty def) = binder f
`telescope` bindsNothing
(foldScopes bvOf args (fvOf order <> fvOf oty <> fvOf def))
instance HasBV Qualid FixBodies where
bvOf (FixOne fb) = bvOf fb
bvOf (FixMany fb1 fbs qid) = binder qid
<> bindsNothing (forgetBinders (scopesMutually bvOf (fb1 <| fbs)))
instance HasBV Qualid IndBody where
bvOf (IndBody tyName params indicesUniverse consDecls) = binder tyName
`telescope` (bindsNothing (foldScopes bvOf params $ fvOf indicesUniverse)
<> mconcat
[binder conName
<> bindsNothing
(foldScopes bvOf params $ foldScopes bvOf args $ fvOf oty)
| (conName, args, oty) <- consDecls
])
instance HasBV Qualid Name where
bvOf (Ident x) = binder x
bvOf UnderscoreName = mempty
instance HasBV Qualid Binder where
bvOf (Inferred _ex x) = bvOf x
bvOf (Typed _gen _ex xs ty) = foldMap bvOf xs <> fvOf' ty
bvOf (Generalized _ex ty) = fvOf' ty
instance HasBV Qualid MatchItem where
bvOf (MatchItem scrut oas oin) = fvOf' scrut <> bvOf oas <> bvOf oin
instance HasBV Qualid MultPattern where
bvOf (MultPattern pats) = foldMap bvOf pats
ambiguous case is that a zero - ary constructor used unqualified looks exactly
is that we treat is as a binder . This is the right behavior : Coq has the
instance HasBV Qualid Pattern where
bvOf (ArgsPat con xs) = fvOf' con <> foldMap bvOf xs
bvOf (ExplicitArgsPat con xs) = fvOf' con <> foldMap bvOf xs
bvOf (InfixPat l op r) = bvOf l <> fvOf' (Bare op) <> bvOf r
bvOf (AsPat pat x) = bvOf pat <> binder x
bvOf (InScopePat pat _scp) = bvOf pat
bvOf (QualidPat qid@(Bare _)) = binder qid
bvOf (QualidPat qid) = fvOf' qid
bvOf UnderscorePat = mempty
bvOf (NumPat _num) = mempty
bvOf (StringPat _str) = mempty
bvOf (OrPats ors) =
foldMap bvOf ors
instance HasBV Qualid OrPattern where
bvOf (OrPattern pats) = foldMap bvOf pats
instance HasBV Qualid (Qualid, [Pattern]) where
bvOf (con, pats) = fvOf' con <> foldMap bvOf pats
instance HasBV Qualid Sentence where
bvOf (AssumptionSentence assum) = bvOf assum
bvOf (ContextSentence binds) = foldMap bvOf binds
bvOf (DefinitionSentence def) = bvOf def
bvOf (InductiveSentence ind) = bvOf ind
bvOf (FixpointSentence fix) = bvOf fix
bvOf (ProgramSentence sen _) = bvOf sen
bvOf (AssertionSentence assert _pf) = bvOf assert
bvOf (ModuleSentence _mod) = mempty
bvOf (ClassSentence cls) = bvOf cls
bvOf (ExistingClassSentence name) = fvOf' name
bvOf (RecordSentence rcd) = bvOf rcd
bvOf (InstanceSentence ins) = bvOf ins
bvOf (NotationSentence notation) = bvOf notation
bvOf (LocalModuleSentence lmd) = bvOf lmd
bvOf (SectionSentence sec) = bvOf sec
bvOf (ArgumentsSentence _arg) = mempty
bvOf (CommentSentence com) = fvOf' com
bvOf (HintSentence hint) = bvOf hint
bvOf (OptionSentence _option) = mempty
instance HasBV Qualid Assumption where
bvOf (Assumption _kwd assumptions) = bvOf assumptions
instance HasBV Qualid Assums where
bvOf (Assums xs ty) = fvOf' ty <> binders xs
instance HasBV Qualid Definition where
bvOf (DefinitionDef _locality x args oty def) = binder x
<> bindsNothing (foldScopes bvOf args $ fvOf oty <> fvOf def)
bvOf (LetDef x args oty def) = binder x
<> bindsNothing (foldScopes bvOf args $ fvOf oty <> fvOf def)
instance HasBV Qualid Inductive where
bvOf (Inductive ibs nots) = scopesMutually id
$ (bvOf <$> ibs) `appendl` (bvOf <$> nots)
bvOf (CoInductive cbs nots) = scopesMutually id
$ (bvOf <$> cbs) `appendl` (bvOf <$> nots)
instance HasBV Qualid Fixpoint where
bvOf (Fixpoint fbs nots) = scopesMutually id
$ (bvOf <$> fbs) `appendl` (bvOf <$> nots)
bvOf (CoFixpoint cbs nots) = scopesMutually id
$ (bvOf <$> cbs) `appendl` (bvOf <$> nots)
instance HasBV Qualid Assertion where
bvOf (Assertion _kwd name args ty) = binder name
<> bindsNothing (foldScopes bvOf args $ fvOf ty)
instance HasBV Qualid ClassDefinition where
bvOf (ClassDefinition cl params _osort fields) = binder cl
<> foldTelescope bvOf params
`telescope` mconcat [binder field <> fvOf' ty | (field, ty) <- fields]
instance HasBV Qualid RecordDefinition where
bvOf (RecordDefinition name params _osort build fields) =
binder name
<> foldMap binder build
<> foldTelescope bvOf params
`telescope` mconcat [binder field <> fvOf' ty | (field, ty) <- fields]
instance HasBV Qualid InstanceDefinition where
bvOf (InstanceDefinition inst params cl defns _mpf) = binder inst
<> bindsNothing (foldScopes bvOf params $ fvOf cl <> fvOf defns)
bvOf (InstanceTerm inst params cl term _mpf) = binder inst
<> bindsNothing (foldScopes bvOf params $ fvOf cl <> fvOf term)
instance HasBV Qualid NotationToken where
bvOf (NSymbol sym) = binder (Bare sym)
bvOf (NIdent nid) = binder (Bare nid)
instance HasBV Qualid Notation where
bvOf (ReservedNotationIdent _) = mempty
bvOf (NotationBinding nb) = bvOf nb
bvOf (NotationDefinition ts def mods)
= let isSymbol (NSymbol _) = True
isSymbol (NIdent _) = False
(symbols, vars) = partition isSymbol ts
freeVars
= foldScopes bvOf vars $ fvOf def <> foldMap fvOf mods
in foldMap bvOf symbols <> bindsNothing freeVars
bvOf (InfixDefinition op defn _ _) = binder (Bare op) <> fvOf' defn
instance HasBV Qualid NotationBinding where
bvOf (NotationIdentBinding op def) = binder (Bare op) <> fvOf' def
instance HasBV Qualid Hint where
bvOf (Hint _locality hint_definition _databases) = bvOf hint_definition
instance HasBV Qualid HintDefinition where
bvOf (HintResolve _ _ (Just pat)) = bvOf pat
bvOf (HintExtern _ (Just pat) _) = bvOf pat
bvOf _ = mempty
instance HasBV Qualid LocalModule where
bvOf (LocalModule _name sentences) = foldTelescope bvOf sentences
instance HasBV Qualid Section where
bvOf (Section _name sentences) = foldTelescope bvOf sentences
bindingTelescope : : ( HasBV b , Monoid d , Foldable f )
= > ( - > d )
- > f b
- > Variables Qualid d a
- > Variables Qualid d a
bindingTelescope f xs rest = foldr ( bvOf ) rest xs
bindingTelescope :: (HasBV b, Monoid d, Foldable f)
=> (Qualid -> d)
-> f b
-> Variables Qualid d a
-> Variables Qualid d a
bindingTelescope f xs rest = foldr (bvOf) rest xs
-}
instance HasBV Qualid b => HasBV Qualid (Maybe b) where
bvOf = foldMap bvOf
instance TypeError
('Text "A sequence of binders could be a telescope (use foldTelescope or foldScopes) or not (use foldMap)")
=> HasBV Qualid [b] where
bvOf = undefined
instance TypeError
('Text "A sequence of binders could be a telescope (use foldTelescope or foldScopes) or not (use foldMap)")
=> HasBV Qualid (NonEmpty b) where
bvOf = undefined
getFreeVars :: HasFV Qualid t => t -> Set Qualid
getFreeVars = getFVs . fvOf
getFreeVars' :: HasBV Qualid t => t -> Set Qualid
getFreeVars' = getFVs . forgetBinders . bvOf
definedBy :: HasBV Qualid x => x -> [Qualid]
definedBy = Set.toList . getBVars . bvOf
instance HasFV Qualid Qualid where
fvOf = occurrence
instance HasFV Qualid Term where
fvOf (Forall xs t) = foldScopes bvOf xs $ fvOf t
fvOf (Fun xs t) = foldScopes bvOf xs $ fvOf t
The fixpoint name stays local
fvOf (Cofix cbs) = forgetBinders $ bvOf cbs
fvOf (Let x args oty val body) = foldScopes bvOf args (fvOf oty <> fvOf val)
<> binder x `scopesOver` fvOf body
fvOf (LetTuple xs oret val body)
= fvOf oret <> fvOf val <> foldScopes bvOf xs (fvOf body)
fvOf (LetTick pat def body)
= fvOf def <> bvOf pat `scopesOver` fvOf body
fvOf (If _ c oret t f) = fvOf c <> fvOf oret <> fvOf t <> fvOf f
fvOf (HasType tm ty) = fvOf tm <> fvOf ty
fvOf (CheckType tm ty) = fvOf tm <> fvOf ty
fvOf (ToSupportType tm) = fvOf tm
fvOf (Arrow ty1 ty2) = fvOf ty1 <> fvOf ty2
fvOf (App f xs) = fvOf f <> fvOf xs
fvOf (ExplicitApp qid xs) = fvOf qid <> fvOf xs
fvOf (InScope t _scope) = fvOf t
fvOf (Match items oret eqns) = foldMap bvOf items
`scopesOver` (fvOf oret <> fvOf eqns)
fvOf (Qualid qid) = fvOf qid
fvOf (RawQualid qid) = fvOf qid
fvOf (Sort _sort) = mempty
fvOf (Num _num) = mempty
fvOf (String _str) = mempty
fvOf (HsString _str) = mempty
fvOf (HsChar _char) = mempty
fvOf Underscore = mempty
fvOf (Parens t) = fvOf t
fvOf (Bang t) = fvOf t
fvOf (Record defns) = fvOf defns
instance HasFV Qualid Arg where
fvOf (PosArg t) = fvOf t
fvOf (NamedArg _x t) =
of a Gallina - level variable .
fvOf t
instance HasFV Qualid Order where
fvOf (StructOrder qid) = fvOf qid
fvOf (MeasureOrder expr rel) = fvOf expr <> fvOf rel
fvOf (WFOrder rel qid) = fvOf rel <> fvOf qid
instance HasFV Qualid DepRetType where
fvOf (DepRetType oas ret) = bvOf oas `scopesOver` fvOf ret
instance HasFV Qualid ReturnType where
fvOf (ReturnType ty) = fvOf ty
instance HasFV Qualid Equation where
fvOf (Equation mpats body) = foldMap bvOf mpats `scopesOver` fvOf body
instance HasFV Qualid Comment where
fvOf (Comment _) = mempty
instance HasFV Qualid AssumptionKeyword where
fvOf Axiom = mempty
fvOf Axioms = mempty
fvOf Conjecture = mempty
fvOf Parameter = mempty
fvOf Parameters = mempty
fvOf Variable = mempty
fvOf Variables = mempty
fvOf Hypothesis = mempty
fvOf Hypotheses = mempty
instance HasFV Qualid Locality where
fvOf Global = mempty
fvOf Local = mempty
instance HasFV Qualid AssertionKeyword where
fvOf Theorem = mempty
fvOf Lemma = mempty
fvOf Remark = mempty
fvOf Fact = mempty
fvOf Corollary = mempty
fvOf Proposition = mempty
fvOf Definition = mempty
fvOf Example = mempty
instance HasFV Qualid SyntaxModifier where
fvOf (SModLevel _) = mempty
fvOf (SModIdentLevel ids _) = foldMap (occurrence . Bare) ids
fvOf (SModAssociativity _) = mempty
fvOf SModOnlyParsing = mempty
fvOf SModOnlyPrinting = mempty
instance HasFV Qualid t => HasFV Qualid (Maybe t) where
fvOf = foldMap fvOf
instance HasFV Qualid t => HasFV Qualid [t] where
fvOf = foldMap fvOf
instance HasFV Qualid t => HasFV Qualid (NonEmpty t) where
fvOf = foldMap fvOf
instance (HasFV Qualid t1, HasFV Qualid t2) => HasFV Qualid (t1, t2) where
fvOf (x, y) = fvOf x <> fvOf y
newtype NoBinding a = NoBinding a
instance HasBV i a => HasFV i (NoBinding a) where
fvOf (NoBinding x) = forgetBinders (bvOf x)
|
68b305524a0bc0ab03b238a50ffc7b937d71f454680903fa36d244b1bbd512ad | fukamachi/clozure-cl | faslenv.lisp | -*- Mode : Lisp ; Package : CCL -*-
;;;
Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
;;;
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL,
which is distributed with Clozure CL as the file " LGPL " . Where these
;;; conflict, the preamble takes precedence.
;;;
;;; Clozure CL is referenced in the preamble as the "LIBRARY."
;;;
;;; The LLGPL is also available online at
;;;
(in-package "CCL")
;; Compile-time environment for fasl dumper/loader.
; loader state istruct
(def-accessors (faslstate) %svref
()
faslstate.faslfname
faslstate.faslevec
faslstate.faslecnt
faslstate.faslfd
faslstate.faslval
faslstate.faslstr
faslstate.oldfaslstr
faslstate.faslerr
faslstate.iobuffer
faslstate.bufcount
faslstate.faslversion
faslstate.faslepush
faslstate.faslgsymbols
faslstate.fasldispatch)
(defconstant numfaslops 80 "Number of fasl file opcodes, roughly")
(defconstant $fasl-epush-bit 7)
(defconstant $fasl-file-id #xff00)
(defconstant $fasl-file-id1 #xff01)
(defconstant $faslend #xff)
(defconstant $fasl-buf-len 2048)
(defmacro deffaslop (n arglist &body body)
`(setf (svref *fasl-dispatch-table* ,n)
(nfunction ,n (lambda ,arglist ,@body))))
(defconstant $fasl-noop 0) ;<nada:zilch>.
(defconstant $fasl-s32-vector 1) ;<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 32) <count>)
(defconstant $fasl-code-vector 2) ;<count> words of code
(defconstant $fasl-clfun 3) ;<size:count><codesize:count>code,size-codesize exprs
(defconstant $fasl-lfuncall 4) ;<lfun:expr> funcall the lfun.
(defconstant $fasl-globals 5) ;<expr> global symbols vector
(defconstant $fasl-char 6) ;<char:byte> Make a char
< value : long > Make a ( 4 - byte ) fixnum
(defconstant $fasl-dfloat 8) ;<hi:long><lo:long> Make a DOUBLE-FLOAT
(defconstant $fasl-bignum32 9) ;<count> make a bignum with count digits
(defconstant $fasl-word-fixnum 10) ;<value:word> Make a fixnum
(defconstant $fasl-double-float-vector 11) ;<count> make a (SIMPLE-ARRAY DOUBLE-FLOAT <count>)
(defconstant $fasl-single-float-vector 12) ;<count> make a (SIMPLE-ARRAY SINGLE-FLOAT <count>)
(defconstant $fasl-bit-vector 13) ;<count> make a (SIMPLE-ARRAY BIT <count>)
< count > make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 8) < count > )
(defconstant $fasl-cons 15) ;<car:expr><cdr:expr> Make a cons
(defconstant $fasl-s8-vector 16) ;<count> make a (SIMPLE-ARRAY (SIGNED-BYTE 8) <count>)
(defconstant $fasl-t-vector 17) ;<count> make a (SIMPLE-ARRAY T <count>)
(defconstant $fasl-nil 18) ; Make nil
(defconstant $fasl-timm 19) ;<n:long>
(defconstant $fasl-function 20) ;<count> Make function
(defconstant $fasl-vstr 21) ;<vstring> Make a string
(defconstant $fasl-vmksym 22) ;<vstring> Make an uninterned symbol
(defconstant $fasl-platform 23) ;<n:byte> Ensure that file's loadable on platform n.
(defconstant $fasl-vetab-alloc 24) ;<count:count> Make a new expression table
; with count slots. Current etab gets lost.
(defconstant $fasl-veref 25) ;<index:count> Get the value from an etab slot.
< high : long><low : long > Make an 8 - byte fixnum .
expr >
(defconstant $fasl-eval 28) ;<expr> Eval <expr> and return value.
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 16 ) < count > )
(defconstant $fasl-s16-vector 30) ;<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 16) <count>)
(defconstant $fasl-vintern 31) ;<vstring> Intern in current pkg.
< pkg : expr><vstring > Make a sym in pkg .
(defconstant $fasl-vpkg 33) ;<vstring> Returns the package of given name
(defconstant $fasl-vgvec 34) ;<subtype:byte><n:count><n exprs>
(defconstant $fasl-defun 35) ;<fn:expr><doc:expr>
(defconstant $fasl-macro 37) ;<fn:expr><doc:expr>
expr><val : expr><doc : expr >
expr><val : expr><doc : expr >
expr >
expr><val : expr><doc : expr >
(defconstant $fasl-vivec 42) ;<subtype:byte><n:count><n data bytes>
(defconstant $fasl-prog1 43) ;<expr><expr> - Second <expr> is for side-affects only
(defconstant $fasl-vlist 44) ;<n:count> <data: n+1 exprs> Make a list
(defconstant $fasl-vlist* 45) ;<n:count> <data:n+2 exprs> Make an sexpr
(defconstant $fasl-sfloat 46) ;<long> Make SINGLE-FLOAT from bits
(defconstant $fasl-src 47) ;<expr> - Set *loading-file-source-file * to <expr>.
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 32 ) < count > )
(defconstant $fasl-provide 49) ;<string:expr>
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 64 ) < count > )
(defconstant $fasl-s64-vector 51) ;<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 64) <count>)
< count > Make an ISTRUCT with < count > elements
(defconstant $fasl-complex 53) ;<real:expr><imag:expr>
(defconstant $fasl-ratio 54) ;<num:expr><den:expr>
(defconstant $fasl-vector-header 55) ;<count> Make a vector header
(defconstant $fasl-array-header 56) ;<count> Make an array header.
(defconstant $fasl-s32 57) ;<4bytes> Make a (SIGNED-BYTE 32)
(defconstant $fasl-vintern-special 58) ;<vstring> Intern in current pkg, ensure that it has a special binding index
(defconstant $fasl-s64 59) ;<8bytes> Make a (SIGNED-BYTE 64)
< pkg : expr><vstring > Make a sym in pkg , ensure that it has a special binding index
(defconstant $fasl-vmksym-special 61) ;<vstring> Make an uninterned symbol, ensure special binding index
(defconstant $fasl-nvmksym-special 62) ;<nvstring> Make an uninterned symbol, ensure special binding index
< pkg : expr><nvstring > Make a sym in pkg , ensure that it has a special binding index
(defconstant $fasl-nvintern-special 64) ;<nvstring> Intern in current pkg, ensure that it has a special binding index
(defconstant $fasl-nvpkg 65) ;<vstring> Returns the package of given name
(defconstant $fasl-nvpkg-intern 66) ;<nvstring> Intern in current pkg.
< pkg : expr><nvstring > Make a sym in pkg .
(defconstant $fasl-nvmksym 68) ;<nvstring> Make a string
(defconstant $fasl-nvstr 69) ;<nvstring> Make an uninterned symbol
(defconstant $fasl-toplevel-location 70);<expr> - Set *loading-toplevel-location* to <expr>
(defconstant $fasl-istruct-cell 71) ;<expr> register istruct cell for expr
;;; <string> means <size><size bytes> (this is no longer used)
< size > means either < n : byte > with n<#xFF , or < : word > with n<#xFFFF or
;;; <FFFF><n:long>
;;; <count> is a variable-length encoding of an unsigned integer, written
7 bits per octet , the least significant bits written first and the most
significant octet having bit 7 set , so 127 would be written as # x00 and
128 as # x00 # x81
;;; <vstring> is a <count> (string length) followed by count octets of
8 - bit charcode data .
;;; <nvstring> is a <count> (string length) followd by count <counts> of
;;; variable-length charcode data. This encodes ASCII/STANDARD-CHAR as
;;; compactly as the <vstring> encoding, which should probably be deprecated.
(defconstant $fasl-end #xFF) ;Stop reading.
(defconstant $fasl-epush-mask #x80) ;Push value on etab if this bit is set in opcode.
(defmacro fasl-epush-op (op) `(%ilogior2 ,$fasl-epush-mask ,op))
(provide "FASLENV")
| null | https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/xdump/faslenv.lisp | lisp | Package : CCL -*-
file "LICENSE". The LLGPL consists of a preamble and the LGPL,
conflict, the preamble takes precedence.
Clozure CL is referenced in the preamble as the "LIBRARY."
The LLGPL is also available online at
Compile-time environment for fasl dumper/loader.
loader state istruct
<nada:zilch>.
<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 32) <count>)
<count> words of code
<size:count><codesize:count>code,size-codesize exprs
<lfun:expr> funcall the lfun.
<expr> global symbols vector
<char:byte> Make a char
<hi:long><lo:long> Make a DOUBLE-FLOAT
<count> make a bignum with count digits
<value:word> Make a fixnum
<count> make a (SIMPLE-ARRAY DOUBLE-FLOAT <count>)
<count> make a (SIMPLE-ARRAY SINGLE-FLOAT <count>)
<count> make a (SIMPLE-ARRAY BIT <count>)
<car:expr><cdr:expr> Make a cons
<count> make a (SIMPLE-ARRAY (SIGNED-BYTE 8) <count>)
<count> make a (SIMPLE-ARRAY T <count>)
Make nil
<n:long>
<count> Make function
<vstring> Make a string
<vstring> Make an uninterned symbol
<n:byte> Ensure that file's loadable on platform n.
<count:count> Make a new expression table
with count slots. Current etab gets lost.
<index:count> Get the value from an etab slot.
<expr> Eval <expr> and return value.
<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 16) <count>)
<vstring> Intern in current pkg.
<vstring> Returns the package of given name
<subtype:byte><n:count><n exprs>
<fn:expr><doc:expr>
<fn:expr><doc:expr>
<subtype:byte><n:count><n data bytes>
<expr><expr> - Second <expr> is for side-affects only
<n:count> <data: n+1 exprs> Make a list
<n:count> <data:n+2 exprs> Make an sexpr
<long> Make SINGLE-FLOAT from bits
<expr> - Set *loading-file-source-file * to <expr>.
<string:expr>
<count> Make a (SIMPLE-ARRAY (SIGNED-BYTE 64) <count>)
<real:expr><imag:expr>
<num:expr><den:expr>
<count> Make a vector header
<count> Make an array header.
<4bytes> Make a (SIGNED-BYTE 32)
<vstring> Intern in current pkg, ensure that it has a special binding index
<8bytes> Make a (SIGNED-BYTE 64)
<vstring> Make an uninterned symbol, ensure special binding index
<nvstring> Make an uninterned symbol, ensure special binding index
<nvstring> Intern in current pkg, ensure that it has a special binding index
<vstring> Returns the package of given name
<nvstring> Intern in current pkg.
<nvstring> Make a string
<nvstring> Make an uninterned symbol
<expr> - Set *loading-toplevel-location* to <expr>
<expr> register istruct cell for expr
<string> means <size><size bytes> (this is no longer used)
<FFFF><n:long>
<count> is a variable-length encoding of an unsigned integer, written
<vstring> is a <count> (string length) followed by count octets of
<nvstring> is a <count> (string length) followd by count <counts> of
variable-length charcode data. This encodes ASCII/STANDARD-CHAR as
compactly as the <vstring> encoding, which should probably be deprecated.
Stop reading.
Push value on etab if this bit is set in opcode. | Copyright ( C ) 2009 Clozure Associates
Copyright ( C ) 1994 - 2001 Digitool , Inc
This file is part of Clozure CL .
Clozure CL is licensed under the terms of the Lisp Lesser GNU Public
License , known as the LLGPL and distributed with Clozure CL as the
which is distributed with Clozure CL as the file " LGPL " . Where these
(in-package "CCL")
(def-accessors (faslstate) %svref
()
faslstate.faslfname
faslstate.faslevec
faslstate.faslecnt
faslstate.faslfd
faslstate.faslval
faslstate.faslstr
faslstate.oldfaslstr
faslstate.faslerr
faslstate.iobuffer
faslstate.bufcount
faslstate.faslversion
faslstate.faslepush
faslstate.faslgsymbols
faslstate.fasldispatch)
(defconstant numfaslops 80 "Number of fasl file opcodes, roughly")
(defconstant $fasl-epush-bit 7)
(defconstant $fasl-file-id #xff00)
(defconstant $fasl-file-id1 #xff01)
(defconstant $faslend #xff)
(defconstant $fasl-buf-len 2048)
(defmacro deffaslop (n arglist &body body)
`(setf (svref *fasl-dispatch-table* ,n)
(nfunction ,n (lambda ,arglist ,@body))))
< value : long > Make a ( 4 - byte ) fixnum
< count > make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 8) < count > )
< high : long><low : long > Make an 8 - byte fixnum .
expr >
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 16 ) < count > )
< pkg : expr><vstring > Make a sym in pkg .
expr><val : expr><doc : expr >
expr><val : expr><doc : expr >
expr >
expr><val : expr><doc : expr >
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 32 ) < count > )
< count > Make a ( SIMPLE - ARRAY ( UNSIGNED - BYTE 64 ) < count > )
< count > Make an ISTRUCT with < count > elements
< pkg : expr><vstring > Make a sym in pkg , ensure that it has a special binding index
< pkg : expr><nvstring > Make a sym in pkg , ensure that it has a special binding index
< pkg : expr><nvstring > Make a sym in pkg .
< size > means either < n : byte > with n<#xFF , or < : word > with n<#xFFFF or
7 bits per octet , the least significant bits written first and the most
significant octet having bit 7 set , so 127 would be written as # x00 and
128 as # x00 # x81
8 - bit charcode data .
(defmacro fasl-epush-op (op) `(%ilogior2 ,$fasl-epush-mask ,op))
(provide "FASLENV")
|
8f7a04dd21d1b6d04f19cf24b26ad2fd6169e1dfdc8da0c66202ab9f58d4a52d | clojure-link/link | project.clj | (def netty-version "4.1.61.Final")
(def example-base-command
["trampoline" "with-profile" "default,example" "run" "-m"])
(defproject link "0.12.8-SNAPSHOT"
:description "A clojure framework for nonblocking network programming"
:url ""
:license {:name "Eclipse Public License - v 1.0"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.3"]
[io.netty/netty-buffer ~netty-version]
[io.netty/netty-codec-http ~netty-version]
[io.netty/netty-codec-http2 ~netty-version]
[io.netty/netty-codec ~netty-version]
[io.netty/netty-common ~netty-version]
[io.netty/netty-handler ~netty-version]
[io.netty/netty-transport ~netty-version]
[org.clojure/tools.logging "1.1.0"]]
:profiles {:dev {:dependencies [[log4j/log4j "1.2.17"]]}
:example {:source-paths ["examples"]}}
:scm {:name "git"
:url ""}
:global-vars {*warn-on-reflection* false}
:deploy-repositories {"releases" :clojars}
:aliases {"run-echo-example" ~(conj example-base-command "link.examples.echo")
"run-http-simple-example" ~(conj example-base-command "link.examples.http.simple")
"run-http-async-example" ~(conj example-base-command "link.examples.http.async")
"run-http-h2c-example" ~(conj example-base-command "link.examples.http.h2c")
"run-http-h2-example" ~(conj example-base-command "link.examples.http.h2")})
| null | https://raw.githubusercontent.com/clojure-link/link/e6844b1cb67c5201907debd65c8de1b5e2454da1/project.clj | clojure | (def netty-version "4.1.61.Final")
(def example-base-command
["trampoline" "with-profile" "default,example" "run" "-m"])
(defproject link "0.12.8-SNAPSHOT"
:description "A clojure framework for nonblocking network programming"
:url ""
:license {:name "Eclipse Public License - v 1.0"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.3"]
[io.netty/netty-buffer ~netty-version]
[io.netty/netty-codec-http ~netty-version]
[io.netty/netty-codec-http2 ~netty-version]
[io.netty/netty-codec ~netty-version]
[io.netty/netty-common ~netty-version]
[io.netty/netty-handler ~netty-version]
[io.netty/netty-transport ~netty-version]
[org.clojure/tools.logging "1.1.0"]]
:profiles {:dev {:dependencies [[log4j/log4j "1.2.17"]]}
:example {:source-paths ["examples"]}}
:scm {:name "git"
:url ""}
:global-vars {*warn-on-reflection* false}
:deploy-repositories {"releases" :clojars}
:aliases {"run-echo-example" ~(conj example-base-command "link.examples.echo")
"run-http-simple-example" ~(conj example-base-command "link.examples.http.simple")
"run-http-async-example" ~(conj example-base-command "link.examples.http.async")
"run-http-h2c-example" ~(conj example-base-command "link.examples.http.h2c")
"run-http-h2-example" ~(conj example-base-command "link.examples.http.h2")})
| |
959868e14a497d4cd795397fe21cca2985f5343c95e8829b73827e594683b7bb | jpmonettas/clindex | schema.clj | (ns clindex.schema)
(def schema
{
;;;;;;;;;;;;;;
;; Projects ;;
;;;;;;;;;;;;;;
;; A symbol with the project name for named dependencies or clindex/main-project for the project
;; being analyzed
:project/name {:db/cardinality :db.cardinality/one}
The project version as a string ( only maven version now )
:project/version {:db/cardinality :db.cardinality/one}
;; A collection of references to other projects which this one depends on
:project/depends {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many}
;; A collection of references to namespaces this project contains
:project/namespaces {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
;;;;;;;;;;;
;; Files ;;
;;;;;;;;;;;
;; A string with the file name, can be a local file or a jar url
:file/name {:db/cardinality :db.cardinality/one}
;;;;;;;;;;;;;;;;
;; Namespaces ;;
;;;;;;;;;;;;;;;;
;; A symbol with the namespace name
:namespace/name {:db/cardinality :db.cardinality/one}
;; A reference to the file that contains this namespace declaration
:namespace/file {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
;; A collection of references to vars this namespace defines
:namespace/vars {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
Namespace documentation string
:namespace/docstring {:db/cardinality :db.cardinality/one}
;; A collection of references to other namespaces which this depends on
:namespace/depends {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many}
;; A collection of references to specs alpha
:namespace/specs-alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
;; A collection of references to functions specs alpha
:namespace/fspecs-alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
;;;;;;;;;;
Vars ; ;
;;;;;;;;;;
;; A non namespaced symbol with the var name
:var/name {:db/cardinality :db.cardinality/one}
;; A integers containing the var definition coordinates
:var/line {:db/cardinality :db.cardinality/one}
:var/column {:db/cardinality :db.cardinality/one}
:var/end-column {:db/cardinality :db.cardinality/one}
;; True if the var is public in the namespace
:var/public? {:db/cardinality :db.cardinality/one}
A reference to function if this var is pointing to one
:var/function {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one :db/isComponent true}
;; A collection of references to var-ref, which are all the references pointing to this var
:var/refs {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
True if the var is pointing to a protocol definition , like ( defprotocol TheProtoVar ... )
:var/protocol? {:db/cardinality :db.cardinality/one}
;; A reference to the multimethod this var points to
:var/multi {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one :db/isComponent true}
Var documentation
:var/docstring {:db/cardinality :db.cardinality/one}
;;;;;;;;;;;;
;; Source ;;
;;;;;;;;;;;;
;; Source form. It contains all the data the clojure reader adds (:line, :column, etc) plus for
;; each symbol inside, if it points to a var is has its :var/id
:source/form {:db/cardinality :db.cardinality/one}
;; Source representation as it appears on the file, contains comments, newlines etc
:source/str {:db/cardinality :db.cardinality/one}
;;;;;;;;;;;;;;;
;; Functions ;;
;;;;;;;;;;;;;;;
;; True if this function is a macro
:function/macro? {:db/cardinality :db.cardinality/one}
;; When this is a protocol function, it points to the protocol definition var
:function/proto-var {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
A collection of argument vectors as strings , it is a collection because fns can have multiple arities
:function/args {:db/cardinality :db.cardinality/many}
;; A reference to the function spec (alpha version) (See :fspec.alpha/*)
:function/spec.alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
;; Functions also contanins `:source/form` and `:source/str`
;;;;;;;;;;;;;;;;;;
Multimethods ; ;
;;;;;;;;;;;;;;;;;;
;; The form used for dispatching
:multi/dispatch-form {:db/cardinality :db.cardinality/one}
;; A collection of references to multimethods that implement this defmulti
:multi/methods {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
;; The dispatch value as it appears on the defmethod
:multimethod/dispatch-val {:db/cardinality :db.cardinality/one}
Multimethods also contanins ` : source / form ` and ` : source / str `
;;;;;;;;;;;;;;;;;;;;
Var references ; ;
;;;;;;;;;;;;;;;;;;;;
;; A reference to the namespace in which this var-ref is found
:var-ref/namespace {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
;; The var reference coordinates
:var-ref/line {:db/cardinality :db.cardinality/one}
:var-ref/column {:db/cardinality :db.cardinality/one}
:var-ref/end-column {:db/cardinality :db.cardinality/one}
;; A reference to the function this var-ref is in
:var-ref/in-function {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
;;;;;;;;;;;;;;;;;;;;;;;;
Clojure spec alpha ; ;
;;;;;;;;;;;;;;;;;;;;;;;;
;; The spec key in the spec registry
:spec.alpha/key {:db/cardinality :db.cardinality/one}
;; spec.alpha and fspec.alpha also contanins `:source/form`
})
| null | https://raw.githubusercontent.com/jpmonettas/clindex/77097d80a23aa85d2ff50e55645a1452f2dcb3c0/src/clindex/schema.clj | clojure |
Projects ;;
A symbol with the project name for named dependencies or clindex/main-project for the project
being analyzed
A collection of references to other projects which this one depends on
A collection of references to namespaces this project contains
Files ;;
A string with the file name, can be a local file or a jar url
Namespaces ;;
A symbol with the namespace name
A reference to the file that contains this namespace declaration
A collection of references to vars this namespace defines
A collection of references to other namespaces which this depends on
A collection of references to specs alpha
A collection of references to functions specs alpha
;
A non namespaced symbol with the var name
A integers containing the var definition coordinates
True if the var is public in the namespace
A collection of references to var-ref, which are all the references pointing to this var
A reference to the multimethod this var points to
Source ;;
Source form. It contains all the data the clojure reader adds (:line, :column, etc) plus for
each symbol inside, if it points to a var is has its :var/id
Source representation as it appears on the file, contains comments, newlines etc
Functions ;;
True if this function is a macro
When this is a protocol function, it points to the protocol definition var
A reference to the function spec (alpha version) (See :fspec.alpha/*)
Functions also contanins `:source/form` and `:source/str`
;
The form used for dispatching
A collection of references to multimethods that implement this defmulti
The dispatch value as it appears on the defmethod
;
A reference to the namespace in which this var-ref is found
The var reference coordinates
A reference to the function this var-ref is in
;
The spec key in the spec registry
spec.alpha and fspec.alpha also contanins `:source/form` | (ns clindex.schema)
(def schema
{
:project/name {:db/cardinality :db.cardinality/one}
The project version as a string ( only maven version now )
:project/version {:db/cardinality :db.cardinality/one}
:project/depends {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many}
:project/namespaces {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
:file/name {:db/cardinality :db.cardinality/one}
:namespace/name {:db/cardinality :db.cardinality/one}
:namespace/file {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
:namespace/vars {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
Namespace documentation string
:namespace/docstring {:db/cardinality :db.cardinality/one}
:namespace/depends {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many}
:namespace/specs-alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
:namespace/fspecs-alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
:var/name {:db/cardinality :db.cardinality/one}
:var/line {:db/cardinality :db.cardinality/one}
:var/column {:db/cardinality :db.cardinality/one}
:var/end-column {:db/cardinality :db.cardinality/one}
:var/public? {:db/cardinality :db.cardinality/one}
A reference to function if this var is pointing to one
:var/function {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one :db/isComponent true}
:var/refs {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
True if the var is pointing to a protocol definition , like ( defprotocol TheProtoVar ... )
:var/protocol? {:db/cardinality :db.cardinality/one}
:var/multi {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one :db/isComponent true}
Var documentation
:var/docstring {:db/cardinality :db.cardinality/one}
:source/form {:db/cardinality :db.cardinality/one}
:source/str {:db/cardinality :db.cardinality/one}
:function/macro? {:db/cardinality :db.cardinality/one}
:function/proto-var {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
A collection of argument vectors as strings , it is a collection because fns can have multiple arities
:function/args {:db/cardinality :db.cardinality/many}
:function/spec.alpha {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
:multi/dispatch-form {:db/cardinality :db.cardinality/one}
:multi/methods {:db/valueType :db.type/ref :db/cardinality :db.cardinality/many :db/isComponent true}
:multimethod/dispatch-val {:db/cardinality :db.cardinality/one}
Multimethods also contanins ` : source / form ` and ` : source / str `
:var-ref/namespace {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
:var-ref/line {:db/cardinality :db.cardinality/one}
:var-ref/column {:db/cardinality :db.cardinality/one}
:var-ref/end-column {:db/cardinality :db.cardinality/one}
:var-ref/in-function {:db/valueType :db.type/ref :db/cardinality :db.cardinality/one}
:spec.alpha/key {:db/cardinality :db.cardinality/one}
})
|
5f5f0271b841ba1547167b8ba030a1cce76ae754fb079fe0dad68c840b03a71c | mini-monkey/mini-monkey | minimal_SUITE.erl | -module(minimal_SUITE).
-include_lib("common_test/include/ct.hrl").
-import(mm_test_tokens, [god_token/0]).
-import(mm_test_common, [setup/0]).
-export([all/0]).
-export([test_failed_auth/1,
test_god_token_auth/1,
test_successful_auth/1]).
all() -> [test_failed_auth,
test_god_token_auth,
test_successful_auth].
test_failed_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
Token = <<"guest">>,
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_failure()} =:= gen_tcp:recv(Sock, 0).
test_god_token_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
ok = gen_tcp:send(Sock, mm_encode:login(god_token())),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
test_successful_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
Token = <<"guest">>,
ok = mm_login:add_token(Token),
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
| null | https://raw.githubusercontent.com/mini-monkey/mini-monkey/4afa4385256c0f1d23db522c0725c3291a8c86c8/test/minimal_SUITE.erl | erlang | -module(minimal_SUITE).
-include_lib("common_test/include/ct.hrl").
-import(mm_test_tokens, [god_token/0]).
-import(mm_test_common, [setup/0]).
-export([all/0]).
-export([test_failed_auth/1,
test_god_token_auth/1,
test_successful_auth/1]).
all() -> [test_failed_auth,
test_god_token_auth,
test_successful_auth].
test_failed_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
Token = <<"guest">>,
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_failure()} =:= gen_tcp:recv(Sock, 0).
test_god_token_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
ok = gen_tcp:send(Sock, mm_encode:login(god_token())),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
test_successful_auth(_Config) ->
setup(),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary]),
Token = <<"guest">>,
ok = mm_login:add_token(Token),
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
| |
a91d065c2fa95af6af759fa648e4afc8b10e222f49f7be586369409f2ed84500 | emilaxelsson/syntactic | Tests.hs | import Test.Tasty
import qualified AlgorithmTests
import qualified NanoFeldsparTests
import qualified WellScopedTests
import qualified MonadTests
import qualified SyntaxTests
import qualified TH
tests = testGroup "AllTests"
[ SyntaxTests.tests
, AlgorithmTests.tests
, NanoFeldsparTests.tests
, WellScopedTests.tests
, MonadTests.tests
]
main = do
TH.main
defaultMain tests
| null | https://raw.githubusercontent.com/emilaxelsson/syntactic/c51258ed96d4e9704e5842ce15667e7d3e5b77d7/tests/Tests.hs | haskell | import Test.Tasty
import qualified AlgorithmTests
import qualified NanoFeldsparTests
import qualified WellScopedTests
import qualified MonadTests
import qualified SyntaxTests
import qualified TH
tests = testGroup "AllTests"
[ SyntaxTests.tests
, AlgorithmTests.tests
, NanoFeldsparTests.tests
, WellScopedTests.tests
, MonadTests.tests
]
main = do
TH.main
defaultMain tests
| |
902979c20fa5da60edf5eaa896e3e4812778f8189243a9a46de4cdaeb807364b | jkrukoff/llists | lfiles.erl | %%%-------------------------------------------------------------------
%%% @doc
%%% A lazily evaluated file module. This module provides replicas of
%%% functions from the kernel `file' and stdlib `io' modules designed
%%% to work with iterators as defined by the `llists' module.
%%%
%%% All iterators created by this module work by side effect, making
%%% them impure. As such, they should only be evaluated once.
%%%
%%% As there is no guarantee that an iterator will be completely
%%% evaluated, this module expects the lifecycle of the opened file
%%% process to be managed by the caller.
%%% @end
%%%-------------------------------------------------------------------
-module(lfiles).
%% API
-export([
Iterator construction .
read/2,
get_chars/3,
read_line/1,
get_line/2,
% Iterator evaluation.
write/2,
put_chars/2
]).
%%%===================================================================
%%% API
%%%===================================================================
%% @doc
%% Create an iterator that returns chunks of data from a file
referenced by ` IODevice ' of approximately ` Number '
%% bytes/characters.
%%
%% If the read fails, an error of form `{file_read_error, Reason}'
%% will be thrown by the iterator.
%% @end
%% @see file:read/2
-spec read(IODevice, Number) -> Iterator when
IODevice :: file:io_device(),
Number :: non_neg_integer(),
Iterator :: llists:iterator(Data),
Data :: string() | binary().
read(IODevice, Number) ->
file_read_iterator(fun() -> file:read(IODevice, Number) end).
%% @doc
%% Create an iterator that returns chunks of `Number' characters from
` IODevice ' , prompting each read with ` Prompt ' .
%%
%% If the get_chars call fails, an error of form
%% `{io_read_error, Reason}' will be thrown by the iterator.
%% @end
%% @see io:get_chars/3
-spec get_chars(IODevice, Prompt, Number) -> Iterator when
IODevice :: file:io_device(),
Prompt :: io:prompt(),
Number :: non_neg_integer(),
Iterator :: llists:iterator(Data),
Data :: string() | unicode:unicode_binary().
get_chars(IODevice, Prompt, Number) ->
io_read_iterator(fun() -> io:get_chars(IODevice, Prompt, Number) end).
%% @doc
%% Create an iterator that returns lines of data from a file
referenced by ` IODevice ' .
%%
%% The trailing linefeed (`\n') character is returned as part of the
%% line.
%%
%% If the read fails, an error of form `{file_read_error, Reason}'
%% will be thrown by the iterator.
%% @end
%% @see file:read_line/1
-spec read_line(IODevice) -> Iterator when
IODevice :: file:io_device(),
Iterator :: llists:iterator(Data),
Data :: string() | binary().
read_line(IODevice) ->
file_read_iterator(fun() -> file:read_line(IODevice) end).
%% @doc
%% Create an iterator that returns lines of data from a file
referenced by ` IODevice ' , prompting each read with ` Prompt ' .
%%
%% The trailing linefeed (`\n') character is returned as part of the
%% line.
%%
%% If the get_line call fails, an error of form
%% `{io_read_error, Reason}' will be thrown by the iterator.
%% @end
%% @see io:get_line/2
-spec get_line(IODevice, Prompt) -> Iterator when
IODevice :: file:io_device(),
Prompt :: io:prompt(),
Iterator :: llists:iterator(Data),
Data :: string() | unicode:unicode_binary().
get_line(IODevice, Prompt) ->
io_read_iterator(fun() -> io:get_line(IODevice, Prompt) end).
%% @doc
%% Fully evaluate `Iterator' and write the bytes returned to the file
referenced by ` IODevice ' .
%%
%% `ok' is returned on success, but if the write fails an error of
%% form `{error, Reason}' will be returned.
%%
%% The iterator will be fully evaluated, infinite iterators will never
%% return (or will fill up the disk and error!).
%% @end
%% @see file:write/2
-spec write(IODevice, Iterator) -> ok | {error, Reason} when
IODevice :: file:io_device(),
Iterator :: llists:iterator(file:io_data()),
Reason :: file:posix() | badarg | terminated.
write(IODevice, Iterator) ->
true = llists:is_iterator(Iterator),
write_loop(IODevice, llists:next(Iterator), ok).
%% @doc
%% Fully evaluate `Iterator' and write the characters returned to the
file referenced by ` IODevice ' .
%%
%% The iterator will be fully evaluated, infinite iterators will never
%% return (or will fill up the disk and error!).
%% @end
%% @see io:put_chars/2
-spec put_chars(IODevice, Iterator) -> ok when
IODevice :: file:io_device(),
Iterator :: llists:iterator(unicode:chardata()).
put_chars(IODevice, Iterator) ->
true = llists:is_iterator(Iterator),
llists:foreach(fun(CharData) -> ok = io:put_chars(IODevice, CharData) end, Iterator).
%%%===================================================================
%%% Internal Functions
%%%===================================================================
% Iterators don't have a way to propagate failure, so we'll throw an
% exception if the underlying read reports an error.
file_read_iterator(Read) ->
llists:unfold(
fun(undefined) ->
case Read() of
{ok, Data} ->
{Data, undefined};
eof ->
none;
{error, Reason} ->
throw({file_read_error, Reason})
end
end,
undefined
).
% Iterators don't have a way to propagate failure, so we'll throw an
% exception if the underlying read reports an error.
io_read_iterator(Read) ->
llists:unfold(
fun(undefined) ->
case Read() of
eof ->
none;
{error, Reason} ->
throw({io_read_error, Reason});
Data ->
{Data, undefined}
end
end,
undefined
).
write_loop(_IODevice, _Iterator, {error, Reason}) ->
{error, Reason};
write_loop(_IODevice, [], ok) ->
ok;
write_loop(IODevice, [Bytes | Iterator], ok) ->
write_loop(IODevice, llists:next(Iterator), file:write(IODevice, Bytes)).
| null | https://raw.githubusercontent.com/jkrukoff/llists/2e9b756b81ff85d7e6230612c065aceb9ebed4b4/src/lfiles.erl | erlang | -------------------------------------------------------------------
@doc
A lazily evaluated file module. This module provides replicas of
functions from the kernel `file' and stdlib `io' modules designed
to work with iterators as defined by the `llists' module.
All iterators created by this module work by side effect, making
them impure. As such, they should only be evaluated once.
As there is no guarantee that an iterator will be completely
evaluated, this module expects the lifecycle of the opened file
process to be managed by the caller.
@end
-------------------------------------------------------------------
API
Iterator evaluation.
===================================================================
API
===================================================================
@doc
Create an iterator that returns chunks of data from a file
bytes/characters.
If the read fails, an error of form `{file_read_error, Reason}'
will be thrown by the iterator.
@end
@see file:read/2
@doc
Create an iterator that returns chunks of `Number' characters from
If the get_chars call fails, an error of form
`{io_read_error, Reason}' will be thrown by the iterator.
@end
@see io:get_chars/3
@doc
Create an iterator that returns lines of data from a file
The trailing linefeed (`\n') character is returned as part of the
line.
If the read fails, an error of form `{file_read_error, Reason}'
will be thrown by the iterator.
@end
@see file:read_line/1
@doc
Create an iterator that returns lines of data from a file
The trailing linefeed (`\n') character is returned as part of the
line.
If the get_line call fails, an error of form
`{io_read_error, Reason}' will be thrown by the iterator.
@end
@see io:get_line/2
@doc
Fully evaluate `Iterator' and write the bytes returned to the file
`ok' is returned on success, but if the write fails an error of
form `{error, Reason}' will be returned.
The iterator will be fully evaluated, infinite iterators will never
return (or will fill up the disk and error!).
@end
@see file:write/2
@doc
Fully evaluate `Iterator' and write the characters returned to the
The iterator will be fully evaluated, infinite iterators will never
return (or will fill up the disk and error!).
@end
@see io:put_chars/2
===================================================================
Internal Functions
===================================================================
Iterators don't have a way to propagate failure, so we'll throw an
exception if the underlying read reports an error.
Iterators don't have a way to propagate failure, so we'll throw an
exception if the underlying read reports an error. | -module(lfiles).
-export([
Iterator construction .
read/2,
get_chars/3,
read_line/1,
get_line/2,
write/2,
put_chars/2
]).
referenced by ` IODevice ' of approximately ` Number '
-spec read(IODevice, Number) -> Iterator when
IODevice :: file:io_device(),
Number :: non_neg_integer(),
Iterator :: llists:iterator(Data),
Data :: string() | binary().
read(IODevice, Number) ->
file_read_iterator(fun() -> file:read(IODevice, Number) end).
` IODevice ' , prompting each read with ` Prompt ' .
-spec get_chars(IODevice, Prompt, Number) -> Iterator when
IODevice :: file:io_device(),
Prompt :: io:prompt(),
Number :: non_neg_integer(),
Iterator :: llists:iterator(Data),
Data :: string() | unicode:unicode_binary().
get_chars(IODevice, Prompt, Number) ->
io_read_iterator(fun() -> io:get_chars(IODevice, Prompt, Number) end).
referenced by ` IODevice ' .
-spec read_line(IODevice) -> Iterator when
IODevice :: file:io_device(),
Iterator :: llists:iterator(Data),
Data :: string() | binary().
read_line(IODevice) ->
file_read_iterator(fun() -> file:read_line(IODevice) end).
referenced by ` IODevice ' , prompting each read with ` Prompt ' .
-spec get_line(IODevice, Prompt) -> Iterator when
IODevice :: file:io_device(),
Prompt :: io:prompt(),
Iterator :: llists:iterator(Data),
Data :: string() | unicode:unicode_binary().
get_line(IODevice, Prompt) ->
io_read_iterator(fun() -> io:get_line(IODevice, Prompt) end).
referenced by ` IODevice ' .
-spec write(IODevice, Iterator) -> ok | {error, Reason} when
IODevice :: file:io_device(),
Iterator :: llists:iterator(file:io_data()),
Reason :: file:posix() | badarg | terminated.
write(IODevice, Iterator) ->
true = llists:is_iterator(Iterator),
write_loop(IODevice, llists:next(Iterator), ok).
file referenced by ` IODevice ' .
-spec put_chars(IODevice, Iterator) -> ok when
IODevice :: file:io_device(),
Iterator :: llists:iterator(unicode:chardata()).
put_chars(IODevice, Iterator) ->
true = llists:is_iterator(Iterator),
llists:foreach(fun(CharData) -> ok = io:put_chars(IODevice, CharData) end, Iterator).
file_read_iterator(Read) ->
llists:unfold(
fun(undefined) ->
case Read() of
{ok, Data} ->
{Data, undefined};
eof ->
none;
{error, Reason} ->
throw({file_read_error, Reason})
end
end,
undefined
).
io_read_iterator(Read) ->
llists:unfold(
fun(undefined) ->
case Read() of
eof ->
none;
{error, Reason} ->
throw({io_read_error, Reason});
Data ->
{Data, undefined}
end
end,
undefined
).
write_loop(_IODevice, _Iterator, {error, Reason}) ->
{error, Reason};
write_loop(_IODevice, [], ok) ->
ok;
write_loop(IODevice, [Bytes | Iterator], ok) ->
write_loop(IODevice, llists:next(Iterator), file:write(IODevice, Bytes)).
|
5230d798dbde1491cc2139b7eae4c49d04de01cd2d9a2a4cc1308c1f9da11a23 | typelead/eta | T1470.hs | { - # OPTIONS_GHC -fno - warn - redundant - constraints # - }
# LANGUAGE MultiParamTypeClasses , FlexibleContexts , FlexibleInstances , UndecidableInstances , KindSignatures #
-- Trac #1470
module Foo where
class Sat a
class Data (ctx :: * -> *) a
instance Sat (ctx Char) => Data ctx Char
instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
class Data FooD a => Foo a
data FooD a = FooD
instance Foo t => Sat (FooD t)
instance {-# OVERLAPPABLE #-} Data FooD a => Foo a
instance {-# OVERLAPS #-} Foo a => Foo [a]
instance {-# OVERLAPPING #-} Foo [Char]
Given : Foo a ,
and its superclasses : Data FooD a
Want superclass : Data FooD [ a ]
by instance Data FooD [ a ]
want : Sat ( FooD [ a ] )
Data FooD a -- We have this
by instance Sat ( FooD t )
want : [ a ]
BUT THIS INSTANCE OVERLAPS
Given: Foo a,
and its superclasses: Data FooD a
Want superclass: Data FooD [a]
by instance Data FooD [a]
want: Sat (FooD [a])
Data FooD a -- We have this
by instance Sat (FooD t)
want: Foo [a]
BUT THIS INSTANCE OVERLAPS
-}
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/T1470.hs | haskell | Trac #1470
# OVERLAPPABLE #
# OVERLAPS #
# OVERLAPPING #
We have this
We have this | { - # OPTIONS_GHC -fno - warn - redundant - constraints # - }
# LANGUAGE MultiParamTypeClasses , FlexibleContexts , FlexibleInstances , UndecidableInstances , KindSignatures #
module Foo where
class Sat a
class Data (ctx :: * -> *) a
instance Sat (ctx Char) => Data ctx Char
instance (Sat (ctx [a]), Data ctx a) => Data ctx [a]
class Data FooD a => Foo a
data FooD a = FooD
instance Foo t => Sat (FooD t)
Given : Foo a ,
and its superclasses : Data FooD a
Want superclass : Data FooD [ a ]
by instance Data FooD [ a ]
want : Sat ( FooD [ a ] )
by instance Sat ( FooD t )
want : [ a ]
BUT THIS INSTANCE OVERLAPS
Given: Foo a,
and its superclasses: Data FooD a
Want superclass: Data FooD [a]
by instance Data FooD [a]
want: Sat (FooD [a])
by instance Sat (FooD t)
want: Foo [a]
BUT THIS INSTANCE OVERLAPS
-}
|
c2c78ce39b78906cb8f1e2b28f8fcda6854c2138b2d684ae00b64c65c93da6a5 | fwcd/curry-language-server | CodeAction.hs | # LANGUAGE FlexibleInstances , OverloadedStrings #
module Curry.LanguageServer.Handlers.CodeAction (codeActionHandler) where
Curry Compiler Libraries + Dependencies
import qualified Curry.Syntax as CS
import qualified Base.Types as CT
import Control.Lens ((^.))
import Control.Monad (guard)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Maybe (runMaybeT)
import qualified Curry.LanguageServer.Index.Store as I
import Curry.LanguageServer.Monad
import Curry.LanguageServer.Utils.Convert (currySpanInfo2Uri, currySpanInfo2Range, ppToText)
import Curry.LanguageServer.Utils.General (rangeOverlaps)
import Curry.LanguageServer.Utils.Sema (untypedTopLevelDecls)
import Curry.LanguageServer.Utils.Uri (normalizeUriWithPath)
import qualified Data.Aeson as A
import Data.Maybe (fromMaybe, maybeToList)
import qualified Language.LSP.Server as S
import qualified Language.LSP.Types as J
import qualified Language.LSP.Types.Lens as J
import System.Log.Logger
codeActionHandler :: S.Handlers LSM
codeActionHandler = S.requestHandler J.STextDocumentCodeAction $ \req responder -> do
liftIO $ debugM "cls.codeAction" "Processing code action request"
let J.CodeActionParams _ _ doc range _ = req ^. J.params
uri = doc ^. J.uri
normUri <- liftIO $ normalizeUriWithPath uri
actions <- runMaybeT $ do
entry <- I.getModule normUri
liftIO $ fetchCodeActions range entry
responder $ Right $ J.List $ J.InR <$> fromMaybe [] actions
fetchCodeActions :: J.Range -> I.ModuleStoreEntry -> IO [J.CodeAction]
fetchCodeActions range entry = do
actions <- maybe (pure []) (codeActions range) $ I.mseModuleAST entry
debugM "cls.codeAction" $ "Found " ++ show (length actions) ++ " code action(s)"
return actions
class HasCodeActions s where
codeActions :: J.Range -> s -> IO [J.CodeAction]
instance HasCodeActions (CS.Module (Maybe CT.PredType)) where
codeActions range mdl@(CS.Module spi _ _ _ _ _ _) = do
maybeUri <- liftIO $ runMaybeT (currySpanInfo2Uri spi)
-- TODO: Attach diagnostics, ideally the frontend could emit these
-- quick fixes along with the warning messages?
let typeHintActions = do
(spi', i, tp) <- untypedTopLevelDecls mdl
t <- maybeToList tp
range' <- maybeToList $ currySpanInfo2Range spi'
guard $ rangeOverlaps range range'
uri <- maybeToList maybeUri
-- TODO: Move the command identifier ('decl.applyTypeHint') to some
-- central place to avoid repetition.
let text = ppToText i <> " :: " <> ppToText t
args = [A.toJSON uri, A.toJSON $ range' ^. J.start, A.toJSON text]
command = J.Command text "decl.applyTypeHint" $ Just $ J.List args
caKind = J.CodeActionQuickFix
isPreferred = True
lens = J.CodeAction ("Add type annotation '" <> text <> "'") (Just caKind) Nothing (Just isPreferred) Nothing Nothing (Just command) Nothing
return lens
return typeHintActions
| null | https://raw.githubusercontent.com/fwcd/curry-language-server/915cd2e82381612c93b220263429304017a24084/src/Curry/LanguageServer/Handlers/CodeAction.hs | haskell | TODO: Attach diagnostics, ideally the frontend could emit these
quick fixes along with the warning messages?
TODO: Move the command identifier ('decl.applyTypeHint') to some
central place to avoid repetition. | # LANGUAGE FlexibleInstances , OverloadedStrings #
module Curry.LanguageServer.Handlers.CodeAction (codeActionHandler) where
Curry Compiler Libraries + Dependencies
import qualified Curry.Syntax as CS
import qualified Base.Types as CT
import Control.Lens ((^.))
import Control.Monad (guard)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Maybe (runMaybeT)
import qualified Curry.LanguageServer.Index.Store as I
import Curry.LanguageServer.Monad
import Curry.LanguageServer.Utils.Convert (currySpanInfo2Uri, currySpanInfo2Range, ppToText)
import Curry.LanguageServer.Utils.General (rangeOverlaps)
import Curry.LanguageServer.Utils.Sema (untypedTopLevelDecls)
import Curry.LanguageServer.Utils.Uri (normalizeUriWithPath)
import qualified Data.Aeson as A
import Data.Maybe (fromMaybe, maybeToList)
import qualified Language.LSP.Server as S
import qualified Language.LSP.Types as J
import qualified Language.LSP.Types.Lens as J
import System.Log.Logger
codeActionHandler :: S.Handlers LSM
codeActionHandler = S.requestHandler J.STextDocumentCodeAction $ \req responder -> do
liftIO $ debugM "cls.codeAction" "Processing code action request"
let J.CodeActionParams _ _ doc range _ = req ^. J.params
uri = doc ^. J.uri
normUri <- liftIO $ normalizeUriWithPath uri
actions <- runMaybeT $ do
entry <- I.getModule normUri
liftIO $ fetchCodeActions range entry
responder $ Right $ J.List $ J.InR <$> fromMaybe [] actions
fetchCodeActions :: J.Range -> I.ModuleStoreEntry -> IO [J.CodeAction]
fetchCodeActions range entry = do
actions <- maybe (pure []) (codeActions range) $ I.mseModuleAST entry
debugM "cls.codeAction" $ "Found " ++ show (length actions) ++ " code action(s)"
return actions
class HasCodeActions s where
codeActions :: J.Range -> s -> IO [J.CodeAction]
instance HasCodeActions (CS.Module (Maybe CT.PredType)) where
codeActions range mdl@(CS.Module spi _ _ _ _ _ _) = do
maybeUri <- liftIO $ runMaybeT (currySpanInfo2Uri spi)
let typeHintActions = do
(spi', i, tp) <- untypedTopLevelDecls mdl
t <- maybeToList tp
range' <- maybeToList $ currySpanInfo2Range spi'
guard $ rangeOverlaps range range'
uri <- maybeToList maybeUri
let text = ppToText i <> " :: " <> ppToText t
args = [A.toJSON uri, A.toJSON $ range' ^. J.start, A.toJSON text]
command = J.Command text "decl.applyTypeHint" $ Just $ J.List args
caKind = J.CodeActionQuickFix
isPreferred = True
lens = J.CodeAction ("Add type annotation '" <> text <> "'") (Just caKind) Nothing (Just isPreferred) Nothing Nothing (Just command) Nothing
return lens
return typeHintActions
|
442ccc26366fa3d2f84f58e71708725a55b2d200da43918661ed4feda48d3e62 | fukamachi/safety-params | number.lisp | (defpackage #:safety-params/fn/number
(:use #:cl)
(:import-from #:alexandria
#:positive-integer-p
#:negative-integer-p
#:positive-float-p
#:negative-float-p)
(:export #:integerp
#:positive-integer-p
#:negative-integer-p
#:integer-string-p
#:positive-integer-string-p
#:negative-integer-string-p
#:number-string-p
#:positive-number-string-p
#:negative-number-string-p
#:positive-float-string-p
#:negative-float-string-p))
(in-package #:safety-params/fn/number)
(defun integer-char-p (char)
(and (characterp char)
(<= (char-code #\0) (char-code char) (char-code #\9))))
(defun integer-string-p (value)
(and (stringp value)
(< 0 (length value))
(let ((start (if (and (or (char= (aref value 0) #\-)
(char= (aref value 0) #\+))
(< 1 (length value)))
1
0)))
(loop for i from start below (length value)
unless (integer-char-p (aref value i))
do (return nil)
finally
(return t)))))
(defun positive-integer-string-p (value)
(and (integer-string-p value)
(< 0 (read-from-string value))))
(defun negative-integer-string-p (value)
(and (integer-string-p value)
(< (read-from-string value) 0)))
(defun number-string-p (string)
(check-type string string)
(when (zerop (length string))
(return-from number-string-p nil))
(let ((start
(if (or (char= (aref string 0) #\-)
(char= (aref string 0) #\+))
(if (< 1 (length string))
1
(return-from number-string-p nil))
0))
(end (length string)))
(declare (type integer start))
(let ((dot-read nil)
(slash-read nil))
(do ((i start (1+ i)))
((= end i))
(let ((char (aref string i)))
(cond
((digit-char-p char))
((char= char #\.)
(when (or dot-read
slash-read)
(return-from number-string-p nil))
(setq dot-read i))
((and (char= char #\/)
(not (= i start)))
(when (or dot-read
slash-read)
(return-from number-string-p nil))
(setq slash-read i))
(t (return-from number-string-p nil)))))
(or (not slash-read)
(and (/= slash-read end)
(find-if (lambda (v) (char/= v #\0))
(subseq string (1+ slash-read)))
t)))))
(defun positive-number-string-p (value)
(and (number-string-p value)
(< 0 (read-from-string value))))
(defun negative-number-string-p (value)
(and (number-string-p value)
(< (read-from-string value) 0)))
(defun positive-float-string-p (value)
(and (number-string-p value)
(positive-float-p (read-from-string value))))
(defun negative-float-string-p (value)
(and (number-string-p value)
(negative-float-p (read-from-string value))))
(defmacro number-greater-than (value)
)
| null | https://raw.githubusercontent.com/fukamachi/safety-params/13e30916dfce130a6b35c22cd7969a9cba20a8f0/src/fn/number.lisp | lisp | (defpackage #:safety-params/fn/number
(:use #:cl)
(:import-from #:alexandria
#:positive-integer-p
#:negative-integer-p
#:positive-float-p
#:negative-float-p)
(:export #:integerp
#:positive-integer-p
#:negative-integer-p
#:integer-string-p
#:positive-integer-string-p
#:negative-integer-string-p
#:number-string-p
#:positive-number-string-p
#:negative-number-string-p
#:positive-float-string-p
#:negative-float-string-p))
(in-package #:safety-params/fn/number)
(defun integer-char-p (char)
(and (characterp char)
(<= (char-code #\0) (char-code char) (char-code #\9))))
(defun integer-string-p (value)
(and (stringp value)
(< 0 (length value))
(let ((start (if (and (or (char= (aref value 0) #\-)
(char= (aref value 0) #\+))
(< 1 (length value)))
1
0)))
(loop for i from start below (length value)
unless (integer-char-p (aref value i))
do (return nil)
finally
(return t)))))
(defun positive-integer-string-p (value)
(and (integer-string-p value)
(< 0 (read-from-string value))))
(defun negative-integer-string-p (value)
(and (integer-string-p value)
(< (read-from-string value) 0)))
(defun number-string-p (string)
(check-type string string)
(when (zerop (length string))
(return-from number-string-p nil))
(let ((start
(if (or (char= (aref string 0) #\-)
(char= (aref string 0) #\+))
(if (< 1 (length string))
1
(return-from number-string-p nil))
0))
(end (length string)))
(declare (type integer start))
(let ((dot-read nil)
(slash-read nil))
(do ((i start (1+ i)))
((= end i))
(let ((char (aref string i)))
(cond
((digit-char-p char))
((char= char #\.)
(when (or dot-read
slash-read)
(return-from number-string-p nil))
(setq dot-read i))
((and (char= char #\/)
(not (= i start)))
(when (or dot-read
slash-read)
(return-from number-string-p nil))
(setq slash-read i))
(t (return-from number-string-p nil)))))
(or (not slash-read)
(and (/= slash-read end)
(find-if (lambda (v) (char/= v #\0))
(subseq string (1+ slash-read)))
t)))))
(defun positive-number-string-p (value)
(and (number-string-p value)
(< 0 (read-from-string value))))
(defun negative-number-string-p (value)
(and (number-string-p value)
(< (read-from-string value) 0)))
(defun positive-float-string-p (value)
(and (number-string-p value)
(positive-float-p (read-from-string value))))
(defun negative-float-string-p (value)
(and (number-string-p value)
(negative-float-p (read-from-string value))))
(defmacro number-greater-than (value)
)
| |
31d11fefda1b3ac05055b2901caf303773ef4ff0d7242d12e8777af9e2ee160f | min-nguyen/prob-fx | Main.hs | module Main (main) where
import SIR
import LinRegr
import LDA
import Test.Expected
import Test.HUnit
import Sampler
import System.Exit
testSimLinRegr :: Test
testSimLinRegr = TestCase $ do
output <- sampleIOFixed simulateLinRegr
assertEqual "Testing simulateLinRegr" simLinRegrExpected output
testLwLinRegr :: Test
testLwLinRegr = TestCase $ do
output <- sampleIOFixed inferLwLinRegr
assertEqual "Testing inferLwLinRegr" lwLinRegrExpected output
testMhLinRegr :: Test
testMhLinRegr = TestCase $ do
output <- sampleIOFixed inferMhLinRegr
assertEqual "Testing inferMhLinRegr" mhLinRegrExpected output
testSimSIR :: Test
testSimSIR = TestCase $ do
output <- sampleIOFixed simulateSIR
assertEqual "Testing simulateSIR" simSIRExpected output
testMhSIR :: Test
testMhSIR = TestCase $ do
output <- sampleIOFixed inferSIR
assertEqual "Testing inferSIR" mhSIRExpected output
testSimLDA :: Test
testSimLDA = TestCase $ do
output <- sampleIOFixed simLDA
assertEqual "Testing simLDA" simLDAExpected output
testMhPredLDA :: Test
testMhPredLDA = TestCase $ do
output <- sampleIOFixed mhLDA
assertEqual "Testing mhLDA" mhPredLDAExpected output
tests :: Test
tests = TestList [testSimLinRegr, testLwLinRegr, testMhLinRegr, testSimSIR, testMhSIR, testSimLDA, testMhPredLDA]
main :: IO ()
main = do
Counts cases tried errors failures <- runTestTT tests
if errors + failures == 0
then
exitSuccess
else do
exitWith (ExitFailure 1) | null | https://raw.githubusercontent.com/min-nguyen/prob-fx/870a341f344638887ac63f6e6f7e3a352a03ef62/examples/Test/Main.hs | haskell | module Main (main) where
import SIR
import LinRegr
import LDA
import Test.Expected
import Test.HUnit
import Sampler
import System.Exit
testSimLinRegr :: Test
testSimLinRegr = TestCase $ do
output <- sampleIOFixed simulateLinRegr
assertEqual "Testing simulateLinRegr" simLinRegrExpected output
testLwLinRegr :: Test
testLwLinRegr = TestCase $ do
output <- sampleIOFixed inferLwLinRegr
assertEqual "Testing inferLwLinRegr" lwLinRegrExpected output
testMhLinRegr :: Test
testMhLinRegr = TestCase $ do
output <- sampleIOFixed inferMhLinRegr
assertEqual "Testing inferMhLinRegr" mhLinRegrExpected output
testSimSIR :: Test
testSimSIR = TestCase $ do
output <- sampleIOFixed simulateSIR
assertEqual "Testing simulateSIR" simSIRExpected output
testMhSIR :: Test
testMhSIR = TestCase $ do
output <- sampleIOFixed inferSIR
assertEqual "Testing inferSIR" mhSIRExpected output
testSimLDA :: Test
testSimLDA = TestCase $ do
output <- sampleIOFixed simLDA
assertEqual "Testing simLDA" simLDAExpected output
testMhPredLDA :: Test
testMhPredLDA = TestCase $ do
output <- sampleIOFixed mhLDA
assertEqual "Testing mhLDA" mhPredLDAExpected output
tests :: Test
tests = TestList [testSimLinRegr, testLwLinRegr, testMhLinRegr, testSimSIR, testMhSIR, testSimLDA, testMhPredLDA]
main :: IO ()
main = do
Counts cases tried errors failures <- runTestTT tests
if errors + failures == 0
then
exitSuccess
else do
exitWith (ExitFailure 1) | |
32fbf9f05f475185aee3baa7dc7df6eda137661d15441ba68b9da80e551d7e24 | show-matz/CL-STL | cl-stl-move-iterator.lisp |
(in-package :cl-stl)
#-cl-stl-0x98
(declaim (inline make_move_iterator))
;;------------------------------------------------------------------------------
;;
;; move iterator classes
;;
;;------------------------------------------------------------------------------
#-cl-stl-0x98
(progn
(defclass move-iterator_in (input_iterator)
((itr :initform nil
:initarg :iterator
:accessor __moveitr-iterator)
(rm :type :remove-reference
:initarg :rm-ref
:accessor __moveitr-rm-ref)))
(defclass move-iterator_fwd ( forward_iterator move-iterator_in ) ())
(defclass move-iterator_bid (bidirectional_iterator move-iterator_fwd) ())
(defclass move-iterator_rdm ( randomaccess_iterator move-iterator_bid) ()))
#-cl-stl-0x98
(macrolet ((movitr-ctor (param-type itr-type)
`(define-constructor move-iterator ((itr ,param-type))
(let* ((itr (clone itr))
(rm (opr:move (_* itr))))
(make-instance ',itr-type :iterator itr :rm-ref rm)))))
(movitr-ctor input_iterator move-iterator_in)
(movitr-ctor forward_iterator move-iterator_fwd)
(movitr-ctor bidirectional_iterator move-iterator_bid)
(movitr-ctor randomaccess_iterator move-iterator_rdm))
#-cl-stl-0x98
(defun make_move_iterator (itr)
(new stl::move-iterator itr))
;;------------------------------------------------------------------------------
implementation of move - iterator_in
;;------------------------------------------------------------------------------
#-cl-stl-0x98
(defmethod operator_= ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_= (__moveitr-iterator itr1) (__moveitr-iterator itr2))
itr1)
#-cl-stl-0x98
(defmethod operator_clone ((itr move-iterator_in))
(let* ((tmp (clone (__moveitr-iterator itr)))
(rm (opr:move (_* tmp))))
(make-instance (type-of itr) :iterator tmp :rm-ref rm)))
#-cl-stl-0x98
(defmethod operator_* ((itr move-iterator_in))
(__moveitr-rm-ref itr))
#-cl-stl-0x98
(defmethod operator_++ ((itr move-iterator_in))
(setf (__moveitr-iterator itr)
(operator_++ (__moveitr-iterator itr)))
itr)
#-cl-stl-0x98
(defmethod operator_== ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_== (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_/= ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_/= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod base ((itr move-iterator_in))
(clone (__moveitr-iterator itr)))
;;------------------------------------------------------------------------------
;; implementation of move-iterator_fwd
;;------------------------------------------------------------------------------
#-cl-stl-0x98
(defmethod (setf operator_*) (new-val (itr move-iterator_fwd))
(setf (_* (__moveitr-iterator itr)) new-val)
new-val)
#-cl-stl-0x98
(defmethod advance ((itr move-iterator_fwd) (n integer))
(advance (__moveitr-iterator itr) n)
nil)
#-cl-stl-0x98
(defmethod distance ((itr1 move-iterator_fwd) (itr2 move-iterator_fwd))
(distance (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
;;------------------------------------------------------------------------------
;; implementation of move-iterator_bid
;;------------------------------------------------------------------------------
#-cl-stl-0x98
(defmethod operator_-- ((itr move-iterator_bid))
(setf (__moveitr-iterator itr)
(operator_-- (__moveitr-iterator itr)))
itr)
;; CAN'T creating reverse iterator.
#-cl-stl-0x98
(define-constructor reverse_iterator ((itr move-iterator_bid))
(error 'type-mismatch :what "reverse_iterator can't create from move-iterator"))
;;------------------------------------------------------------------------------
;; implementation of move-iterator_rdm
;;------------------------------------------------------------------------------
#-cl-stl-0x98
(defmethod operator_< ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_< (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_<= ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_<= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_> ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_> (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_>= ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_>= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_+ ((itr move-iterator_rdm) (n integer))
(let ((r (clone itr)))
(advance r n)
r))
#-cl-stl-0x98
(defmethod operator_+= ((itr move-iterator_rdm) (n integer))
(advance itr n)
itr)
#-cl-stl-0x98
(defmethod operator_- ((itr move-iterator_rdm) (n integer))
(let ((r (clone itr)))
(advance r (* -1 n))
r))
#-cl-stl-0x98
(defmethod operator_- ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_- (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_-= ((itr move-iterator_rdm) (n integer))
(advance itr (* -1 n))
itr)
#-cl-stl-0x98
(defmethod operator_[] ((itr move-iterator_rdm) (idx integer))
(opr:move (_[] (__moveitr-iterator itr) idx)))
#-cl-stl-0x98
(defmethod (setf operator_[]) (new-val (itr move-iterator_rdm) (idx integer))
(_= (_[] (__moveitr-iterator itr) idx) new-val)
new-val)
;; CAN'T creating reverse iterator.
#-cl-stl-0x98
(define-constructor reverse_iterator ((itr move-iterator_rdm))
(error 'type-mismatch :what "reverse_iterator can't create from move-iterator"))
| null | https://raw.githubusercontent.com/show-matz/CL-STL/c6ffeac2815fa933121bc4c8b331d9c3516dff88/src/cl-stl-move-iterator.lisp | lisp | ------------------------------------------------------------------------------
move iterator classes
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
implementation of move-iterator_fwd
------------------------------------------------------------------------------
------------------------------------------------------------------------------
implementation of move-iterator_bid
------------------------------------------------------------------------------
CAN'T creating reverse iterator.
------------------------------------------------------------------------------
implementation of move-iterator_rdm
------------------------------------------------------------------------------
CAN'T creating reverse iterator. |
(in-package :cl-stl)
#-cl-stl-0x98
(declaim (inline make_move_iterator))
#-cl-stl-0x98
(progn
(defclass move-iterator_in (input_iterator)
((itr :initform nil
:initarg :iterator
:accessor __moveitr-iterator)
(rm :type :remove-reference
:initarg :rm-ref
:accessor __moveitr-rm-ref)))
(defclass move-iterator_fwd ( forward_iterator move-iterator_in ) ())
(defclass move-iterator_bid (bidirectional_iterator move-iterator_fwd) ())
(defclass move-iterator_rdm ( randomaccess_iterator move-iterator_bid) ()))
#-cl-stl-0x98
(macrolet ((movitr-ctor (param-type itr-type)
`(define-constructor move-iterator ((itr ,param-type))
(let* ((itr (clone itr))
(rm (opr:move (_* itr))))
(make-instance ',itr-type :iterator itr :rm-ref rm)))))
(movitr-ctor input_iterator move-iterator_in)
(movitr-ctor forward_iterator move-iterator_fwd)
(movitr-ctor bidirectional_iterator move-iterator_bid)
(movitr-ctor randomaccess_iterator move-iterator_rdm))
#-cl-stl-0x98
(defun make_move_iterator (itr)
(new stl::move-iterator itr))
implementation of move - iterator_in
#-cl-stl-0x98
(defmethod operator_= ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_= (__moveitr-iterator itr1) (__moveitr-iterator itr2))
itr1)
#-cl-stl-0x98
(defmethod operator_clone ((itr move-iterator_in))
(let* ((tmp (clone (__moveitr-iterator itr)))
(rm (opr:move (_* tmp))))
(make-instance (type-of itr) :iterator tmp :rm-ref rm)))
#-cl-stl-0x98
(defmethod operator_* ((itr move-iterator_in))
(__moveitr-rm-ref itr))
#-cl-stl-0x98
(defmethod operator_++ ((itr move-iterator_in))
(setf (__moveitr-iterator itr)
(operator_++ (__moveitr-iterator itr)))
itr)
#-cl-stl-0x98
(defmethod operator_== ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_== (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_/= ((itr1 move-iterator_in) (itr2 move-iterator_in))
(_/= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod base ((itr move-iterator_in))
(clone (__moveitr-iterator itr)))
#-cl-stl-0x98
(defmethod (setf operator_*) (new-val (itr move-iterator_fwd))
(setf (_* (__moveitr-iterator itr)) new-val)
new-val)
#-cl-stl-0x98
(defmethod advance ((itr move-iterator_fwd) (n integer))
(advance (__moveitr-iterator itr) n)
nil)
#-cl-stl-0x98
(defmethod distance ((itr1 move-iterator_fwd) (itr2 move-iterator_fwd))
(distance (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_-- ((itr move-iterator_bid))
(setf (__moveitr-iterator itr)
(operator_-- (__moveitr-iterator itr)))
itr)
#-cl-stl-0x98
(define-constructor reverse_iterator ((itr move-iterator_bid))
(error 'type-mismatch :what "reverse_iterator can't create from move-iterator"))
#-cl-stl-0x98
(defmethod operator_< ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_< (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_<= ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_<= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_> ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_> (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_>= ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_>= (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_+ ((itr move-iterator_rdm) (n integer))
(let ((r (clone itr)))
(advance r n)
r))
#-cl-stl-0x98
(defmethod operator_+= ((itr move-iterator_rdm) (n integer))
(advance itr n)
itr)
#-cl-stl-0x98
(defmethod operator_- ((itr move-iterator_rdm) (n integer))
(let ((r (clone itr)))
(advance r (* -1 n))
r))
#-cl-stl-0x98
(defmethod operator_- ((itr1 move-iterator_rdm) (itr2 move-iterator_rdm))
(_- (__moveitr-iterator itr1) (__moveitr-iterator itr2)))
#-cl-stl-0x98
(defmethod operator_-= ((itr move-iterator_rdm) (n integer))
(advance itr (* -1 n))
itr)
#-cl-stl-0x98
(defmethod operator_[] ((itr move-iterator_rdm) (idx integer))
(opr:move (_[] (__moveitr-iterator itr) idx)))
#-cl-stl-0x98
(defmethod (setf operator_[]) (new-val (itr move-iterator_rdm) (idx integer))
(_= (_[] (__moveitr-iterator itr) idx) new-val)
new-val)
#-cl-stl-0x98
(define-constructor reverse_iterator ((itr move-iterator_rdm))
(error 'type-mismatch :what "reverse_iterator can't create from move-iterator"))
|
c3170866077e6b477b847416d2425e57fa067527ac0dd10d0f560c621c537479 | conal/Fran | Force.hs |
The Forceable class containing just one function force . This provides
hyperstrict evaluation by forcing the whole data structure to normal form
as opposed to just whnf . It is normally used in conjunction with seq ,
e.g.
force x ` seq ` E
to ensure that x is evaluated to normal form before E is evaluated . Note
that force inside a definition will not force anything until the top level
is required , i.e. the following will not force x until the value of x is
needed ,
.... ( force x ) ... -- Does not force x until x is needed , probably not useful .
Finally , only structured types require forcing because when the value of a
simple type is needed , and so it is evaluated to whnf , it actually
evaluates all the way to normal form . Hence instances of force for simple
types are just the identity .
hyperstrict evaluation by forcing the whole data structure to normal form
as opposed to just whnf. It is normally used in conjunction with seq,
e.g.
force x `seq` E
to ensure that x is evaluated to normal form before E is evaluated. Note
that force inside a definition will not force anything until the top level
is required, i.e. the following will not force x until the value of x is
needed,
.... (force x) ... -- Does not force x until x is needed, probably not useful.
Finally, only structured types require forcing because when the value of a
simple type is needed, and so it is evaluated to whnf, it actually
evaluates all the way to normal form. Hence instances of force for simple
types are just the identity. -}
module Force where
class Forceable a where
force :: a -> a
class ( Forceable a ) = > ForceableIdentity a where
-- force : : a - > a
force = i d
How can we implement default methods for instances of Forceable when we
say so explicitly ( e.g. by saying they are a member of ForceableIdentity )
but not just when we do not give a specific instance method ( because it is
too tempting just to forget to give a proper definition for instances ) ?
Basically , all non - structured types can use the i d function to force
( since evaluating them to whnf actualy gives normal form ) .
instance
instance ForceableIdentity Float
instance ForceableIdentity Double
-- force :: a -> a
force = id
How can we implement default methods for instances of Forceable when we
say so explicitly (e.g. by saying they are a member of ForceableIdentity)
but not just when we do not give a specific instance method (because it is
too tempting just to forget to give a proper definition for instances)?
Basically, all non-structured types can use the id function to force
(since evaluating them to whnf actualy gives normal form).
instance ForceableIdentity Int
instance ForceableIdentity Float
instance ForceableIdentity Double
-}
instance Forceable Int where
force = id
instance Forceable Double where
force = id
instance Forceable Float where
force = id
instance Forceable Bool where
force = id
instance Forceable () where
force = id
instance (Forceable a, Forceable b) => Forceable (a, b) where
force p@(a, b) = force a `seq` force b `seq` p
instance (Forceable a) => Forceable [a] where
force [] = []
force xs@(x:xs') = force x `seq` force xs' `seq` xs
| null | https://raw.githubusercontent.com/conal/Fran/a113693cfab23f9ac9704cfee9c610c5edc13d9d/src/Force.hs | haskell | Does not force x until x is needed , probably not useful .
Does not force x until x is needed, probably not useful.
force : : a - > a
force :: a -> a
|
The Forceable class containing just one function force . This provides
hyperstrict evaluation by forcing the whole data structure to normal form
as opposed to just whnf . It is normally used in conjunction with seq ,
e.g.
force x ` seq ` E
to ensure that x is evaluated to normal form before E is evaluated . Note
that force inside a definition will not force anything until the top level
is required , i.e. the following will not force x until the value of x is
needed ,
Finally , only structured types require forcing because when the value of a
simple type is needed , and so it is evaluated to whnf , it actually
evaluates all the way to normal form . Hence instances of force for simple
types are just the identity .
hyperstrict evaluation by forcing the whole data structure to normal form
as opposed to just whnf. It is normally used in conjunction with seq,
e.g.
force x `seq` E
to ensure that x is evaluated to normal form before E is evaluated. Note
that force inside a definition will not force anything until the top level
is required, i.e. the following will not force x until the value of x is
needed,
Finally, only structured types require forcing because when the value of a
simple type is needed, and so it is evaluated to whnf, it actually
evaluates all the way to normal form. Hence instances of force for simple
types are just the identity. -}
module Force where
class Forceable a where
force :: a -> a
class ( Forceable a ) = > ForceableIdentity a where
force = i d
How can we implement default methods for instances of Forceable when we
say so explicitly ( e.g. by saying they are a member of ForceableIdentity )
but not just when we do not give a specific instance method ( because it is
too tempting just to forget to give a proper definition for instances ) ?
Basically , all non - structured types can use the i d function to force
( since evaluating them to whnf actualy gives normal form ) .
instance
instance ForceableIdentity Float
instance ForceableIdentity Double
force = id
How can we implement default methods for instances of Forceable when we
say so explicitly (e.g. by saying they are a member of ForceableIdentity)
but not just when we do not give a specific instance method (because it is
too tempting just to forget to give a proper definition for instances)?
Basically, all non-structured types can use the id function to force
(since evaluating them to whnf actualy gives normal form).
instance ForceableIdentity Int
instance ForceableIdentity Float
instance ForceableIdentity Double
-}
instance Forceable Int where
force = id
instance Forceable Double where
force = id
instance Forceable Float where
force = id
instance Forceable Bool where
force = id
instance Forceable () where
force = id
instance (Forceable a, Forceable b) => Forceable (a, b) where
force p@(a, b) = force a `seq` force b `seq` p
instance (Forceable a) => Forceable [a] where
force [] = []
force xs@(x:xs') = force x `seq` force xs' `seq` xs
|
d3895fdb27e38c42e0695752bd717a2ac315eb9fc4efecb5215c1374d3686522 | day8/re-com | throbber.cljs | (ns re-demo.throbber
(:require [re-com.core :refer [at h-box v-box box gap line button label throbber p]]
[re-com.throbber :refer [throbber-parts-desc throbber-args-desc]]
[re-demo.utils :refer [panel-title title2 title3 parts-table args-table github-hyperlink status-text]]
[re-com.util :refer [px]]
[reagent.core :as reagent]))
(def state (reagent/atom
{:outcome-index 0
:see-throbber false}))
(defn throbber-demo
[]
[v-box :src (at)
:size "auto"
:gap "10px"
:children [[panel-title "[throbber ... ]"
"src/re_com/throbber.cljs"
"src/re_demo/throbber.cljs"]
[h-box :src (at)
:gap "100px"
:children [[v-box :src (at)
:gap "10px"
:width "450px"
:children [[title2 "Notes"]
[status-text "Stable"]
[p "A CSS Throbber."]
[args-table throbber-args-desc]]]
[v-box :src (at)
:gap "10px"
:children [[title2 "Demo"]
[h-box :src (at)
:gap "50px"
:children [[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":smaller"]]
[throbber :src (at)
:size :smaller
:color "green"]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":small"]]
[throbber :src (at)
:size :small
:color "red"]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":regular"]]
[throbber :src (at)]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":large"]]
[throbber :src (at)
:size :large
:color "blue"]]]]]]]]]
[parts-table "throbber" throbber-parts-desc]]])
core holds a reference to panel , so need one level of indirection to get figwheel updates
(defn panel
[]
[throbber-demo])
| null | https://raw.githubusercontent.com/day8/re-com/07451b1d19c59eb185548efe93e2d00b5d3eab89/src/re_demo/throbber.cljs | clojure | (ns re-demo.throbber
(:require [re-com.core :refer [at h-box v-box box gap line button label throbber p]]
[re-com.throbber :refer [throbber-parts-desc throbber-args-desc]]
[re-demo.utils :refer [panel-title title2 title3 parts-table args-table github-hyperlink status-text]]
[re-com.util :refer [px]]
[reagent.core :as reagent]))
(def state (reagent/atom
{:outcome-index 0
:see-throbber false}))
(defn throbber-demo
[]
[v-box :src (at)
:size "auto"
:gap "10px"
:children [[panel-title "[throbber ... ]"
"src/re_com/throbber.cljs"
"src/re_demo/throbber.cljs"]
[h-box :src (at)
:gap "100px"
:children [[v-box :src (at)
:gap "10px"
:width "450px"
:children [[title2 "Notes"]
[status-text "Stable"]
[p "A CSS Throbber."]
[args-table throbber-args-desc]]]
[v-box :src (at)
:gap "10px"
:children [[title2 "Demo"]
[h-box :src (at)
:gap "50px"
:children [[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":smaller"]]
[throbber :src (at)
:size :smaller
:color "green"]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":small"]]
[throbber :src (at)
:size :small
:color "red"]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":regular"]]
[throbber :src (at)]]]
[v-box :src (at)
:align :center
:children [[box :src (at) :align :start :child [:code ":large"]]
[throbber :src (at)
:size :large
:color "blue"]]]]]]]]]
[parts-table "throbber" throbber-parts-desc]]])
core holds a reference to panel , so need one level of indirection to get figwheel updates
(defn panel
[]
[throbber-demo])
| |
aaeeb6f0a9bb6ef1eb3b1fc44959cb85683f3e256c3d395f7896c0cea662b8ef | heechul/crest-z3 | mergecil.mli |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
(** Set this to true to ignore the merge conflicts *)
val ignore_merge_conflicts: bool ref
(** Merge a number of CIL files *)
val merge: Cil.file list -> string -> Cil.file
| null | https://raw.githubusercontent.com/heechul/crest-z3/cfcebadddb5e9d69e9956644fc37b46f6c2a21a0/cil/src/mergecil.mli | ocaml | * Set this to true to ignore the merge conflicts
* Merge a number of CIL files |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* George C. Necula <>
* Scott McPeak <>
* Wes Weimer <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
val ignore_merge_conflicts: bool ref
val merge: Cil.file list -> string -> Cil.file
|
4ce743e9c5be6d75fe3a61862eb775b5eacfa70194246e7ad5d5d5e0426e7cc5 | uncomplicate/fluokitten | algo.clj | Copyright ( c ) . All rights reserved .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php) or later
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns uncomplicate.fluokitten.algo
(:require [clojure.string :as cs]
[uncomplicate.fluokitten
[protocols :refer :all]
[utils :refer [with-context deref?]]])
(:require [clojure.core.reducers :as r]))
;;====================== Default functions ==========
(defn default-foldmap
([x g]
(fold (fmap x g)))
([x g f init]
(fold (fmap x g) f init))
([x g f init y]
(fold (fmap x g [y]) f init))
([x g f init y z]
(fold (fmap x g [y z]) f init))
([x g f init y z w]
(fold (fmap x g [y z w]) f init))
([x g f init y z w ws]
(fold (fmap x g (cons y (cons z (cons w ws)))) f init)))
(defn default-bind
([m g]
(join (fmap m g)))
([m g ms]
(join (fmap m g ms))))
(defn default-unbind
([wa g]
(fmap wa (comp g (partial pure wa))))
([wa g was]
(fmap wa (fn [a as] (apply g (pure wa a) (map (partial pure wa) as))) was)))
(defn default-unbind!
([wa g]
(fmap! wa (comp g (partial pure wa))))
([wa g was]
(fmap! wa (fn [a as] (apply g (pure wa a) (map (partial pure wa) as))) was)))
;; ==================== Object =====================
(defn object-fmap
([o f]
(f o))
([o f os]
(apply f o os)))
(defn object-pure [o x]
x)
(defn object-foldmap
([x g]
(g x))
([x g f init]
(f init (g x)))
([x g f init y]
(f init (g x y)))
([x g f init y z]
(f init (g x y z)))
([x g f init y z w]
(f init (g x y z w)))
([x g f init y z w ws]
(f init (g x y z w ws))))
(defn object-fold
([x]
x)
([x f init]
(f init x))
([x f init y]
(f init ((op x) x y)))
([x f init y z]
(f init ((op x) x y z)))
([x f init y z w]
(f init ((op x) x y z w)))
([x f init y z w ws]
(f init (apply (op x) x y z w ws))))
(extend Object
Functor
{:fmap object-fmap}
Applicative
{:fapply object-fmap
:pure object-pure}
Monad
{:join identity
:bind object-fmap}
Comonad
{:extract identity
:unbind default-unbind}
Foldable
{:fold object-fold
:foldmap object-foldmap})
;;=============== Functor implementations =========================
;;--------------- fmap implementations ---------------
(defn collreduce-fmap
([cr g]
(r/map g cr))
([_ _ _]
(throw (UnsupportedOperationException. "fmap for reducibles does not support varargs."))))
(defn reducible-fmap
([c g]
(into (empty c) (r/map g c)))
([c g cs]
(into (empty c) (apply map g c cs))))
(defn ^:private group-entries-xf [k]
(comp (map #(find % k)) (remove nil?) (map val)))
(defn ^:private hashmap-fmap-xf
([g ms]
(comp (mapcat keys)
(dedupe)
(map (fn [k] [k (apply g (into [] (group-entries-xf k) ms))])))))
(defn hashmap-fmap
([m g]
(into (empty m) (r/map (fn [[k v]] [k (g v)]) m)))
([m g ms]
(let [ms (cons m ms)]
(into (empty m) (hashmap-fmap-xf g ms) ms))))
(defn list-fmap
([l g]
(with-meta
(apply list (map g l))
(meta l)))
([l g ss]
(with-meta
(apply list (apply map g l ss))
(meta l))))
(defn seq-fmap
([s g]
(with-meta
(map g s)
(meta s)))
([s g ss]
(with-meta
(apply map g s ss)
(meta s))))
(defn coll-fmap
([c g]
(into (empty c) (map g c)))
([c g ss]
(into (empty c) (apply map g c ss))))
(defn eduction-fmap
([e g]
(eduction (map g) e))
([e g ss]
(eduction (seq-fmap e g ss))))
;;================ Applicative implementations ==================
-------------- fapply implementations ----------------
(defn collreduce-fapply
([crv crg]
(r/mapcat (partial fmap crv) crg))
([cv cg cvs]
(r/mapcat #(fmap cv % cvs) cg)))
(defn collreduce-pure [_ v]
(r/map identity [v]))
(defn reducible-fapply
([cv cg]
(into (empty cv) (collreduce-fapply cv cg)))
([cv cg cvs]
(into (empty cv) (collreduce-fapply cv cg cvs))))
(defn hashmap-fapply
([mv mg]
(if-let [f (mg nil)]
(into (empty mv)
(r/map (fn [[kv vv]]
(if-let [eg (find mg kv)]
[kv ((val eg) vv)]
[kv (f vv)]))
mv))
(into mv
(comp (map (fn [[kg vg]]
(if-let [ev (find mv kg)]
[kg (vg (val ev))])))
(remove nil?))
mg)))
([mv mg mvs]
(let [ms (cons mv mvs)]
(if-let [f (mg nil)]
(into (empty mv)
(comp (mapcat keys)
(dedupe)
(map (fn [kv]
(let [vs (into [] (group-entries-xf kv) ms)
fun (if-let [eg (find mg kv)] (val eg) f)]
[kv (apply fun vs)]))))
ms)
(into (apply merge mv mvs)
(comp (map (fn [[kg vg]]
(if-let [vs (seq (into [] (group-entries-xf kg) ms))]
[kg (apply vg vs)])))
(remove nil?))
mg)))))
(defn list-fapply
([cv cg]
(with-meta
(apply list (mapcat (partial fmap cv) cg))
(meta cv)))
([cv cg cvs]
(with-meta
(apply list (mapcat #(fmap cv % cvs) cg))
(meta cv))))
(defn seq-fapply
([cv cg]
(with-meta
(mapcat (partial fmap cv) cg)
(meta cv)))
([cv cg cvs]
(with-meta
(mapcat #(fmap cv % cvs) cg)
(meta cv))))
(defn coll-fapply
([cv cg]
(into (empty cv) (mapcat (partial fmap cv) cg)))
([cv cg cvs]
(into (empty cv) (mapcat #(fmap cv % cvs) cg))))
(defn eduction-fapply
([ev eg]
(eduction (mapcat (partial fmap ev)) eg))
([ev eg evs]
(eduction (mapcat #(fmap ev % evs)) eg)))
(defn coll-pure
([cv v]
(conj (empty cv) v))
([cv v vs]
(into (coll-pure cv v) vs)))
(defn seq-pure
([cv v]
(cons v nil))
([cv v vs]
(cons v vs)))
(defn eduction-pure
([e v]
(eduction [v]))
([e v vs]
(eduction (cons v vs))))
(defn hashmap-pure
([m v]
(coll-pure m [nil v]))
([m v vs]
(into (empty m)
(if (vector? v)
(cons v vs)
(apply hash-map v vs)))))
;;================== Monad Implementations ======================
(defn collreduce-bind
([cr g]
(r/mapcat g cr))
([cr g ss]
(throw (UnsupportedOperationException. "bind for reducibles does not support varargs."))))
(defn reducible-bind
([c g]
(into (empty c) (r/mapcat g c)))
([c g ss]
(into (empty c) (apply mapcat g c ss))))
(let [flatten-keys (fn [[k x :as e]]
(if (map? x)
(map (fn [[kx vx]]
[(if (and k kx)
(vec (flatten [k kx]))
(or k kx))
vx])
x)
[e]))]
(defn hashmap-join [m]
(into (empty m) (r/mapcat flatten-keys m)))
(defn hashmap-bind
([m g]
(into (empty m)
(comp (map (fn [[k v]] [k (g v)]))
(mapcat flatten-keys))
m))
([m g ms]
(let [ms (cons m ms)]
(into (empty m)
(comp (hashmap-fmap-xf g ms)
(mapcat flatten-keys))
ms)))))
(defn coll-bind
([c g]
(into (empty c) (mapcat g) c))
([c g ss]
(into (empty c) (apply mapcat g c ss))))
(defn coll-join [c]
(with-meta
(persistent! (reduce (fn [acc e] (if (coll? e)
(reduce conj! acc e)
(conj! acc e)))
(transient (empty c)) c))
(meta c)))
(defn seq-join [s]
(let [o (op s)]
(with-meta
(reduce (fn [acc e]
(if (sequential? e)
(o acc e)
(cons e acc)))
(id s) s)
(meta s))))
(defn list-join [c]
(with-meta
(apply list (seq-join c))
(meta c)))
(defn eduction-join [e]
(eduction (mapcat #(if (sequential? %) % [%])) e))
(defn collreduce-join [c]
(r/mapcat #(if (coll? %) % [%]) c))
(defn reducible-join [c]
(into (empty c) (collreduce-join c)))
(defn list-bind
([c g]
(with-meta
(apply list (mapcat g c))
(meta c)))
([c g ss]
(with-meta
(apply list (apply mapcat g c ss))
(meta c))))
(defn seq-bind
([c g]
(with-meta
(mapcat g c)
(meta c)))
([c g ss]
(with-meta
(apply mapcat g c ss)
(meta c))))
(defn eduction-bind
([e g]
(eduction (mapcat g) e))
([e g ss]
(eduction (apply mapcat g e ss))))
;;================== Comonad Implementations ======================
(defn seq-unbind
([s g]
(cons (g s) (lazy-seq (seq-unbind (rest s) g))))
([s g ss]
(cons (apply g s ss) (lazy-seq (seq-unbind (rest s) g (map rest ss))))))
(defn collreduce-extract [c]
(reduce + (r/take 1 c)))
;;======== Algebraic structures implementations ==================
(defn coll-op* [zero]
(fn coll-op
([]
zero)
([x]
x)
([x y]
(into x y))
([x y z]
(into x cat [y z]))
([x y z w]
(into x cat [y z w]))
([x y z w & ws]
(into x cat (into [y z w] ws)))))
(defn collreduce-op
([]
[])
([x]
x)
([x y]
(if (instance? clojure.core.protocols.CollReduce y)
(r/cat x y)
(into x y)))
([x y z]
(collreduce-op x (collreduce-op y z)))
([x y z w]
(collreduce-op (collreduce-op x y) (collreduce-op z w)))
([x y z w & ws]
(collreduce-op (collreduce-op x y z w) (r/fold collreduce-op ws))))
(defn reducible-op
([]
[])
([x]
x)
([x y]
(into x y))
([x y z]
(into x (collreduce-op y z)))
([x y z w]
(into x (collreduce-op y z w)))
([x y z w & ws]
(into x (apply collreduce-op y z w ws))))
(defn seq-op* [zero]
(fn seq-op
([]
zero)
([x]
x)
([x y]
(concat x y))
([x y z]
(concat x y z))
([x y z w]
(concat x y z w))
([x y z w & ws]
(apply concat x y z w ws))))
(defn eduction-op
([]
(eduction))
([x]
x)
([x y]
(eduction cat [x y]))
([x y z]
(eduction cat [x y z]))
([x y z w]
(eduction cat [x y z w]))
([x y z w & ws]
(eduction cat (into [x y z w] ws))))
(defn list-op
([]
(list))
([x]
x)
([x y]
(apply list (concat x y)))
([x y z]
(apply list (concat x y z)))
([x y z w]
(apply list (concat x y z w)))
([x y z w & ws]
(apply list (apply concat x y z w ws))))
;;================== Foldable ===================================
(defn collection-foldmap
([c g]
(if-let [e (first c)]
(let [ge (g e)]
(r/fold (op ge) (r/map g c)))))
([c g f init]
(f init (r/fold f (r/map g c))))
([cx g f init cy]
(loop [acc init cx cx cy cy]
(if cx
(recur (f acc (g (first cx) (first cy))) (next cx) (next cy))
acc)))
([cx g f init cy cz]
(loop [acc init cx cx cy cy cz cz]
(if cx
(recur (f acc (g (first cx) (first cy) (first cz)))
(next cx) (next cy) (next cz))
acc)))
([cx g f init cy cz cw]
(loop [acc init cx cx cy cy cz cz cw cw]
(if cx
(recur (f acc (g (first cx) (first cy) (first cz) (first cw)))
(next cx) (next cy) (next cz) (next cw))
acc)))
([cx g f init cy cz cw cws]
(loop [acc init cx cx cy cy cz cz cw cw cws cws]
(if cx
(recur (f acc (apply g (first cx) (first cy) (first cz) (first cw)
(map first cws)))
(next cx) (next cy) (next cz) (next cw) (map next cws))
acc))))
(defn collection-fold
([c]
(if-let [e (first c)]
(r/fold (op e) c)))
([c f init]
(f init (r/fold f c)))
([cx f init cy]
(collection-foldmap cx (op (first cx)) f init cy))
([cx f init cy cz]
(collection-foldmap cx (op (first cx)) f init cy cz))
([cx f init cy cz cw]
(collection-foldmap cx (op (first cx)) f init cy cz cw))
([cx f init cy cz cw cws]
(loop [acc init cx cx cy cy cz cz cw cw cws cws]
(if (and cx cy cz cw (not-any? empty? cws))
(recur (f acc (apply (op (first cx)) (first cx) (first cy) (first cz) (first cw) (map first cws)))
(next cx) (next cy) (next cz) (next cw) (map next cws))
acc))))
(defn eduction-foldmap
([c g]
(if-let [e (first c)]
(transduce (map g) (op (g e)) c)))
([c g f init]
(transduce (map g) f init c))
([cx g f init cy]
(collection-foldmap cx g f init cy))
([cx g f init cy cz]
(collection-foldmap cx g f init cy cz))
([cx g f init cy cz cw]
(collection-foldmap cx g f init cy cz cz cw))
([cx g f init cy cz cw cws]
(collection-foldmap cx g f init cy cz cz cw cws)))
(defn hashmap-fold
([m]
(collection-fold (vals m)))
([m f init]
(collection-fold (vals m) f init))
([mx f init my]
(collection-fold (vals mx) f init (vals my)))
([mx f init my mz]
(collection-fold (vals mx) f init (vals my) (vals mz)))
([mx f init my mz mw]
(collection-fold (vals mx) f init (vals my) (vals mz) (vals mw)))
([mx f init my mz mw mws]
(collection-fold (vals mx) f init (vals my) (vals mz) (vals mw) (map vals mws))))
(defn collfold-fold
([c]
(if-let [e (first (into [] (r/take 1 c)))]
(collection-fold c (op e) (id e))))
([c f init]
(collection-fold c f init)))
;;================== Collections Extensions =====================
(defmacro extend-collection [t]
`(extend ~t
Functor
{:fmap coll-fmap}
Applicative
{:pure coll-pure
:fapply coll-fapply}
Monad
{:join coll-join
:bind coll-bind}
Comonad
{:extract peek
:unbind default-unbind}
Foldable
{:fold collection-fold
:foldmap collection-foldmap}
Magma
{:op (constantly (coll-op* []))}
Monoid
{:id empty}))
(defmacro extend-vector [t]
`(extend ~t
Functor
{:fmap reducible-fmap}
Applicative
{:pure coll-pure
:fapply reducible-fapply}
Monad
{:join reducible-join
:bind reducible-bind}
Magma
{:op (constantly reducible-op)}))
(defmacro extend-list [t]
`(extend ~t
Functor
{:fmap list-fmap}
Applicative
{:pure coll-pure
:fapply list-fapply}
Monad
{:join list-join
:bind list-bind}
Magma
{:op (constantly list-op)}))
(defmacro extend-seq [t]
`(extend ~t
Functor
{:fmap seq-fmap}
Applicative
{:pure seq-pure
:fapply seq-fapply}
Monad
{:join seq-join
:bind seq-bind}
Comonad
{:extract first
:unbind seq-unbind}
Magma
{:op (constantly (seq-op* (list)))}))
(defmacro extend-lazyseq [t]
`(extend ~t
Functor
{:fmap seq-fmap}
Applicative
{:pure seq-pure
:fapply seq-fapply}
Monad
{:join seq-join
:bind seq-bind}
Comonad
{:extract first
:unbind seq-unbind}
Magma
{:op (constantly (seq-op* (lazy-seq)))}))
(defmacro extend-eduction [t]
`(extend ~t
Functor
{:fmap eduction-fmap}
Applicative
{:pure eduction-pure
:fapply eduction-fapply}
Monad
{:join eduction-join
:bind eduction-bind}
Comonad
{:extract first
:unbind default-unbind}
Foldable
{:fold collection-fold
:foldmap eduction-foldmap}
Magma
{:op (constantly eduction-op)}
Monoid
{:id (constantly (eduction))}))
(defmacro extend-set [t]
`(extend ~t
Functor
{:fmap reducible-fmap}
Applicative
{:pure coll-pure
:fapply reducible-fapply}
Monad
{:join coll-join
:bind reducible-bind}
Comonad
{:extract first
:unbind default-unbind}
Magma
{:op (constantly (coll-op* #{}))}))
(defmacro extend-hashmap [t]
`(extend ~t
Functor
{:fmap hashmap-fmap}
Applicative
{:pure hashmap-pure
:fapply hashmap-fapply}
Monad
{:join hashmap-join
:bind hashmap-bind}
Comonad
{:extract (comp val first)
:unbind default-unbind}
Foldable
{:fold hashmap-fold
:foldmap default-foldmap}
Magma
{:op (constantly (coll-op* {}))}))
(extend clojure.core.protocols.CollReduce
Functor
{:fmap collreduce-fmap}
Applicative
{:pure collreduce-pure
:fapply collreduce-fapply}
Monad
{:join collreduce-join
:bind collreduce-bind}
Comonad
{:extract collreduce-extract
:unbind default-unbind}
Magma
{:op (constantly collreduce-op)})
(extend clojure.core.reducers.CollFold
Foldable
{:fold collfold-fold
:foldmap default-foldmap})
(declare create-mapentry)
(defn mapentry-fmap
([[ke ve] g]
(create-mapentry ke (g ve)))
([[ke ve] g es]
(create-mapentry ke (apply g ve (vals es)))))
(defn mapentry-pure [e v]
(create-mapentry nil v))
(defn mapentry-fapply
([[ke ve :as e] [kg vg]]
(if (or (nil? kg) (= ke kg))
(create-mapentry ke (vg ve))
e))
([[ke ve :as e] [kg vg] es]
(if (or (nil? kg)
(not-any? (fn [[k _]]
(not= k kg))
(cons e es)))
(create-mapentry ke (apply vg ve (map val es)))
e)))
(defn mapentry-join [[k x :as e]]
(if (vector? x)
(let [[kx vx] x]
(create-mapentry (if (and k kx)
(vec (flatten [k kx]))
(or k kx))
vx))
e))
(defn mapentry-id [[kx vx]]
(create-mapentry (id kx) (id vx)))
(defn mapentry-op [e]
(fn
([]
(id e))
([x]
x)
([[kx vx] [ky vy]]
(create-mapentry ((op kx) kx ky) ((op vx) vx vy)))
([[kx vx] [ky vy] [kz vz]]
(create-mapentry ((op kx) kx ky kz) ((op vx) vx vy vz)))
([[kx vx] [ky vy] [kz vz] [kw vw]]
(create-mapentry ((op kx) kx ky kz kw) ((op vx) vx vy vz vw)))
([[kx vx] [ky vy] [kz vz] [kw vw] es]
(create-mapentry (apply (op kx) kx ky kz kw (map key es))
(apply (op vx) vx vy kz kw (map val es))))))
(defn mapentry-foldmap
([e g]
(g (val e)))
([e g f init]
(f init (g (val e))))
([e g f init e1]
(f init (g (val e) (val e1))))
([e g f init e1 e2]
(f init (g (val e) (val e1) (val e2))))
([e g f init e1 e2 e3]
(f init (g (val e) (val e1) (val e2) (val e3))))
([e g f init e1 e2 e3 es]
(f init (apply g (val e) (val e1) (val e2) (val e3) (map val es)))))
(defn mapentry-fold
([e]
(val e))
([e f init]
(f init (val e)))
([e f init e1]
(mapentry-foldmap e (op e) f init e1))
([e f init e1 e2]
(mapentry-foldmap e (op e) f init e1 e2))
([e f init e1 e2 e3]
(mapentry-foldmap e (op e) f init e1 e2 e3))
([e f init e1 e2 e3 es]
(f init (apply (op e) (val e) (val e1) (val e2) (val e3) (map val es)))))
(defmacro extend-mapentry [t]
`(extend ~t
Functor
{:fmap mapentry-fmap}
Applicative
{:pure mapentry-pure
:fapply mapentry-fapply}
Monad
{:join mapentry-join
:bind default-bind}
Comonad
{:extract val
:unbind default-unbind}
Magma
{:op mapentry-op}
Monoid
{:id mapentry-id}
Foldable
{:fold mapentry-fold
:foldmap mapentry-foldmap}))
;;===================== Literals Extensions ================
(defn ^:private deref-resolve [s]
(deref (resolve (symbol (name s)))))
(defn ^:private to-string
([s]
(if (sequential? s)
(cs/join s)
(str s)))
([s ss]
(apply str (to-string s) (map to-string ss))))
(extend-type String
Functor
(fmap
([s g]
(to-string (g s)))
([s g ss]
(to-string (apply g s ss))))
Applicative
(fapply
([sv sg]
(fmap sv (deref-resolve sg)))
([sv sg svs]
(fmap sv (deref-resolve sg) svs)))
(pure
([_ x]
(to-string x)
(str x))
([_ x xs]
(to-string x xs)))
Magma
(op [x]
str)
Monoid
(id [s] ""))
(extend-type Number
Magma
(op [x]
+)
Monoid
(id [x] 0))
(extend-type Double
Monoid
(id [x] 0.0))
(extend-type Float
Monoid
(id [x] 0.0))
(defn keyword-fmap
([k g]
(keyword (fmap (name k) g)))
([k g ks]
(keyword (fmap (name k) g (map name ks)))))
(defn keyword-pure
([k v]
(keyword (str v)))
([k v vs]
(keyword (apply str v vs))))
(defn keyword-fapply
([kv kg]
(keyword-fmap kv (deref-resolve kg)))
([kv kg kvs]
(keyword-fmap kv (deref-resolve kg) kvs)))
(def keyword-id (constantly (keyword "")))
(defn keyword-op
([] (keyword ""))
([x]
x)
([x y]
(keyword (str (name x) (name y))))
([x y z]
(keyword (str (name x) (name y) (name z))))
([x y z w]
(keyword (str (name x) (name y) (name z) (name w))))
([x y z w ws]
(keyword (apply str (name x) (name y) (name z) (name w) ws))))
(defmacro extend-keyword [t]
`(extend ~t
Functor
{:fmap keyword-fmap}
Applicative
{:fapply keyword-fapply
:pure keyword-pure}
Magma
{:op (constantly keyword-op)}
Monoid
{:id keyword-id}))
;;===================== Function ===========================
(let [identity? (fn [f] (identical? identity f))]
(defn function-op
([] identity)
([x]
x)
([x y & zs]
(apply comp
(cond
(identity? x) y
(identity? y) x
:default (comp x y))
(remove identity? zs)))))
(defn function-fmap
([f g]
(function-op g f))
([f g hs]
(fn
([]
(apply g (f) (map #(%) hs)))
([x]
(apply g (f x) (map #(% x) hs)))
([x & xs]
(apply g (apply f x xs) (map #(apply % x xs) hs))))))
(defn function-fapply
([f g]
(if (identical? identity g)
f
(fn
([]
((g) (f)))
([x]
((g x) (f x)))
([x & xs]
((apply g x xs) (apply f x xs))))))
([f g hs]
(fn
([]
(apply (g) (f) (map #(%) hs)))
([x]
(apply (g x) (f x) (map #(% x) hs)))
([x & xs]
(apply (apply g x xs) (apply f x xs) (map #(apply % x xs) hs))))))
(defn function-pure [f x]
(constantly x))
(defn function-join [f]
(fn
([]
(with-context f
((f))))
([x]
(with-context f
((f x) x)))
([x & xs]
(with-context f
(apply (apply f x xs) x xs)))))
(defn function-bind
([f g]
(join (fmap f g)))
([f g hs]
(join (fmap f g hs))))
(defn function-extract [f]
(f))
(defn function-fold
([fx]
(fx))
([fx f init]
(f init (fx)))
([fx f init fy]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy)))))
([fx f init fy fz]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy) (fz)))))
([fx f init fy fz fw]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy) (fz) (fw)))))
([fx f init fy fz fw fws]
(let [fxv (fx)
op-fx (op fxv)]
(f init (apply op-fx fxv (fy) (fz) (fw) (map #(%) fws))))))
(defmacro extend-function [t]
`(extend ~t
Functor
{:fmap function-fmap}
Applicative
{:fapply function-fapply
:pure function-pure}
Monad
{:join function-join
:bind function-bind}
Comonad
{:extract function-extract
:unbind default-unbind}
Foldable
{:fold function-fold
:foldmap default-foldmap}
Magma
{:op (constantly function-op)}
Monoid
{:id (constantly identity)}))
;;====================== References =======================
;;----------------- Universal ------------------
(defn reference-fmap
([r g]
(pure r (g (deref r))))
([r g rs]
(pure r (apply g (deref r) (map deref rs)))))
(defn reference-fapply!
([rv rg]
(fmap! rv (deref rg)))
([rv rg rvs]
(apply fmap! rv (deref rg) rvs)))
(defn reference-fapply
([rv rg]
(reference-fmap rv (deref rg)))
([rv rg rvs]
(reference-fmap rv (deref rg) rvs)))
(defn reference-join! [r]
(if (deref? @r)
(fmap! r deref)
r))
(defn reference-join [r]
(if (deref? @r)
(fmap! r deref)
r))
(defn reference-bind!
([mv g]
(fmap! (fmap! mv g) deref))
([mv g mvs]
(fmap! (apply fmap! mv g mvs) deref)))
(defn reference-bind
([mv g]
(fmap! (fmap mv g) deref))
([mv g mvs]
(fmap! (fmap mv g mvs) deref)))
(defn reference-op [r]
(fn
([] (id r))
([r & rs]
(if rs
(fmap r (op @r) rs)
r))))
(defn reference-foldmap
([rx g]
(g @rx))
([rx g f init]
(f init (g @rx)))
([rx g f init ry]
(f init (g @rx @ry)))
([rx g f init ry rz]
(f init (g @rx @ry @rz)))
([rx g f init ry rz rw]
(f init (g @rx @ry @rz @rw)))
([rx g f init ry rz rw rws]
(f init (apply g @rx @ry @rz @rw (map deref rws)))))
(defn reference-fold
([r]
(deref r))
([r f init]
(f init (deref r)))
([rx f init ry]
(f init ((op @rx) @rx @ry)))
([rx f init ry rz]
(f init ((op @rx) @rx @ry @rz)))
([rx f init ry rz rw]
(f init ((op @rx) @rx @ry @rz @rw)))
([rx f init ry rz rw rws]
(f init (apply (op @rx) @rx @ry @rz @rw (map deref rws)))))
;;----------------- Atom -----------------------
(defn atom-fmap!
([a g]
(doto a (swap! g)))
([ax g ry]
(doto ax (swap! g @ry)))
([ax g ry rz]
(doto ax (swap! g @ry @rz)))
([ax g ry rz rw]
(doto ax (swap! g @ry @rz @rw)))
([ax g ry rz rw rws]
(do
(apply swap! ax g @ry @rz @rw (map deref rws))
ax)))
(defn atom-pure [_ v]
(atom v))
(defn atom-id [a]
(atom (id (deref a))))
;;------------------- Ref --------------------------
(defn ref-fmap!
([rx g]
(doto rx (alter g)))
([rx g ry]
(doto rx (alter g @ry)))
([rx g ry rz]
(doto rx (alter g @ry @rz)))
([rx g ry rz rw]
(doto rx (alter g @ry @rz @rw)))
([rx g ry rz rw rws]
(do
(apply alter rx g @ry @rz @rw (map deref rws))
rx)))
(defn ref-pure [_ v]
(ref v))
(defn ref-id [r]
(ref (id @r)))
;;------------------ Volatile ----------------------
(defmacro ^:private vswap!! [vol f ry rz rw rws]
`(vswap! ~vol ~f ~ry ~rz ~rw ~@rws))
(defn volatile-fmap!
([v g]
(doto v (vswap! g)))
([vx g ry]
(doto vx (vswap! g @ry)))
([vx g ry rz]
(doto vx (vswap! g @ry @rz)))
([vx g ry rz rw]
(doto vx (vswap! g @ry @rz @rw)))
([vx g ry rz rw rws]
(do
(vswap!! vx g @ry @rz @rw (map deref rws))
vx)))
(defn volatile-pure [_ v]
(volatile! v))
(defn volatile-id [a]
(volatile! (id (deref a))))
;;------------------ Extensions --------------------
(defmacro extend-ideref [t]
`(extend ~t
Functor
{:fmap reference-fmap}
Applicative
{:fapply reference-fapply}
PseudoApplicative
{:fapply! reference-fapply!}
Monad
{:join reference-join
:bind reference-bind}
PseudoMonad
{:join! reference-join!
:bind! reference-bind!}
Comonad
{:extract deref
:unbind default-unbind}
PseudoComonad
{:unbind! default-unbind!}
Foldable
{:fold reference-fold
:foldmap reference-foldmap}
Magma
{:op reference-op}))
(defmacro extend-atom [t]
`(extend ~t
PseudoFunctor
{:fmap! atom-fmap!}
Applicative
{:pure atom-pure
:fapply reference-fapply}
Monoid
{:id atom-id}))
(defmacro extend-ref [t]
`(extend ~t
PseudoFunctor
{:fmap! ref-fmap!}
Applicative
{:pure ref-pure
:fapply reference-fapply}
Monoid
{:id ref-id}))
(defmacro extend-volatile [t]
`(extend ~t
PseudoFunctor
{:fmap! volatile-fmap!}
Applicative
{:pure volatile-pure
:fapply reference-fapply}
Monoid
{:id volatile-id}))
;;================== Maybe ===========================
(defn just-fmap
([jv g]
(pure jv (g (value jv))))
([jv g jvs]
(when-not (some nil? jvs)
(pure jv (apply g (value jv) (map value jvs))))))
(defn just-fapply
([jv jg]
(when jg
(fmap jv (value jg))))
([jv jg jvs]
(when jg
(fmap jv (value jg) jvs))))
(defn just-bind
([jv g]
(g (value jv)))
([jv g jvs]
(when-not (some nil? jvs)
(apply g (value jv) (map value jvs)))))
(defn just-join [jjv]
(let [v (value jjv)]
(if (or (not v) (satisfies? Maybe v)) v jjv)))
(defn just-foldmap
([x g]
(g (value x)))
([x g f init]
(f init (g (value x))))
([x g f init y]
(when y
(f init (g (value x) (value y)))))
([x g f init y z]
(when (and y z)
(f init (g (value x) (value y) (value y)))))
([x g f init y z w]
(when (and y z w)
(f init (g (value x) (value y) (value z) (value w)))))
([x g f init y z w ws]
(when (and y z w (not-any? nil? ws))
(f init (apply g (value x) (value y) (value z) (value w) (map value ws))))))
(defn just-fold
([x]
(value x))
([x f init]
(f init (value x)))
([x f init y]
(just-foldmap x ((op (value x)) (value x) f init y)))
([x f init y z]
(just-foldmap x ((op (value x)) (value x) f init y z)))
([x f init y z w]
(just-foldmap x ((op (value x)) (value x) f init y z w)))
([x f init y z w ws]
(just-foldmap x ((op (value x)) (value x) f init y z w ws))))
(defn just-op
([] nil)
([x] x)
([x y & zs]
(if x
(let [vx (value x)
o (op vx)
init (if-let [vy (value y)] (o vx vy) vx)
res (if zs (transduce (comp (map value) (remove nil?)) o init zs) init)]
(if (= vx res) x (pure x res)))
(apply just-op y zs))))
(defmacro extend-just [t just-pure]
`(extend ~t
Functor
{:fmap just-fmap}
Applicative
{:pure ~just-pure
:fapply just-fapply}
Monad
{:join just-join
:bind just-bind}
Comonad
{:extract value
:unbind default-unbind}
Foldable
{:fold just-fold
:foldmap just-foldmap}
Magma
{:op (constantly just-op)}
Monoid
{:id (constantly nil)}))
(extend-type nil
Functor
(fmap
([_ _] nil)
([_ _ _] nil))
PseudoFunctor
(fmap!
([_ _] nil)
([_ _ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil))
PseudoApplicative
(fapply!
([_ _] nil)
([_ _ _] nil))
Monad
(bind
([_ _] nil)
([_ _ _] nil))
(join [_] nil)
PseudoMonad
(bind!
([_ _] nil)
([_ _ _] nil))
(join! [_] nil)
Comonad
(extract [_]
nil)
(unbind
([_ _] nil)
([_ _ _] nil))
PseudoComonad
(unbind!
([_ _] nil)
([_ _ _] nil))
Foldable
(fold
([_] nil)
([_ _ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil)
([_ _ _ _ _ _ _] nil))
(foldmap
([_ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil)
([_ _ _ _ _ _ _] nil)
([_ _ _ _ _ _ _ _] nil))
Magma
(op [_] just-op)
Monoid
(id [_] nil)
Maybe
(value [_] nil))
| null | https://raw.githubusercontent.com/uncomplicate/fluokitten/65dc74881533a202871d9235c52db89c26c0d41d/src/uncomplicate/fluokitten/algo.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php) or later
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
====================== Default functions ==========
==================== Object =====================
=============== Functor implementations =========================
--------------- fmap implementations ---------------
================ Applicative implementations ==================
================== Monad Implementations ======================
================== Comonad Implementations ======================
======== Algebraic structures implementations ==================
================== Foldable ===================================
================== Collections Extensions =====================
===================== Literals Extensions ================
===================== Function ===========================
====================== References =======================
----------------- Universal ------------------
----------------- Atom -----------------------
------------------- Ref --------------------------
------------------ Volatile ----------------------
------------------ Extensions --------------------
================== Maybe =========================== | Copyright ( c ) . All rights reserved .
(ns uncomplicate.fluokitten.algo
(:require [clojure.string :as cs]
[uncomplicate.fluokitten
[protocols :refer :all]
[utils :refer [with-context deref?]]])
(:require [clojure.core.reducers :as r]))
(defn default-foldmap
([x g]
(fold (fmap x g)))
([x g f init]
(fold (fmap x g) f init))
([x g f init y]
(fold (fmap x g [y]) f init))
([x g f init y z]
(fold (fmap x g [y z]) f init))
([x g f init y z w]
(fold (fmap x g [y z w]) f init))
([x g f init y z w ws]
(fold (fmap x g (cons y (cons z (cons w ws)))) f init)))
(defn default-bind
([m g]
(join (fmap m g)))
([m g ms]
(join (fmap m g ms))))
(defn default-unbind
([wa g]
(fmap wa (comp g (partial pure wa))))
([wa g was]
(fmap wa (fn [a as] (apply g (pure wa a) (map (partial pure wa) as))) was)))
(defn default-unbind!
([wa g]
(fmap! wa (comp g (partial pure wa))))
([wa g was]
(fmap! wa (fn [a as] (apply g (pure wa a) (map (partial pure wa) as))) was)))
(defn object-fmap
([o f]
(f o))
([o f os]
(apply f o os)))
(defn object-pure [o x]
x)
(defn object-foldmap
([x g]
(g x))
([x g f init]
(f init (g x)))
([x g f init y]
(f init (g x y)))
([x g f init y z]
(f init (g x y z)))
([x g f init y z w]
(f init (g x y z w)))
([x g f init y z w ws]
(f init (g x y z w ws))))
(defn object-fold
([x]
x)
([x f init]
(f init x))
([x f init y]
(f init ((op x) x y)))
([x f init y z]
(f init ((op x) x y z)))
([x f init y z w]
(f init ((op x) x y z w)))
([x f init y z w ws]
(f init (apply (op x) x y z w ws))))
(extend Object
Functor
{:fmap object-fmap}
Applicative
{:fapply object-fmap
:pure object-pure}
Monad
{:join identity
:bind object-fmap}
Comonad
{:extract identity
:unbind default-unbind}
Foldable
{:fold object-fold
:foldmap object-foldmap})
(defn collreduce-fmap
([cr g]
(r/map g cr))
([_ _ _]
(throw (UnsupportedOperationException. "fmap for reducibles does not support varargs."))))
(defn reducible-fmap
([c g]
(into (empty c) (r/map g c)))
([c g cs]
(into (empty c) (apply map g c cs))))
(defn ^:private group-entries-xf [k]
(comp (map #(find % k)) (remove nil?) (map val)))
(defn ^:private hashmap-fmap-xf
([g ms]
(comp (mapcat keys)
(dedupe)
(map (fn [k] [k (apply g (into [] (group-entries-xf k) ms))])))))
(defn hashmap-fmap
([m g]
(into (empty m) (r/map (fn [[k v]] [k (g v)]) m)))
([m g ms]
(let [ms (cons m ms)]
(into (empty m) (hashmap-fmap-xf g ms) ms))))
(defn list-fmap
([l g]
(with-meta
(apply list (map g l))
(meta l)))
([l g ss]
(with-meta
(apply list (apply map g l ss))
(meta l))))
(defn seq-fmap
([s g]
(with-meta
(map g s)
(meta s)))
([s g ss]
(with-meta
(apply map g s ss)
(meta s))))
(defn coll-fmap
([c g]
(into (empty c) (map g c)))
([c g ss]
(into (empty c) (apply map g c ss))))
(defn eduction-fmap
([e g]
(eduction (map g) e))
([e g ss]
(eduction (seq-fmap e g ss))))
-------------- fapply implementations ----------------
(defn collreduce-fapply
([crv crg]
(r/mapcat (partial fmap crv) crg))
([cv cg cvs]
(r/mapcat #(fmap cv % cvs) cg)))
(defn collreduce-pure [_ v]
(r/map identity [v]))
(defn reducible-fapply
([cv cg]
(into (empty cv) (collreduce-fapply cv cg)))
([cv cg cvs]
(into (empty cv) (collreduce-fapply cv cg cvs))))
(defn hashmap-fapply
([mv mg]
(if-let [f (mg nil)]
(into (empty mv)
(r/map (fn [[kv vv]]
(if-let [eg (find mg kv)]
[kv ((val eg) vv)]
[kv (f vv)]))
mv))
(into mv
(comp (map (fn [[kg vg]]
(if-let [ev (find mv kg)]
[kg (vg (val ev))])))
(remove nil?))
mg)))
([mv mg mvs]
(let [ms (cons mv mvs)]
(if-let [f (mg nil)]
(into (empty mv)
(comp (mapcat keys)
(dedupe)
(map (fn [kv]
(let [vs (into [] (group-entries-xf kv) ms)
fun (if-let [eg (find mg kv)] (val eg) f)]
[kv (apply fun vs)]))))
ms)
(into (apply merge mv mvs)
(comp (map (fn [[kg vg]]
(if-let [vs (seq (into [] (group-entries-xf kg) ms))]
[kg (apply vg vs)])))
(remove nil?))
mg)))))
(defn list-fapply
([cv cg]
(with-meta
(apply list (mapcat (partial fmap cv) cg))
(meta cv)))
([cv cg cvs]
(with-meta
(apply list (mapcat #(fmap cv % cvs) cg))
(meta cv))))
(defn seq-fapply
([cv cg]
(with-meta
(mapcat (partial fmap cv) cg)
(meta cv)))
([cv cg cvs]
(with-meta
(mapcat #(fmap cv % cvs) cg)
(meta cv))))
(defn coll-fapply
([cv cg]
(into (empty cv) (mapcat (partial fmap cv) cg)))
([cv cg cvs]
(into (empty cv) (mapcat #(fmap cv % cvs) cg))))
(defn eduction-fapply
([ev eg]
(eduction (mapcat (partial fmap ev)) eg))
([ev eg evs]
(eduction (mapcat #(fmap ev % evs)) eg)))
(defn coll-pure
([cv v]
(conj (empty cv) v))
([cv v vs]
(into (coll-pure cv v) vs)))
(defn seq-pure
([cv v]
(cons v nil))
([cv v vs]
(cons v vs)))
(defn eduction-pure
([e v]
(eduction [v]))
([e v vs]
(eduction (cons v vs))))
(defn hashmap-pure
([m v]
(coll-pure m [nil v]))
([m v vs]
(into (empty m)
(if (vector? v)
(cons v vs)
(apply hash-map v vs)))))
(defn collreduce-bind
([cr g]
(r/mapcat g cr))
([cr g ss]
(throw (UnsupportedOperationException. "bind for reducibles does not support varargs."))))
(defn reducible-bind
([c g]
(into (empty c) (r/mapcat g c)))
([c g ss]
(into (empty c) (apply mapcat g c ss))))
(let [flatten-keys (fn [[k x :as e]]
(if (map? x)
(map (fn [[kx vx]]
[(if (and k kx)
(vec (flatten [k kx]))
(or k kx))
vx])
x)
[e]))]
(defn hashmap-join [m]
(into (empty m) (r/mapcat flatten-keys m)))
(defn hashmap-bind
([m g]
(into (empty m)
(comp (map (fn [[k v]] [k (g v)]))
(mapcat flatten-keys))
m))
([m g ms]
(let [ms (cons m ms)]
(into (empty m)
(comp (hashmap-fmap-xf g ms)
(mapcat flatten-keys))
ms)))))
(defn coll-bind
([c g]
(into (empty c) (mapcat g) c))
([c g ss]
(into (empty c) (apply mapcat g c ss))))
(defn coll-join [c]
(with-meta
(persistent! (reduce (fn [acc e] (if (coll? e)
(reduce conj! acc e)
(conj! acc e)))
(transient (empty c)) c))
(meta c)))
(defn seq-join [s]
(let [o (op s)]
(with-meta
(reduce (fn [acc e]
(if (sequential? e)
(o acc e)
(cons e acc)))
(id s) s)
(meta s))))
(defn list-join [c]
(with-meta
(apply list (seq-join c))
(meta c)))
(defn eduction-join [e]
(eduction (mapcat #(if (sequential? %) % [%])) e))
(defn collreduce-join [c]
(r/mapcat #(if (coll? %) % [%]) c))
(defn reducible-join [c]
(into (empty c) (collreduce-join c)))
(defn list-bind
([c g]
(with-meta
(apply list (mapcat g c))
(meta c)))
([c g ss]
(with-meta
(apply list (apply mapcat g c ss))
(meta c))))
(defn seq-bind
([c g]
(with-meta
(mapcat g c)
(meta c)))
([c g ss]
(with-meta
(apply mapcat g c ss)
(meta c))))
(defn eduction-bind
([e g]
(eduction (mapcat g) e))
([e g ss]
(eduction (apply mapcat g e ss))))
(defn seq-unbind
([s g]
(cons (g s) (lazy-seq (seq-unbind (rest s) g))))
([s g ss]
(cons (apply g s ss) (lazy-seq (seq-unbind (rest s) g (map rest ss))))))
(defn collreduce-extract [c]
(reduce + (r/take 1 c)))
(defn coll-op* [zero]
(fn coll-op
([]
zero)
([x]
x)
([x y]
(into x y))
([x y z]
(into x cat [y z]))
([x y z w]
(into x cat [y z w]))
([x y z w & ws]
(into x cat (into [y z w] ws)))))
(defn collreduce-op
([]
[])
([x]
x)
([x y]
(if (instance? clojure.core.protocols.CollReduce y)
(r/cat x y)
(into x y)))
([x y z]
(collreduce-op x (collreduce-op y z)))
([x y z w]
(collreduce-op (collreduce-op x y) (collreduce-op z w)))
([x y z w & ws]
(collreduce-op (collreduce-op x y z w) (r/fold collreduce-op ws))))
(defn reducible-op
([]
[])
([x]
x)
([x y]
(into x y))
([x y z]
(into x (collreduce-op y z)))
([x y z w]
(into x (collreduce-op y z w)))
([x y z w & ws]
(into x (apply collreduce-op y z w ws))))
(defn seq-op* [zero]
(fn seq-op
([]
zero)
([x]
x)
([x y]
(concat x y))
([x y z]
(concat x y z))
([x y z w]
(concat x y z w))
([x y z w & ws]
(apply concat x y z w ws))))
(defn eduction-op
([]
(eduction))
([x]
x)
([x y]
(eduction cat [x y]))
([x y z]
(eduction cat [x y z]))
([x y z w]
(eduction cat [x y z w]))
([x y z w & ws]
(eduction cat (into [x y z w] ws))))
(defn list-op
([]
(list))
([x]
x)
([x y]
(apply list (concat x y)))
([x y z]
(apply list (concat x y z)))
([x y z w]
(apply list (concat x y z w)))
([x y z w & ws]
(apply list (apply concat x y z w ws))))
(defn collection-foldmap
([c g]
(if-let [e (first c)]
(let [ge (g e)]
(r/fold (op ge) (r/map g c)))))
([c g f init]
(f init (r/fold f (r/map g c))))
([cx g f init cy]
(loop [acc init cx cx cy cy]
(if cx
(recur (f acc (g (first cx) (first cy))) (next cx) (next cy))
acc)))
([cx g f init cy cz]
(loop [acc init cx cx cy cy cz cz]
(if cx
(recur (f acc (g (first cx) (first cy) (first cz)))
(next cx) (next cy) (next cz))
acc)))
([cx g f init cy cz cw]
(loop [acc init cx cx cy cy cz cz cw cw]
(if cx
(recur (f acc (g (first cx) (first cy) (first cz) (first cw)))
(next cx) (next cy) (next cz) (next cw))
acc)))
([cx g f init cy cz cw cws]
(loop [acc init cx cx cy cy cz cz cw cw cws cws]
(if cx
(recur (f acc (apply g (first cx) (first cy) (first cz) (first cw)
(map first cws)))
(next cx) (next cy) (next cz) (next cw) (map next cws))
acc))))
(defn collection-fold
([c]
(if-let [e (first c)]
(r/fold (op e) c)))
([c f init]
(f init (r/fold f c)))
([cx f init cy]
(collection-foldmap cx (op (first cx)) f init cy))
([cx f init cy cz]
(collection-foldmap cx (op (first cx)) f init cy cz))
([cx f init cy cz cw]
(collection-foldmap cx (op (first cx)) f init cy cz cw))
([cx f init cy cz cw cws]
(loop [acc init cx cx cy cy cz cz cw cw cws cws]
(if (and cx cy cz cw (not-any? empty? cws))
(recur (f acc (apply (op (first cx)) (first cx) (first cy) (first cz) (first cw) (map first cws)))
(next cx) (next cy) (next cz) (next cw) (map next cws))
acc))))
(defn eduction-foldmap
([c g]
(if-let [e (first c)]
(transduce (map g) (op (g e)) c)))
([c g f init]
(transduce (map g) f init c))
([cx g f init cy]
(collection-foldmap cx g f init cy))
([cx g f init cy cz]
(collection-foldmap cx g f init cy cz))
([cx g f init cy cz cw]
(collection-foldmap cx g f init cy cz cz cw))
([cx g f init cy cz cw cws]
(collection-foldmap cx g f init cy cz cz cw cws)))
(defn hashmap-fold
([m]
(collection-fold (vals m)))
([m f init]
(collection-fold (vals m) f init))
([mx f init my]
(collection-fold (vals mx) f init (vals my)))
([mx f init my mz]
(collection-fold (vals mx) f init (vals my) (vals mz)))
([mx f init my mz mw]
(collection-fold (vals mx) f init (vals my) (vals mz) (vals mw)))
([mx f init my mz mw mws]
(collection-fold (vals mx) f init (vals my) (vals mz) (vals mw) (map vals mws))))
(defn collfold-fold
([c]
(if-let [e (first (into [] (r/take 1 c)))]
(collection-fold c (op e) (id e))))
([c f init]
(collection-fold c f init)))
(defmacro extend-collection [t]
`(extend ~t
Functor
{:fmap coll-fmap}
Applicative
{:pure coll-pure
:fapply coll-fapply}
Monad
{:join coll-join
:bind coll-bind}
Comonad
{:extract peek
:unbind default-unbind}
Foldable
{:fold collection-fold
:foldmap collection-foldmap}
Magma
{:op (constantly (coll-op* []))}
Monoid
{:id empty}))
(defmacro extend-vector [t]
`(extend ~t
Functor
{:fmap reducible-fmap}
Applicative
{:pure coll-pure
:fapply reducible-fapply}
Monad
{:join reducible-join
:bind reducible-bind}
Magma
{:op (constantly reducible-op)}))
(defmacro extend-list [t]
`(extend ~t
Functor
{:fmap list-fmap}
Applicative
{:pure coll-pure
:fapply list-fapply}
Monad
{:join list-join
:bind list-bind}
Magma
{:op (constantly list-op)}))
(defmacro extend-seq [t]
`(extend ~t
Functor
{:fmap seq-fmap}
Applicative
{:pure seq-pure
:fapply seq-fapply}
Monad
{:join seq-join
:bind seq-bind}
Comonad
{:extract first
:unbind seq-unbind}
Magma
{:op (constantly (seq-op* (list)))}))
(defmacro extend-lazyseq [t]
`(extend ~t
Functor
{:fmap seq-fmap}
Applicative
{:pure seq-pure
:fapply seq-fapply}
Monad
{:join seq-join
:bind seq-bind}
Comonad
{:extract first
:unbind seq-unbind}
Magma
{:op (constantly (seq-op* (lazy-seq)))}))
(defmacro extend-eduction [t]
`(extend ~t
Functor
{:fmap eduction-fmap}
Applicative
{:pure eduction-pure
:fapply eduction-fapply}
Monad
{:join eduction-join
:bind eduction-bind}
Comonad
{:extract first
:unbind default-unbind}
Foldable
{:fold collection-fold
:foldmap eduction-foldmap}
Magma
{:op (constantly eduction-op)}
Monoid
{:id (constantly (eduction))}))
(defmacro extend-set [t]
`(extend ~t
Functor
{:fmap reducible-fmap}
Applicative
{:pure coll-pure
:fapply reducible-fapply}
Monad
{:join coll-join
:bind reducible-bind}
Comonad
{:extract first
:unbind default-unbind}
Magma
{:op (constantly (coll-op* #{}))}))
(defmacro extend-hashmap [t]
`(extend ~t
Functor
{:fmap hashmap-fmap}
Applicative
{:pure hashmap-pure
:fapply hashmap-fapply}
Monad
{:join hashmap-join
:bind hashmap-bind}
Comonad
{:extract (comp val first)
:unbind default-unbind}
Foldable
{:fold hashmap-fold
:foldmap default-foldmap}
Magma
{:op (constantly (coll-op* {}))}))
(extend clojure.core.protocols.CollReduce
Functor
{:fmap collreduce-fmap}
Applicative
{:pure collreduce-pure
:fapply collreduce-fapply}
Monad
{:join collreduce-join
:bind collreduce-bind}
Comonad
{:extract collreduce-extract
:unbind default-unbind}
Magma
{:op (constantly collreduce-op)})
(extend clojure.core.reducers.CollFold
Foldable
{:fold collfold-fold
:foldmap default-foldmap})
(declare create-mapentry)
(defn mapentry-fmap
([[ke ve] g]
(create-mapentry ke (g ve)))
([[ke ve] g es]
(create-mapentry ke (apply g ve (vals es)))))
(defn mapentry-pure [e v]
(create-mapentry nil v))
(defn mapentry-fapply
([[ke ve :as e] [kg vg]]
(if (or (nil? kg) (= ke kg))
(create-mapentry ke (vg ve))
e))
([[ke ve :as e] [kg vg] es]
(if (or (nil? kg)
(not-any? (fn [[k _]]
(not= k kg))
(cons e es)))
(create-mapentry ke (apply vg ve (map val es)))
e)))
(defn mapentry-join [[k x :as e]]
(if (vector? x)
(let [[kx vx] x]
(create-mapentry (if (and k kx)
(vec (flatten [k kx]))
(or k kx))
vx))
e))
(defn mapentry-id [[kx vx]]
(create-mapentry (id kx) (id vx)))
(defn mapentry-op [e]
(fn
([]
(id e))
([x]
x)
([[kx vx] [ky vy]]
(create-mapentry ((op kx) kx ky) ((op vx) vx vy)))
([[kx vx] [ky vy] [kz vz]]
(create-mapentry ((op kx) kx ky kz) ((op vx) vx vy vz)))
([[kx vx] [ky vy] [kz vz] [kw vw]]
(create-mapentry ((op kx) kx ky kz kw) ((op vx) vx vy vz vw)))
([[kx vx] [ky vy] [kz vz] [kw vw] es]
(create-mapentry (apply (op kx) kx ky kz kw (map key es))
(apply (op vx) vx vy kz kw (map val es))))))
(defn mapentry-foldmap
([e g]
(g (val e)))
([e g f init]
(f init (g (val e))))
([e g f init e1]
(f init (g (val e) (val e1))))
([e g f init e1 e2]
(f init (g (val e) (val e1) (val e2))))
([e g f init e1 e2 e3]
(f init (g (val e) (val e1) (val e2) (val e3))))
([e g f init e1 e2 e3 es]
(f init (apply g (val e) (val e1) (val e2) (val e3) (map val es)))))
(defn mapentry-fold
([e]
(val e))
([e f init]
(f init (val e)))
([e f init e1]
(mapentry-foldmap e (op e) f init e1))
([e f init e1 e2]
(mapentry-foldmap e (op e) f init e1 e2))
([e f init e1 e2 e3]
(mapentry-foldmap e (op e) f init e1 e2 e3))
([e f init e1 e2 e3 es]
(f init (apply (op e) (val e) (val e1) (val e2) (val e3) (map val es)))))
(defmacro extend-mapentry [t]
`(extend ~t
Functor
{:fmap mapentry-fmap}
Applicative
{:pure mapentry-pure
:fapply mapentry-fapply}
Monad
{:join mapentry-join
:bind default-bind}
Comonad
{:extract val
:unbind default-unbind}
Magma
{:op mapentry-op}
Monoid
{:id mapentry-id}
Foldable
{:fold mapentry-fold
:foldmap mapentry-foldmap}))
(defn ^:private deref-resolve [s]
(deref (resolve (symbol (name s)))))
(defn ^:private to-string
([s]
(if (sequential? s)
(cs/join s)
(str s)))
([s ss]
(apply str (to-string s) (map to-string ss))))
(extend-type String
Functor
(fmap
([s g]
(to-string (g s)))
([s g ss]
(to-string (apply g s ss))))
Applicative
(fapply
([sv sg]
(fmap sv (deref-resolve sg)))
([sv sg svs]
(fmap sv (deref-resolve sg) svs)))
(pure
([_ x]
(to-string x)
(str x))
([_ x xs]
(to-string x xs)))
Magma
(op [x]
str)
Monoid
(id [s] ""))
(extend-type Number
Magma
(op [x]
+)
Monoid
(id [x] 0))
(extend-type Double
Monoid
(id [x] 0.0))
(extend-type Float
Monoid
(id [x] 0.0))
(defn keyword-fmap
([k g]
(keyword (fmap (name k) g)))
([k g ks]
(keyword (fmap (name k) g (map name ks)))))
(defn keyword-pure
([k v]
(keyword (str v)))
([k v vs]
(keyword (apply str v vs))))
(defn keyword-fapply
([kv kg]
(keyword-fmap kv (deref-resolve kg)))
([kv kg kvs]
(keyword-fmap kv (deref-resolve kg) kvs)))
(def keyword-id (constantly (keyword "")))
(defn keyword-op
([] (keyword ""))
([x]
x)
([x y]
(keyword (str (name x) (name y))))
([x y z]
(keyword (str (name x) (name y) (name z))))
([x y z w]
(keyword (str (name x) (name y) (name z) (name w))))
([x y z w ws]
(keyword (apply str (name x) (name y) (name z) (name w) ws))))
(defmacro extend-keyword [t]
`(extend ~t
Functor
{:fmap keyword-fmap}
Applicative
{:fapply keyword-fapply
:pure keyword-pure}
Magma
{:op (constantly keyword-op)}
Monoid
{:id keyword-id}))
(let [identity? (fn [f] (identical? identity f))]
(defn function-op
([] identity)
([x]
x)
([x y & zs]
(apply comp
(cond
(identity? x) y
(identity? y) x
:default (comp x y))
(remove identity? zs)))))
(defn function-fmap
([f g]
(function-op g f))
([f g hs]
(fn
([]
(apply g (f) (map #(%) hs)))
([x]
(apply g (f x) (map #(% x) hs)))
([x & xs]
(apply g (apply f x xs) (map #(apply % x xs) hs))))))
(defn function-fapply
([f g]
(if (identical? identity g)
f
(fn
([]
((g) (f)))
([x]
((g x) (f x)))
([x & xs]
((apply g x xs) (apply f x xs))))))
([f g hs]
(fn
([]
(apply (g) (f) (map #(%) hs)))
([x]
(apply (g x) (f x) (map #(% x) hs)))
([x & xs]
(apply (apply g x xs) (apply f x xs) (map #(apply % x xs) hs))))))
(defn function-pure [f x]
(constantly x))
(defn function-join [f]
(fn
([]
(with-context f
((f))))
([x]
(with-context f
((f x) x)))
([x & xs]
(with-context f
(apply (apply f x xs) x xs)))))
(defn function-bind
([f g]
(join (fmap f g)))
([f g hs]
(join (fmap f g hs))))
(defn function-extract [f]
(f))
(defn function-fold
([fx]
(fx))
([fx f init]
(f init (fx)))
([fx f init fy]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy)))))
([fx f init fy fz]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy) (fz)))))
([fx f init fy fz fw]
(let [fxv (fx)
op-fx (op fxv)]
(f init (op-fx fxv (fy) (fz) (fw)))))
([fx f init fy fz fw fws]
(let [fxv (fx)
op-fx (op fxv)]
(f init (apply op-fx fxv (fy) (fz) (fw) (map #(%) fws))))))
(defmacro extend-function [t]
`(extend ~t
Functor
{:fmap function-fmap}
Applicative
{:fapply function-fapply
:pure function-pure}
Monad
{:join function-join
:bind function-bind}
Comonad
{:extract function-extract
:unbind default-unbind}
Foldable
{:fold function-fold
:foldmap default-foldmap}
Magma
{:op (constantly function-op)}
Monoid
{:id (constantly identity)}))
(defn reference-fmap
([r g]
(pure r (g (deref r))))
([r g rs]
(pure r (apply g (deref r) (map deref rs)))))
(defn reference-fapply!
([rv rg]
(fmap! rv (deref rg)))
([rv rg rvs]
(apply fmap! rv (deref rg) rvs)))
(defn reference-fapply
([rv rg]
(reference-fmap rv (deref rg)))
([rv rg rvs]
(reference-fmap rv (deref rg) rvs)))
(defn reference-join! [r]
(if (deref? @r)
(fmap! r deref)
r))
(defn reference-join [r]
(if (deref? @r)
(fmap! r deref)
r))
(defn reference-bind!
([mv g]
(fmap! (fmap! mv g) deref))
([mv g mvs]
(fmap! (apply fmap! mv g mvs) deref)))
(defn reference-bind
([mv g]
(fmap! (fmap mv g) deref))
([mv g mvs]
(fmap! (fmap mv g mvs) deref)))
(defn reference-op [r]
(fn
([] (id r))
([r & rs]
(if rs
(fmap r (op @r) rs)
r))))
(defn reference-foldmap
([rx g]
(g @rx))
([rx g f init]
(f init (g @rx)))
([rx g f init ry]
(f init (g @rx @ry)))
([rx g f init ry rz]
(f init (g @rx @ry @rz)))
([rx g f init ry rz rw]
(f init (g @rx @ry @rz @rw)))
([rx g f init ry rz rw rws]
(f init (apply g @rx @ry @rz @rw (map deref rws)))))
(defn reference-fold
([r]
(deref r))
([r f init]
(f init (deref r)))
([rx f init ry]
(f init ((op @rx) @rx @ry)))
([rx f init ry rz]
(f init ((op @rx) @rx @ry @rz)))
([rx f init ry rz rw]
(f init ((op @rx) @rx @ry @rz @rw)))
([rx f init ry rz rw rws]
(f init (apply (op @rx) @rx @ry @rz @rw (map deref rws)))))
(defn atom-fmap!
([a g]
(doto a (swap! g)))
([ax g ry]
(doto ax (swap! g @ry)))
([ax g ry rz]
(doto ax (swap! g @ry @rz)))
([ax g ry rz rw]
(doto ax (swap! g @ry @rz @rw)))
([ax g ry rz rw rws]
(do
(apply swap! ax g @ry @rz @rw (map deref rws))
ax)))
(defn atom-pure [_ v]
(atom v))
(defn atom-id [a]
(atom (id (deref a))))
(defn ref-fmap!
([rx g]
(doto rx (alter g)))
([rx g ry]
(doto rx (alter g @ry)))
([rx g ry rz]
(doto rx (alter g @ry @rz)))
([rx g ry rz rw]
(doto rx (alter g @ry @rz @rw)))
([rx g ry rz rw rws]
(do
(apply alter rx g @ry @rz @rw (map deref rws))
rx)))
(defn ref-pure [_ v]
(ref v))
(defn ref-id [r]
(ref (id @r)))
(defmacro ^:private vswap!! [vol f ry rz rw rws]
`(vswap! ~vol ~f ~ry ~rz ~rw ~@rws))
(defn volatile-fmap!
([v g]
(doto v (vswap! g)))
([vx g ry]
(doto vx (vswap! g @ry)))
([vx g ry rz]
(doto vx (vswap! g @ry @rz)))
([vx g ry rz rw]
(doto vx (vswap! g @ry @rz @rw)))
([vx g ry rz rw rws]
(do
(vswap!! vx g @ry @rz @rw (map deref rws))
vx)))
(defn volatile-pure [_ v]
(volatile! v))
(defn volatile-id [a]
(volatile! (id (deref a))))
(defmacro extend-ideref [t]
`(extend ~t
Functor
{:fmap reference-fmap}
Applicative
{:fapply reference-fapply}
PseudoApplicative
{:fapply! reference-fapply!}
Monad
{:join reference-join
:bind reference-bind}
PseudoMonad
{:join! reference-join!
:bind! reference-bind!}
Comonad
{:extract deref
:unbind default-unbind}
PseudoComonad
{:unbind! default-unbind!}
Foldable
{:fold reference-fold
:foldmap reference-foldmap}
Magma
{:op reference-op}))
(defmacro extend-atom [t]
`(extend ~t
PseudoFunctor
{:fmap! atom-fmap!}
Applicative
{:pure atom-pure
:fapply reference-fapply}
Monoid
{:id atom-id}))
(defmacro extend-ref [t]
`(extend ~t
PseudoFunctor
{:fmap! ref-fmap!}
Applicative
{:pure ref-pure
:fapply reference-fapply}
Monoid
{:id ref-id}))
(defmacro extend-volatile [t]
`(extend ~t
PseudoFunctor
{:fmap! volatile-fmap!}
Applicative
{:pure volatile-pure
:fapply reference-fapply}
Monoid
{:id volatile-id}))
(defn just-fmap
([jv g]
(pure jv (g (value jv))))
([jv g jvs]
(when-not (some nil? jvs)
(pure jv (apply g (value jv) (map value jvs))))))
(defn just-fapply
([jv jg]
(when jg
(fmap jv (value jg))))
([jv jg jvs]
(when jg
(fmap jv (value jg) jvs))))
(defn just-bind
([jv g]
(g (value jv)))
([jv g jvs]
(when-not (some nil? jvs)
(apply g (value jv) (map value jvs)))))
(defn just-join [jjv]
(let [v (value jjv)]
(if (or (not v) (satisfies? Maybe v)) v jjv)))
(defn just-foldmap
([x g]
(g (value x)))
([x g f init]
(f init (g (value x))))
([x g f init y]
(when y
(f init (g (value x) (value y)))))
([x g f init y z]
(when (and y z)
(f init (g (value x) (value y) (value y)))))
([x g f init y z w]
(when (and y z w)
(f init (g (value x) (value y) (value z) (value w)))))
([x g f init y z w ws]
(when (and y z w (not-any? nil? ws))
(f init (apply g (value x) (value y) (value z) (value w) (map value ws))))))
(defn just-fold
([x]
(value x))
([x f init]
(f init (value x)))
([x f init y]
(just-foldmap x ((op (value x)) (value x) f init y)))
([x f init y z]
(just-foldmap x ((op (value x)) (value x) f init y z)))
([x f init y z w]
(just-foldmap x ((op (value x)) (value x) f init y z w)))
([x f init y z w ws]
(just-foldmap x ((op (value x)) (value x) f init y z w ws))))
(defn just-op
([] nil)
([x] x)
([x y & zs]
(if x
(let [vx (value x)
o (op vx)
init (if-let [vy (value y)] (o vx vy) vx)
res (if zs (transduce (comp (map value) (remove nil?)) o init zs) init)]
(if (= vx res) x (pure x res)))
(apply just-op y zs))))
(defmacro extend-just [t just-pure]
`(extend ~t
Functor
{:fmap just-fmap}
Applicative
{:pure ~just-pure
:fapply just-fapply}
Monad
{:join just-join
:bind just-bind}
Comonad
{:extract value
:unbind default-unbind}
Foldable
{:fold just-fold
:foldmap just-foldmap}
Magma
{:op (constantly just-op)}
Monoid
{:id (constantly nil)}))
(extend-type nil
Functor
(fmap
([_ _] nil)
([_ _ _] nil))
PseudoFunctor
(fmap!
([_ _] nil)
([_ _ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil))
PseudoApplicative
(fapply!
([_ _] nil)
([_ _ _] nil))
Monad
(bind
([_ _] nil)
([_ _ _] nil))
(join [_] nil)
PseudoMonad
(bind!
([_ _] nil)
([_ _ _] nil))
(join! [_] nil)
Comonad
(extract [_]
nil)
(unbind
([_ _] nil)
([_ _ _] nil))
PseudoComonad
(unbind!
([_ _] nil)
([_ _ _] nil))
Foldable
(fold
([_] nil)
([_ _ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil)
([_ _ _ _ _ _ _] nil))
(foldmap
([_ _] nil)
([_ _ _ _] nil)
([_ _ _ _ _] nil)
([_ _ _ _ _ _] nil)
([_ _ _ _ _ _ _] nil)
([_ _ _ _ _ _ _ _] nil))
Magma
(op [_] just-op)
Monoid
(id [_] nil)
Maybe
(value [_] nil))
|
86f45df2453f6806301afe65af661a79b3211f1ac10111f572734545c52fae62 | andersfugmann/amqp-client | thread.ml | module type T = sig
module Deferred : sig
type 'a t
val all_unit : unit t list -> unit t
val try_with : (unit -> 'a t) -> [> `Error of exn | `Ok of 'a ] t
module List : sig
val init : f:(int -> 'a t) -> int -> 'a list t
val iter : ?how:[`Sequential | `Parallel] -> f:('a -> unit t) -> 'a list -> unit t
end
end
val ( >>= ) : 'a Deferred.t -> ('a -> 'b Deferred.t) -> 'b Deferred.t
val ( >>| ) : 'a Deferred.t -> ('a -> 'b) -> 'b Deferred.t
val return : 'a -> 'a Deferred.t
val after : float -> unit Deferred.t
val spawn : ?exn_handler:(exn -> unit Deferred.t) -> unit Deferred.t -> unit
val with_timeout : int -> 'a Deferred.t -> [ `Result of 'a | `Timeout ] Deferred.t
module Ivar : sig
type 'a t
val create : unit -> 'a t
val create_full : 'a -> 'a t
val fill : 'a t -> 'a -> unit
val read : 'a t -> 'a Deferred.t
val is_full : 'a t -> bool
val fill_if_empty : 'a t -> 'a -> unit
end
module Reader : sig
type t
val close : t -> unit Deferred.t
val read : t -> bytes -> [ `Eof of int | `Ok ] Deferred.t
end
module Writer : sig
type t
val write : t -> string -> unit
val close : t -> unit Deferred.t
val flush : t -> unit Deferred.t
end
module Tcp : sig
val connect : exn_handler:(exn -> unit Deferred.t) -> ?nodelay:unit -> string -> int ->
(Reader.t * Writer.t) Deferred.t
end
module Log : sig
val debug : ('a, unit, string, unit) format4 -> 'a
val info : ('a, unit, string, unit) format4 -> 'a
val error : ('a, unit, string, unit) format4 -> 'a
end
module Pipe : sig
module Writer : sig type 'a t end
module Reader : sig type 'a t end
val create : unit -> 'a Reader.t * 'a Writer.t
val set_size_budget : 'a Writer.t -> int -> unit
val flush : 'a Writer.t -> unit Deferred.t
val interleave_pipe : 'a Reader.t Reader.t -> 'a Reader.t
val write : 'a Writer.t -> 'a -> unit Deferred.t
val write_without_pushback : 'a Writer.t -> 'a -> unit
val transfer_in : from:'a Queue.t -> 'a Writer.t -> unit Deferred.t
val close : 'a Writer.t -> unit Deferred.t
val read : 'a Reader.t -> [ `Eof | `Ok of 'a ] Deferred.t
val iter : 'a Reader.t -> f:('a -> unit Deferred.t) -> unit Deferred.t
val iter_without_pushback : 'a Reader.t -> f:('a -> unit) -> unit Deferred.t
val close_without_pushback : 'a Writer.t -> unit
end
module Scheduler : sig
val go : unit -> unit
val shutdown : int -> unit
end
end
| null | https://raw.githubusercontent.com/andersfugmann/amqp-client/e6e92225b91742fa8777a02ad9b59a1dde45e752/lib/thread.ml | ocaml | module type T = sig
module Deferred : sig
type 'a t
val all_unit : unit t list -> unit t
val try_with : (unit -> 'a t) -> [> `Error of exn | `Ok of 'a ] t
module List : sig
val init : f:(int -> 'a t) -> int -> 'a list t
val iter : ?how:[`Sequential | `Parallel] -> f:('a -> unit t) -> 'a list -> unit t
end
end
val ( >>= ) : 'a Deferred.t -> ('a -> 'b Deferred.t) -> 'b Deferred.t
val ( >>| ) : 'a Deferred.t -> ('a -> 'b) -> 'b Deferred.t
val return : 'a -> 'a Deferred.t
val after : float -> unit Deferred.t
val spawn : ?exn_handler:(exn -> unit Deferred.t) -> unit Deferred.t -> unit
val with_timeout : int -> 'a Deferred.t -> [ `Result of 'a | `Timeout ] Deferred.t
module Ivar : sig
type 'a t
val create : unit -> 'a t
val create_full : 'a -> 'a t
val fill : 'a t -> 'a -> unit
val read : 'a t -> 'a Deferred.t
val is_full : 'a t -> bool
val fill_if_empty : 'a t -> 'a -> unit
end
module Reader : sig
type t
val close : t -> unit Deferred.t
val read : t -> bytes -> [ `Eof of int | `Ok ] Deferred.t
end
module Writer : sig
type t
val write : t -> string -> unit
val close : t -> unit Deferred.t
val flush : t -> unit Deferred.t
end
module Tcp : sig
val connect : exn_handler:(exn -> unit Deferred.t) -> ?nodelay:unit -> string -> int ->
(Reader.t * Writer.t) Deferred.t
end
module Log : sig
val debug : ('a, unit, string, unit) format4 -> 'a
val info : ('a, unit, string, unit) format4 -> 'a
val error : ('a, unit, string, unit) format4 -> 'a
end
module Pipe : sig
module Writer : sig type 'a t end
module Reader : sig type 'a t end
val create : unit -> 'a Reader.t * 'a Writer.t
val set_size_budget : 'a Writer.t -> int -> unit
val flush : 'a Writer.t -> unit Deferred.t
val interleave_pipe : 'a Reader.t Reader.t -> 'a Reader.t
val write : 'a Writer.t -> 'a -> unit Deferred.t
val write_without_pushback : 'a Writer.t -> 'a -> unit
val transfer_in : from:'a Queue.t -> 'a Writer.t -> unit Deferred.t
val close : 'a Writer.t -> unit Deferred.t
val read : 'a Reader.t -> [ `Eof | `Ok of 'a ] Deferred.t
val iter : 'a Reader.t -> f:('a -> unit Deferred.t) -> unit Deferred.t
val iter_without_pushback : 'a Reader.t -> f:('a -> unit) -> unit Deferred.t
val close_without_pushback : 'a Writer.t -> unit
end
module Scheduler : sig
val go : unit -> unit
val shutdown : int -> unit
end
end
| |
5524612d26e14e7e48b8c6ad60f775350e11f847cb64245f9d7a681332a3a4a7 | mirage/ocaml-github | github_json.ml |
Adapters used by atdgen to turn Github 's representation of variants
into an ATD - compatible representation .
Adapters used by atdgen to turn Github's representation of variants
into an ATD-compatible representation.
*)
module Adapter = struct
module Ref =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "ref_type"
let value_field_name = "ref"
let known_tags = None
end)
module Payload =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "type"
let value_field_name = "payload"
let known_tags = None
end)
module Issue_comment_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (["created"; "edited"; "deleted"], "Unknown")
end)
module Issues_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (
[
"assigned";
"unassigned";
"labeled";
"unlabeled";
"opened";
"edited";
"closed";
"reopened";
],
"Unknown"
)
end)
module Pull_request_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (
[
"assigned";
"unassigned";
"labeled";
"unlabeled";
"opened";
"edited";
"closed";
"reopened";
"synchronize";
],
"Unknown"
)
end)
module Pull_request_review_comment_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (["created"; "edited"; "deleted"], "Unknown")
end)
module Event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "type"
let value_field_name = "payload"
let known_tags =
Some (
[
"CommitCommentEvent";
"CreateEvent";
"DeleteEvent";
"DownloadEvent";
"FollowEvent";
"ForkEvent";
"ForkApplyEvent";
"GistEvent";
"GollumEvent";
"IssueCommentEvent";
"IssuesEvent";
"MemberEvent";
"PublicEvent";
"PullRequestEvent";
"PullRequestReviewCommentEvent";
"PushEvent";
"ReleaseEvent";
"RepositoryEvent";
"StatusEvent";
"WatchEvent";
],
"Unknown"
)
end)
module Hook =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "name"
let value_field_name = "config"
let known_tags = Some (["web"], "Unknown")
end)
end
| null | https://raw.githubusercontent.com/mirage/ocaml-github/304bd487620d3ea9486812047daf7b5062fc61e5/lib_data/github_json.ml | ocaml |
Adapters used by atdgen to turn Github 's representation of variants
into an ATD - compatible representation .
Adapters used by atdgen to turn Github's representation of variants
into an ATD-compatible representation.
*)
module Adapter = struct
module Ref =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "ref_type"
let value_field_name = "ref"
let known_tags = None
end)
module Payload =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "type"
let value_field_name = "payload"
let known_tags = None
end)
module Issue_comment_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (["created"; "edited"; "deleted"], "Unknown")
end)
module Issues_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (
[
"assigned";
"unassigned";
"labeled";
"unlabeled";
"opened";
"edited";
"closed";
"reopened";
],
"Unknown"
)
end)
module Pull_request_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (
[
"assigned";
"unassigned";
"labeled";
"unlabeled";
"opened";
"edited";
"closed";
"reopened";
"synchronize";
],
"Unknown"
)
end)
module Pull_request_review_comment_event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "action"
let value_field_name = "changes"
let known_tags =
Some (["created"; "edited"; "deleted"], "Unknown")
end)
module Event =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "type"
let value_field_name = "payload"
let known_tags =
Some (
[
"CommitCommentEvent";
"CreateEvent";
"DeleteEvent";
"DownloadEvent";
"FollowEvent";
"ForkEvent";
"ForkApplyEvent";
"GistEvent";
"GollumEvent";
"IssueCommentEvent";
"IssuesEvent";
"MemberEvent";
"PublicEvent";
"PullRequestEvent";
"PullRequestReviewCommentEvent";
"PushEvent";
"ReleaseEvent";
"RepositoryEvent";
"StatusEvent";
"WatchEvent";
],
"Unknown"
)
end)
module Hook =
Atdgen_runtime.Json_adapter.Type_and_value_fields.Make (struct
let type_field_name = "name"
let value_field_name = "config"
let known_tags = Some (["web"], "Unknown")
end)
end
| |
c3f23f5f0826a626f598060cd43f8cf55fff5008e5e3feea89731755bbb2f2d0 | broadinstitute/firecloud-ui | user.cljs | (ns broadfcui.utils.user
(:require
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
))
(defonce ^:private user-listeners (atom {}))
(defn add-user-listener [k on-change]
(swap! user-listeners assoc k on-change))
(defn remove-user-listener [k]
(swap! user-listeners dissoc k))
(defonce auth2-atom (atom nil))
(defn set-google-auth2-instance! [instance]
(reset! auth2-atom instance)
(-> instance
(aget "currentUser")
(js-invoke
"listen" (fn [u]
(doseq [[_ on-change] @user-listeners]
(on-change u))))))
(defn get-user []
(-> @auth2-atom (aget "currentUser") (js-invoke "get")))
(defn get-access-token []
(-> (get-user) (js-invoke "getAuthResponse") (aget "access_token")))
(defn get-bearer-token-header []
{"Authorization" (str "Bearer " (get-access-token))})
(defn get-email []
(-> (get-user) (js-invoke "getBasicProfile") (js-invoke "getEmail")))
(defn get-id []
(-> (get-user) (js-invoke "getBasicProfile") (js-invoke "getId")))
(defn get-cookie-domain []
(if (= "local.broadinstitute.org" js/window.location.hostname)
"local.broadinstitute.org"
(string/join "." (rest (string/split js/window.location.hostname ".")))))
(defn delete-access-token-cookie []
(.remove goog.net.cookies "FCtoken" "/" (get-cookie-domain)))
(defn set-access-token-cookie [token]
(if token
(.set goog.net.cookies "FCtoken" token -1 "/" (get-cookie-domain) true) ; secure cookie
(delete-access-token-cookie)))
(defn refresh-access-token [] (set-access-token-cookie (get-access-token)))
(defonce profile (atom false))
(defonce terra-preference (atom nil)) ;; initially false to disable redirects until profile is loaded
(defn reload-profile [& [on-done]]
(endpoints/profile-get
(fn [{:keys [success? get-parsed-response] :as response}]
(when success?
(let [parsed-profile (common/parse-profile (get-parsed-response))
profile-pref (if-some [pp (:preferTerra parsed-profile)]
(utils/parse-boolean pp)
true)]
(reset! profile parsed-profile)
(reset! terra-preference profile-pref)))
(when on-done (on-done response)))))
(defonce saved-ready-billing-project-names (atom []))
(defn reload-billing-projects [& [on-done]]
(endpoints/get-billing-projects
(fn [err-text projects]
(when-not err-text
(reset! saved-ready-billing-project-names (map :projectName projects)))
(when on-done (on-done err-text)))))
| null | https://raw.githubusercontent.com/broadinstitute/firecloud-ui/8eb077bc137ead105db5665a8fa47a7523145633/src/cljs/main/broadfcui/utils/user.cljs | clojure | secure cookie
initially false to disable redirects until profile is loaded | (ns broadfcui.utils.user
(:require
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
))
(defonce ^:private user-listeners (atom {}))
(defn add-user-listener [k on-change]
(swap! user-listeners assoc k on-change))
(defn remove-user-listener [k]
(swap! user-listeners dissoc k))
(defonce auth2-atom (atom nil))
(defn set-google-auth2-instance! [instance]
(reset! auth2-atom instance)
(-> instance
(aget "currentUser")
(js-invoke
"listen" (fn [u]
(doseq [[_ on-change] @user-listeners]
(on-change u))))))
(defn get-user []
(-> @auth2-atom (aget "currentUser") (js-invoke "get")))
(defn get-access-token []
(-> (get-user) (js-invoke "getAuthResponse") (aget "access_token")))
(defn get-bearer-token-header []
{"Authorization" (str "Bearer " (get-access-token))})
(defn get-email []
(-> (get-user) (js-invoke "getBasicProfile") (js-invoke "getEmail")))
(defn get-id []
(-> (get-user) (js-invoke "getBasicProfile") (js-invoke "getId")))
(defn get-cookie-domain []
(if (= "local.broadinstitute.org" js/window.location.hostname)
"local.broadinstitute.org"
(string/join "." (rest (string/split js/window.location.hostname ".")))))
(defn delete-access-token-cookie []
(.remove goog.net.cookies "FCtoken" "/" (get-cookie-domain)))
(defn set-access-token-cookie [token]
(if token
(delete-access-token-cookie)))
(defn refresh-access-token [] (set-access-token-cookie (get-access-token)))
(defonce profile (atom false))
(defn reload-profile [& [on-done]]
(endpoints/profile-get
(fn [{:keys [success? get-parsed-response] :as response}]
(when success?
(let [parsed-profile (common/parse-profile (get-parsed-response))
profile-pref (if-some [pp (:preferTerra parsed-profile)]
(utils/parse-boolean pp)
true)]
(reset! profile parsed-profile)
(reset! terra-preference profile-pref)))
(when on-done (on-done response)))))
(defonce saved-ready-billing-project-names (atom []))
(defn reload-billing-projects [& [on-done]]
(endpoints/get-billing-projects
(fn [err-text projects]
(when-not err-text
(reset! saved-ready-billing-project-names (map :projectName projects)))
(when on-done (on-done err-text)))))
|
244b4e41411d798a22f587025b983b673067bb7a7abd86fcd73b804c7e6b76cb | forward/incanter-BLAS | stats_tests.clj | core-test-cases.clj -- Unit tests of Incanter functions
by
October 31 , 2009
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; to run these tests:
;; (use 'tests core-test-cases)
;; need to load this file to define data variables
;; (use 'clojure.test)
;; then run tests
;; (run-tests 'incanter.tests.core-test-cases)
(ns incanter.stats-tests
(:use clojure.test
(incanter core stats)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; UNIT TESTS FOR incanter.stats.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; define a simple matrix for testing
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]
[10 11 12]]))
(def test-mat (matrix
[[39 10 ]
[51 20 ]
[60 30 ]
[64 40 ]
[73 50 ]
[83 60 ]
[90 70 ]
[93 80 ]
[99 90 ]
[105 100]
[110 110]
[111 120]
[113 130]
[117 140]
[120 150]
[125 160]
[130 170]
[133 180]
[133 190]
[134 200]
[138 210]
[140 220]
[145 230]
[146 240]
[148 250]]))
(def x (sel test-mat :cols 0))
(def y (sel test-mat :cols 1))
(def dataset1 (dataset [:a :b :c] [[1 2 3] [4 5 6] [7 8 9] [10 11 12]]))
(def summary-ds0 (to-dataset [[1] [4] [7]]))
(def summary-ds1 (to-dataset [[1] [3.142] [7]]))
(def summary-ds2 (to-dataset [["a"] ["b"] ["c"]]))
(def summary-ds3 (to-dataset [[:a] [:b] [:c]]))
(def summary-ds4 (to-dataset [[:a] ["b"] [:c]]))
(def summary-ds5 (to-dataset [[1] [2.1] [:c]]))
(def summary-ds6 (to-dataset [[1] [2.1] ["c"]]))
(def summary-ds7 (to-dataset [[1] [2.1] [nil]]))
(def summary-ds8 (to-dataset [["a"] ["b"] ["c"] ["d"] ["b"] ["e"] ["a"] ["b"] ["f"] ["a"] ["b"] ["e"]]))
(def summary-ds9 (to-dataset [["a" 1.2] [":b" 3] [:c 0.1] ["d" 8] ["b" 9] ["e" 7.21] ["a" 1E1] ["b" 6.0000] ["f" 1e-2] ["a" 3.0] ["b" 4] ["e" 5]]))
(deftest mean-test
(is (= (map mean (trans test-mat)) [108.0 130.0])))
(deftest variance-test
(is (= (map variance (trans test-mat)) [1001.5833333333334 5416.666666666667])))
(deftest sd-test
;; calculate the standard deviation of a variable
(is (= (sd x) 31.6478013980961))
(is (= (map sd A) [1.0 1.0 1.0 1.0])))
(deftest covariance-test
get the covariance between two variables
(is (= (Math/round (covariance x y)) 2263)))
(deftest median-test
;; calculate the median of a variable
(is (= (median x) 113.0)))
(deftest sample-tests
;; test sample function
(is (not= (sample (range 10) :replacement false) (range 10)))
(is (= (count (sample (range 10))) 10))
(is (= (count (sample (range 10) :size 5)) 5))
(is (= (count (sample (range 10) :size 5 :replacement false)) 5))
(is (= (count (sample (range 10) :replacement false)) (count (range 10))))
(is (= (into #{} (sample (range 10) :replacement false)) (into #{} (range 10))))
(is (= (nrow (sample test-mat :size 3)) 3))
(is (= (nrow (sample dataset1 :size 3)) 3)))
(deftest sample-mean
(is (= 3.0
(mean [2 3 4]))))
(deftest stdev-test
(is (= 2.138089935299395
(sd [2 4 4 4 5 5 7 9]))))
(deftest simple-regresssion-tests
(let [r (simple-regression [2 4] [1 3])]
(is (= 3.0
(predict r 2)))))
(deftest odds-ratio-test
(let [p1 9/10
p2 2/10]
(is (= 36
(odds-ratio p1 p2)))))
(deftest covariance-test
(is (= 5.333333333333333
(covariance
[3 1 3 9]
[4 4 8 8]))))
(deftest pearson-test
(is (within 0.0001 1
(correlation [5 6 7 8] [8 9 10 11]))))
(deftest correlation-ratio-example
(let [algebra [45, 70, 29, 15, 21]
geometry [40, 20, 30 42]
statistics [65, 95, 80, 70, 85, 73]]
(is (within 0.0001
0.8386
(correlation-ratio
algebra
geometry
statistics)))))
(deftest ranking-test
(is (=
{97 2, 99 3, 100 4, 101 5, 103 6, 106 7, 110 8, 112 9, 113 10, 86 1}
(rank-index [106 86 100 101 99 103 97 113 112 110]))))
(deftest spearmans-rho-test
(is (within 0.000001 (float -29/165)
(spearmans-rho [106 86 100 101 99 103 97 113 112 110]
[7 0 27 50 28 29 20 12 6 17]))))
(deftest kendalls-tau-test
(is (= 23/45
(kendalls-tau [4 10 3 1 9 2 6 7 8 5]
[5 8 6 2 10 3 9 4 7 1])))
(is (= 9/13
(kendalls-tau
[1 3 2 4 5 8 6 7 13 10 12 11 9]
[1 4 3 2 7 5 6 8 9 10 12 13 11]))))
(deftest concordancy-test
(is (discordant? [[4 2] [2 4]]))
(is (= 4
(discordant-pairs [1 2 3 4 5]
[3 4 1 2 5]))))
(deftest kendalls-tau-distance-test
(is (= 4
(kendalls-tau-distance [1 2 3 4 5]
[3 4 1 2 5])))
(is (= 2/5
(normalized-kendall-tau-distance [1 2 3 4 5]
[3 4 1 2 5]))))
(deftest jaccard-examples
(is (= 2/6
(jaccard-index #{1 2 3 4} #{3 4 5 6})))
(is (= 2/5
(jaccard-distance #{1 2 3 4} #{2 3 4 5}))))
Each set has four elements , and the intersection of these two sets has only one element : ht .
;; {ni,ig,gh,ht}
;; {na,ac,ch,ht}
Plugging this into the formula , we calculate , s = ( 2 · 1 ) / ( 4 + 4 ) = 0.25 .
(deftest dice-string
(is
(== 0.25
(dice-coefficient-str "night" "nacht"))))
(deftest get-ngrams
(is (= #{"gh" "ht" "ni" "ig"}
(bigrams "night"))))
;;TODO: think about a hamming distance that measure how far someting is off for k-way classification rathern than jsut binary classification.
(deftest hamming-ints-and-strings
(is (= 2
(hamming-distance 1011101 1001001)))
(is (= 3
(hamming-distance 2173896 2233796)))
(is (= 3
(hamming-distance "toned" "roses"))))
(deftest lee-distance-withq
(= (+ 1 2 0 3)
(lee-distance 3340 2543 6)))
since the following three edits change one into the other , and there is no way to do it with fewer than three edits :
1 . kitten ( substitution of 's ' for ' k ' )
2 . → sittin ( substitution of ' i ' for ' e ' )
3 . sittin → sitting ( insert ' g ' at the end ) .
(deftest levenshtein-kitten
(is (= 3
(levenshtein-distance "kitten" "sitting")))
(is (= 3
(levenshtein-distance "Sunday" "Saturday"))))
(deftest damerau-levenshtein-distance-tests
(let [a "TO"
b "OT"
c "OST"]
(is (= 1 (damerau-levenshtein-distance a b)))
(is (= 1 (damerau-levenshtein-distance b c)))
(is (= 3 (damerau-levenshtein-distance a c)))))
(deftest euclid
(is
(= 2.8284271247461903
(euclidean-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest manhattan
(is
(= (+ 1.0 1 2 1 1)
(manhattan-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest chebyshev
(is
(== 2
(chebyshev-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest cosine-sim
(is
0.938572618717
(cosine-similarity [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest tanimoto-sim
(is
(= 0.8591549295774648
(tanimoto-coefficient [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest benford-law-test
(let [coll [1131111 623946 325911 1799255 199654 299357 3819495 359578 285984 2214801 341104 1303129 444480 295177 450269 1758026 498061 422457 315689 1160446 573568 253962 515211 998573 677829 1289257 572988 482990 765723 337178]]
(is
(= 5.4456385557467595
(:X-sq (benford-test coll))))))
(deftest summary-datasets
(is (summarizable? 0 summary-ds0))
(is (summarizable? 0 summary-ds1))
(is (summarizable? 0 summary-ds2))
(is (summarizable? 0 summary-ds3))
(is (summarizable? 0 summary-ds4))
(is (not (summarizable? 0 summary-ds5)))
(is (not (summarizable? 0 summary-ds6)))
(is (summarizable? 0 summary-ds7))
)
(deftest simple-p-value-test
(testing "Basic p-value testing"
(is (= 1.0 (simple-p-value (range 1 11) 5.5)))
(is (< 0.999 (simple-p-value (range 1 11) 5.499)))))
(deftest t-test-test
(testing "Return values for a t-test"
(let [t-test-result
(t-test
[1,1,1,1,2,2,2,4,4,4,4]
:y [1,1,2,2,2,4,4])]
(is (> 1 (:p-value t-test-result))))))
(deftest benford-law-test
(let [coll [1131111 623946 325911 1799255 199654 299357 3819495 359578 285984 2214801 341104 1303129 444480 295177 450269 1758026 498061 422457 315689 1160446 573568 253962 515211 998573 677829 1289257 572988 482990 765723 337178]]
(is
(= 5.4456385557467595
(:X-sq (benford-test coll)))))) | null | https://raw.githubusercontent.com/forward/incanter-BLAS/da48558cc9d8296b775d8e88de532a4897ee966e/src/test/clojure/incanter/stats_tests.clj | clojure | Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution. By using this software in any fashion, you are
agreeing to be bound by the terms of this license. You must not
remove this notice, or any other, from this software.
to run these tests:
(use 'tests core-test-cases)
need to load this file to define data variables
(use 'clojure.test)
then run tests
(run-tests 'incanter.tests.core-test-cases)
UNIT TESTS FOR incanter.stats.clj
define a simple matrix for testing
calculate the standard deviation of a variable
calculate the median of a variable
test sample function
{ni,ig,gh,ht}
{na,ac,ch,ht}
TODO: think about a hamming distance that measure how far someting is off for k-way classification rathern than jsut binary classification. | core-test-cases.clj -- Unit tests of Incanter functions
by
October 31 , 2009
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
(ns incanter.stats-tests
(:use clojure.test
(incanter core stats)))
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]
[10 11 12]]))
(def test-mat (matrix
[[39 10 ]
[51 20 ]
[60 30 ]
[64 40 ]
[73 50 ]
[83 60 ]
[90 70 ]
[93 80 ]
[99 90 ]
[105 100]
[110 110]
[111 120]
[113 130]
[117 140]
[120 150]
[125 160]
[130 170]
[133 180]
[133 190]
[134 200]
[138 210]
[140 220]
[145 230]
[146 240]
[148 250]]))
(def x (sel test-mat :cols 0))
(def y (sel test-mat :cols 1))
(def dataset1 (dataset [:a :b :c] [[1 2 3] [4 5 6] [7 8 9] [10 11 12]]))
(def summary-ds0 (to-dataset [[1] [4] [7]]))
(def summary-ds1 (to-dataset [[1] [3.142] [7]]))
(def summary-ds2 (to-dataset [["a"] ["b"] ["c"]]))
(def summary-ds3 (to-dataset [[:a] [:b] [:c]]))
(def summary-ds4 (to-dataset [[:a] ["b"] [:c]]))
(def summary-ds5 (to-dataset [[1] [2.1] [:c]]))
(def summary-ds6 (to-dataset [[1] [2.1] ["c"]]))
(def summary-ds7 (to-dataset [[1] [2.1] [nil]]))
(def summary-ds8 (to-dataset [["a"] ["b"] ["c"] ["d"] ["b"] ["e"] ["a"] ["b"] ["f"] ["a"] ["b"] ["e"]]))
(def summary-ds9 (to-dataset [["a" 1.2] [":b" 3] [:c 0.1] ["d" 8] ["b" 9] ["e" 7.21] ["a" 1E1] ["b" 6.0000] ["f" 1e-2] ["a" 3.0] ["b" 4] ["e" 5]]))
(deftest mean-test
(is (= (map mean (trans test-mat)) [108.0 130.0])))
(deftest variance-test
(is (= (map variance (trans test-mat)) [1001.5833333333334 5416.666666666667])))
(deftest sd-test
(is (= (sd x) 31.6478013980961))
(is (= (map sd A) [1.0 1.0 1.0 1.0])))
(deftest covariance-test
get the covariance between two variables
(is (= (Math/round (covariance x y)) 2263)))
(deftest median-test
(is (= (median x) 113.0)))
(deftest sample-tests
(is (not= (sample (range 10) :replacement false) (range 10)))
(is (= (count (sample (range 10))) 10))
(is (= (count (sample (range 10) :size 5)) 5))
(is (= (count (sample (range 10) :size 5 :replacement false)) 5))
(is (= (count (sample (range 10) :replacement false)) (count (range 10))))
(is (= (into #{} (sample (range 10) :replacement false)) (into #{} (range 10))))
(is (= (nrow (sample test-mat :size 3)) 3))
(is (= (nrow (sample dataset1 :size 3)) 3)))
(deftest sample-mean
(is (= 3.0
(mean [2 3 4]))))
(deftest stdev-test
(is (= 2.138089935299395
(sd [2 4 4 4 5 5 7 9]))))
(deftest simple-regresssion-tests
(let [r (simple-regression [2 4] [1 3])]
(is (= 3.0
(predict r 2)))))
(deftest odds-ratio-test
(let [p1 9/10
p2 2/10]
(is (= 36
(odds-ratio p1 p2)))))
(deftest covariance-test
(is (= 5.333333333333333
(covariance
[3 1 3 9]
[4 4 8 8]))))
(deftest pearson-test
(is (within 0.0001 1
(correlation [5 6 7 8] [8 9 10 11]))))
(deftest correlation-ratio-example
(let [algebra [45, 70, 29, 15, 21]
geometry [40, 20, 30 42]
statistics [65, 95, 80, 70, 85, 73]]
(is (within 0.0001
0.8386
(correlation-ratio
algebra
geometry
statistics)))))
(deftest ranking-test
(is (=
{97 2, 99 3, 100 4, 101 5, 103 6, 106 7, 110 8, 112 9, 113 10, 86 1}
(rank-index [106 86 100 101 99 103 97 113 112 110]))))
(deftest spearmans-rho-test
(is (within 0.000001 (float -29/165)
(spearmans-rho [106 86 100 101 99 103 97 113 112 110]
[7 0 27 50 28 29 20 12 6 17]))))
(deftest kendalls-tau-test
(is (= 23/45
(kendalls-tau [4 10 3 1 9 2 6 7 8 5]
[5 8 6 2 10 3 9 4 7 1])))
(is (= 9/13
(kendalls-tau
[1 3 2 4 5 8 6 7 13 10 12 11 9]
[1 4 3 2 7 5 6 8 9 10 12 13 11]))))
(deftest concordancy-test
(is (discordant? [[4 2] [2 4]]))
(is (= 4
(discordant-pairs [1 2 3 4 5]
[3 4 1 2 5]))))
(deftest kendalls-tau-distance-test
(is (= 4
(kendalls-tau-distance [1 2 3 4 5]
[3 4 1 2 5])))
(is (= 2/5
(normalized-kendall-tau-distance [1 2 3 4 5]
[3 4 1 2 5]))))
(deftest jaccard-examples
(is (= 2/6
(jaccard-index #{1 2 3 4} #{3 4 5 6})))
(is (= 2/5
(jaccard-distance #{1 2 3 4} #{2 3 4 5}))))
Each set has four elements , and the intersection of these two sets has only one element : ht .
Plugging this into the formula , we calculate , s = ( 2 · 1 ) / ( 4 + 4 ) = 0.25 .
(deftest dice-string
(is
(== 0.25
(dice-coefficient-str "night" "nacht"))))
(deftest get-ngrams
(is (= #{"gh" "ht" "ni" "ig"}
(bigrams "night"))))
(deftest hamming-ints-and-strings
(is (= 2
(hamming-distance 1011101 1001001)))
(is (= 3
(hamming-distance 2173896 2233796)))
(is (= 3
(hamming-distance "toned" "roses"))))
(deftest lee-distance-withq
(= (+ 1 2 0 3)
(lee-distance 3340 2543 6)))
since the following three edits change one into the other , and there is no way to do it with fewer than three edits :
1 . kitten ( substitution of 's ' for ' k ' )
2 . → sittin ( substitution of ' i ' for ' e ' )
3 . sittin → sitting ( insert ' g ' at the end ) .
(deftest levenshtein-kitten
(is (= 3
(levenshtein-distance "kitten" "sitting")))
(is (= 3
(levenshtein-distance "Sunday" "Saturday"))))
(deftest damerau-levenshtein-distance-tests
(let [a "TO"
b "OT"
c "OST"]
(is (= 1 (damerau-levenshtein-distance a b)))
(is (= 1 (damerau-levenshtein-distance b c)))
(is (= 3 (damerau-levenshtein-distance a c)))))
(deftest euclid
(is
(= 2.8284271247461903
(euclidean-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest manhattan
(is
(= (+ 1.0 1 2 1 1)
(manhattan-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest chebyshev
(is
(== 2
(chebyshev-distance [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest cosine-sim
(is
0.938572618717
(cosine-similarity [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest tanimoto-sim
(is
(= 0.8591549295774648
(tanimoto-coefficient [2 4 3 1 6]
[3 5 1 2 5]))))
(deftest benford-law-test
(let [coll [1131111 623946 325911 1799255 199654 299357 3819495 359578 285984 2214801 341104 1303129 444480 295177 450269 1758026 498061 422457 315689 1160446 573568 253962 515211 998573 677829 1289257 572988 482990 765723 337178]]
(is
(= 5.4456385557467595
(:X-sq (benford-test coll))))))
(deftest summary-datasets
(is (summarizable? 0 summary-ds0))
(is (summarizable? 0 summary-ds1))
(is (summarizable? 0 summary-ds2))
(is (summarizable? 0 summary-ds3))
(is (summarizable? 0 summary-ds4))
(is (not (summarizable? 0 summary-ds5)))
(is (not (summarizable? 0 summary-ds6)))
(is (summarizable? 0 summary-ds7))
)
(deftest simple-p-value-test
(testing "Basic p-value testing"
(is (= 1.0 (simple-p-value (range 1 11) 5.5)))
(is (< 0.999 (simple-p-value (range 1 11) 5.499)))))
(deftest t-test-test
(testing "Return values for a t-test"
(let [t-test-result
(t-test
[1,1,1,1,2,2,2,4,4,4,4]
:y [1,1,2,2,2,4,4])]
(is (> 1 (:p-value t-test-result))))))
(deftest benford-law-test
(let [coll [1131111 623946 325911 1799255 199654 299357 3819495 359578 285984 2214801 341104 1303129 444480 295177 450269 1758026 498061 422457 315689 1160446 573568 253962 515211 998573 677829 1289257 572988 482990 765723 337178]]
(is
(= 5.4456385557467595
(:X-sq (benford-test coll)))))) |
71817ede9ad6969579fb115479637773226a5619c7307a3d18f51aacdb7d67c7 | tamarit/edd | miller_rabin.erl | -module(miller_rabin).
-compile([export_all]).
basis(N) when N>2 ->
1 + random:uniform(N-2).
find_ds(D, S) ->
case D rem 2 == 0 of
true ->
find_ds(trunc(D/2), S+1);
false ->
{D, S}
end.
find_ds(N) ->
find_ds(N-1, 0).
pow_mod(_B, 0, _M) ->
1;
pow_mod(B, E, M) ->
case trunc(E) rem 2 == 0 of
true -> trunc(math:pow(pow_mod(B, trunc(E/2), M), 2)) rem M;
trunc(B*pow_mod(B , E-1 , M ) ) rem M % RIGHT
trunc(pow_mod(B, E-1, M)) rem M % WRONG
end.
mr_series(N, A, D, S) when N rem 2 == 1 ->
Js = lists:seq(0, S),
lists:map(fun(J) -> pow_mod(A, math:pow(2, J)*D, N) end, Js).
is_mr_prime(N, As) when N>2, N rem 2 == 1 ->
{D, S} = find_ds(N),
not lists:any(fun(A) ->
case mr_series(N, A, D, S) of
[1|_] -> false;
L -> not lists:member(N-1, L)
end
end,
As).
proving_bases(N) when N < 1373653 ->
[2, 3];
proving_bases(N) when N < 25326001 ->
[2, 3, 5];
proving_bases(N) when N < 25000000000 ->
[2, 3, 5, 7];
proving_bases(N) when N < 2152302898747->
[2, 3, 5, 7, 11];
proving_bases(N) when N < 341550071728321 ->
[2, 3, 5, 7, 11, 13];
proving_bases(N) when N < 341550071728321 ->
[2, 3, 5, 7, 11, 13, 17].
random_bases(N, K) ->
[basis(N) || _ <- lists:seq(1, K)].
is_prime(1) -> false;
is_prime(2) -> true;
is_prime(N) when N rem 2 == 0 -> false;
is_prime(N) when N < 341550071728321 ->
is_mr_prime(N, proving_bases(N)).
is_probable_prime(N) ->
is_mr_prime(N, random_bases(N, 20)).
first_10() ->
lists:filter( fun is_prime/1, lists:seq(1,10) ).
%first_10() ->
L = lists : seq(1,10 ) ,
% lists:map(fun(X) ->
% case is_prime(X) of
% true ->
% io:format("~w~n", [X]);
% false ->
% false
% end
% end,
% L),
% ok.
| null | https://raw.githubusercontent.com/tamarit/edd/867f287efe951bec6a8213743a218b86e4f5bbf7/examples/miller_rabin/miller_rabin.erl | erlang | RIGHT
WRONG
first_10() ->
lists:map(fun(X) ->
case is_prime(X) of
true ->
io:format("~w~n", [X]);
false ->
false
end
end,
L),
ok. | -module(miller_rabin).
-compile([export_all]).
basis(N) when N>2 ->
1 + random:uniform(N-2).
find_ds(D, S) ->
case D rem 2 == 0 of
true ->
find_ds(trunc(D/2), S+1);
false ->
{D, S}
end.
find_ds(N) ->
find_ds(N-1, 0).
pow_mod(_B, 0, _M) ->
1;
pow_mod(B, E, M) ->
case trunc(E) rem 2 == 0 of
true -> trunc(math:pow(pow_mod(B, trunc(E/2), M), 2)) rem M;
end.
mr_series(N, A, D, S) when N rem 2 == 1 ->
Js = lists:seq(0, S),
lists:map(fun(J) -> pow_mod(A, math:pow(2, J)*D, N) end, Js).
is_mr_prime(N, As) when N>2, N rem 2 == 1 ->
{D, S} = find_ds(N),
not lists:any(fun(A) ->
case mr_series(N, A, D, S) of
[1|_] -> false;
L -> not lists:member(N-1, L)
end
end,
As).
proving_bases(N) when N < 1373653 ->
[2, 3];
proving_bases(N) when N < 25326001 ->
[2, 3, 5];
proving_bases(N) when N < 25000000000 ->
[2, 3, 5, 7];
proving_bases(N) when N < 2152302898747->
[2, 3, 5, 7, 11];
proving_bases(N) when N < 341550071728321 ->
[2, 3, 5, 7, 11, 13];
proving_bases(N) when N < 341550071728321 ->
[2, 3, 5, 7, 11, 13, 17].
random_bases(N, K) ->
[basis(N) || _ <- lists:seq(1, K)].
is_prime(1) -> false;
is_prime(2) -> true;
is_prime(N) when N rem 2 == 0 -> false;
is_prime(N) when N < 341550071728321 ->
is_mr_prime(N, proving_bases(N)).
is_probable_prime(N) ->
is_mr_prime(N, random_bases(N, 20)).
first_10() ->
lists:filter( fun is_prime/1, lists:seq(1,10) ).
L = lists : seq(1,10 ) ,
|
9644ef6f063147e7dee6efd333343a3aa4a702c607b3241a2f0e2250a3365a41 | racket/macro-debugger | steps.rkt | #lang racket/base
(require racket/contract/base
"stx-util.rkt")
(provide (struct-out protostep)
(struct-out step)
(struct-out misstep)
(struct-out remarkstep)
(struct-out state)
(struct-out bigframe)
reduction-sequence/c
context-fill
state-term
step-term1
step-term2
misstep-term1
bigframe-term
step-type?
step-type->string
rewrite-step?
rename-step?)
;; A Step is one of
- ( step StepType State State )
- ( misstep StepType State Exn )
- ( remarkstep ( ( U String Syntax ' arrow ) ) )
(struct protostep (type s1) #:transparent)
(struct step protostep (s2) #:transparent)
(struct misstep protostep (exn) #:transparent)
(struct remarkstep protostep (contents) #:transparent)
A ReductionSequence is ( )
(define reduction-sequence/c (listof protostep?))
A State is ( state Context BigContext Ids Ids Stxs Nat/#f )
(struct state (e foci ctx lctx binders uses frontier seq) #:transparent)
A Context is ( Listof Frame )
;; A Frame is (Syntax -> Syntax)
A BigContext is ( list - of BigFrame )
A BigFrame is ( make - bigframe Context Syntaxes Syntax )
(struct bigframe (ctx foci e))
;; context-fill : Context Syntax -> Syntax
(define (context-fill ctx stx)
(datum->artificial-syntax
(let loop ([ctx ctx] [stx stx])
(if (null? ctx)
stx
(let ([frame0 (car ctx)])
(loop (cdr ctx) (frame0 stx)))))))
(define (state-term s)
(context-fill (state-ctx s) (state-e s)))
(define (step-term1 s)
(state-term (protostep-s1 s)))
(define (step-term2 s)
(state-term (step-s2 s)))
(define (misstep-term1 s)
(state-term (protostep-s1 s)))
(define (bigframe-term bf)
(context-fill (bigframe-ctx bf) (bigframe-e bf)))
A StepType is a Symbol in the following alist .
(define step-type-meanings
;; Kinds: rw=rewrite, sc=scope, tr=track, ac=action, er=error
'((macro rw "Macro transformation")
(tag-module-begin rw "Add explicit #%module-begin")
(tag-app rw "Add explicit #%app")
(tag-datum rw "Add explicit #%datum")
(tag-top rw "Add explicit #%top")
(finish-block rw "Finish block")
(finish-lsv rw "Finish letrec-syntaxes+values")
(finish-expr rw "Finish #%expression")
(block->letrec rw "Transform block to letrec")
(splice-block rw "Splice block-level begin")
(splice-module rw "Splice module-level begin")
(splice-lifts rw "Splice definitions from lifted expressions")
(splice-end-lifts rw "Splice lifted module declarations")
(capture-lifts rw "Capture lifts")
(provide rw "Expand provide-specs")
(rename-lambda sc "Introduce scope for local bindings")
(rename-letX sc "Introduce scope for local bindings")
(rename-block sc "Introduce scope for internal definition context")
(rename-module sc "Introduce scope for module")
(rename-mod-shift sc "Shift the self module-path-index")
(rename-modbeg sc "Introduce scope for module body")
(resolve-variable sc "Resolve variable (remove extra scopes)") ;; rw?
(local-lift ac "Lift")
(remark ac "Macro made a remark")
(sync -- "Sync with expander")
(error er "Error")))
(define (step-type->string x)
(cond [(assq x step-type-meanings) => caddr]
[(string? x) x]
[else (error 'step-type->string "not a step type: ~s" x)]))
(define (step-type? x #:kinds [kinds #f])
(cond [(assq x step-type-meanings)
=> (lambda (c)
(define kind (cadr c))
(or (not kinds) (and (memq kind kinds) #t)))]
[else #f]))
(define (rename-step? x) (step-type? (protostep-type x) #:kinds '(sc)))
(define (rewrite-step? x) (step-type? (protostep-type x) #:kinds '(rw er)))
| null | https://raw.githubusercontent.com/racket/macro-debugger/d4e2325e6d8eced81badf315048ff54f515110d5/macro-debugger-text-lib/macro-debugger/model/steps.rkt | racket | A Step is one of
A Frame is (Syntax -> Syntax)
context-fill : Context Syntax -> Syntax
Kinds: rw=rewrite, sc=scope, tr=track, ac=action, er=error
rw? | #lang racket/base
(require racket/contract/base
"stx-util.rkt")
(provide (struct-out protostep)
(struct-out step)
(struct-out misstep)
(struct-out remarkstep)
(struct-out state)
(struct-out bigframe)
reduction-sequence/c
context-fill
state-term
step-term1
step-term2
misstep-term1
bigframe-term
step-type?
step-type->string
rewrite-step?
rename-step?)
- ( step StepType State State )
- ( misstep StepType State Exn )
- ( remarkstep ( ( U String Syntax ' arrow ) ) )
(struct protostep (type s1) #:transparent)
(struct step protostep (s2) #:transparent)
(struct misstep protostep (exn) #:transparent)
(struct remarkstep protostep (contents) #:transparent)
A ReductionSequence is ( )
(define reduction-sequence/c (listof protostep?))
A State is ( state Context BigContext Ids Ids Stxs Nat/#f )
(struct state (e foci ctx lctx binders uses frontier seq) #:transparent)
A Context is ( Listof Frame )
A BigContext is ( list - of BigFrame )
A BigFrame is ( make - bigframe Context Syntaxes Syntax )
(struct bigframe (ctx foci e))
(define (context-fill ctx stx)
(datum->artificial-syntax
(let loop ([ctx ctx] [stx stx])
(if (null? ctx)
stx
(let ([frame0 (car ctx)])
(loop (cdr ctx) (frame0 stx)))))))
(define (state-term s)
(context-fill (state-ctx s) (state-e s)))
(define (step-term1 s)
(state-term (protostep-s1 s)))
(define (step-term2 s)
(state-term (step-s2 s)))
(define (misstep-term1 s)
(state-term (protostep-s1 s)))
(define (bigframe-term bf)
(context-fill (bigframe-ctx bf) (bigframe-e bf)))
A StepType is a Symbol in the following alist .
(define step-type-meanings
'((macro rw "Macro transformation")
(tag-module-begin rw "Add explicit #%module-begin")
(tag-app rw "Add explicit #%app")
(tag-datum rw "Add explicit #%datum")
(tag-top rw "Add explicit #%top")
(finish-block rw "Finish block")
(finish-lsv rw "Finish letrec-syntaxes+values")
(finish-expr rw "Finish #%expression")
(block->letrec rw "Transform block to letrec")
(splice-block rw "Splice block-level begin")
(splice-module rw "Splice module-level begin")
(splice-lifts rw "Splice definitions from lifted expressions")
(splice-end-lifts rw "Splice lifted module declarations")
(capture-lifts rw "Capture lifts")
(provide rw "Expand provide-specs")
(rename-lambda sc "Introduce scope for local bindings")
(rename-letX sc "Introduce scope for local bindings")
(rename-block sc "Introduce scope for internal definition context")
(rename-module sc "Introduce scope for module")
(rename-mod-shift sc "Shift the self module-path-index")
(rename-modbeg sc "Introduce scope for module body")
(local-lift ac "Lift")
(remark ac "Macro made a remark")
(sync -- "Sync with expander")
(error er "Error")))
(define (step-type->string x)
(cond [(assq x step-type-meanings) => caddr]
[(string? x) x]
[else (error 'step-type->string "not a step type: ~s" x)]))
(define (step-type? x #:kinds [kinds #f])
(cond [(assq x step-type-meanings)
=> (lambda (c)
(define kind (cadr c))
(or (not kinds) (and (memq kind kinds) #t)))]
[else #f]))
(define (rename-step? x) (step-type? (protostep-type x) #:kinds '(sc)))
(define (rewrite-step? x) (step-type? (protostep-type x) #:kinds '(rw er)))
|
1cc35b3b8776f17ef83a48fdfd436525350c0be117f4e1b601b05fbadcf0e21d | avatar29A/hs-aitubots-api | Types.hs | module Aitu.Bot.Types
( module Types
)
where
-- Types
import Aitu.Bot.Types.Audio as Types
import Aitu.Bot.Types.Avatar as Types
import Aitu.Bot.Types.Bot as Types
import Aitu.Bot.Types.Contact as Types
import Aitu.Bot.Types.Document as Types
import Aitu.Bot.Types.Errors as Types
import Aitu.Bot.Types.ForwardMetadata
as Types
import Aitu.Bot.Types.Image as Types
import Aitu.Bot.Types.InputMedia as Types
import Aitu.Bot.Types.Media as Types
import Aitu.Bot.Types.Peer as Types
import Aitu.Bot.Types.UIState as Types
import Aitu.Bot.Types.User as Types
import Aitu.Bot.Types.Video as Types
import Aitu.Bot.Types.WebHookInfo as Types
import Aitu.Bot.Types.InlineCommand as Types
import Aitu.Bot.Types.QuickButtonCommand
as Types
import Aitu.Bot.Types.ReplyCommand as Types
import Aitu.Bot.Types.InputContact as Types
-- Updates
import Aitu.Bot.Types.Updates as Types
-- Files
import Aitu.Bot.Types.UploadFiles as Types
| null | https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/src/Aitu/Bot/Types.hs | haskell | Types
Updates
Files | module Aitu.Bot.Types
( module Types
)
where
import Aitu.Bot.Types.Audio as Types
import Aitu.Bot.Types.Avatar as Types
import Aitu.Bot.Types.Bot as Types
import Aitu.Bot.Types.Contact as Types
import Aitu.Bot.Types.Document as Types
import Aitu.Bot.Types.Errors as Types
import Aitu.Bot.Types.ForwardMetadata
as Types
import Aitu.Bot.Types.Image as Types
import Aitu.Bot.Types.InputMedia as Types
import Aitu.Bot.Types.Media as Types
import Aitu.Bot.Types.Peer as Types
import Aitu.Bot.Types.UIState as Types
import Aitu.Bot.Types.User as Types
import Aitu.Bot.Types.Video as Types
import Aitu.Bot.Types.WebHookInfo as Types
import Aitu.Bot.Types.InlineCommand as Types
import Aitu.Bot.Types.QuickButtonCommand
as Types
import Aitu.Bot.Types.ReplyCommand as Types
import Aitu.Bot.Types.InputContact as Types
import Aitu.Bot.Types.Updates as Types
import Aitu.Bot.Types.UploadFiles as Types
|
452e695ce94f9b298715e5ab6843a5903a1ab972375e576952f7e4298f601b10 | TorXakis/TorXakis | ControlLoop.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
{-# LANGUAGE OverloadedStrings #-}
module ExploreModels.ControlLoop (exampleSet) where
import Examples.Paths
import Prelude hiding (FilePath)
import Sqatt
exampDir :: FilePath
exampDir = "ControlLoop"
multipleControlLoopTxsPath :: FilePath
multipleControlLoopTxsPath = txsFilePath exampDir "MultipleControlLoops"
test0 :: TxsExample
test0 = emptyExample
{ exampleName = "Stepper 500"
, txsModelFiles = [txsFilePath exampDir "ControlLoopModel"]
, txsCmdsFiles = [txsCmdPath exampDir "ControlLoop_Stepper_Model"]
, expectedResult = Pass
}
test1 :: TxsExample
test1 = emptyExample
{ exampleName = "Spec Produce 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecProduce_Stepper_Model"]
, expectedResult = Pass
}
test2 :: TxsExample
test2 = emptyExample
{ exampleName = "Spec Measure 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecMeasure_Stepper_Model"]
, expectedResult = Pass
}
test3 :: TxsExample
test3 = emptyExample
{ exampleName = "Spec Correct 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecCorrect_Stepper_Model"]
, expectedResult = Pass
}
test4 :: TxsExample
test4 = emptyExample
{ exampleName = "Multiple Loops Stepper 30"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_Spec_Stepper_Model"]
, expectedResult = Pass
}
examples :: [TxsExample]
examples = [test0, test1, test2, test3, test4]
exampleSet :: TxsExampleSet
exampleSet = TxsExampleSet "Control Loop #model" examples
| null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/test/sqatt/src/ExploreModels/ControlLoop.hs | haskell | # LANGUAGE OverloadedStrings # |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
module ExploreModels.ControlLoop (exampleSet) where
import Examples.Paths
import Prelude hiding (FilePath)
import Sqatt
exampDir :: FilePath
exampDir = "ControlLoop"
multipleControlLoopTxsPath :: FilePath
multipleControlLoopTxsPath = txsFilePath exampDir "MultipleControlLoops"
test0 :: TxsExample
test0 = emptyExample
{ exampleName = "Stepper 500"
, txsModelFiles = [txsFilePath exampDir "ControlLoopModel"]
, txsCmdsFiles = [txsCmdPath exampDir "ControlLoop_Stepper_Model"]
, expectedResult = Pass
}
test1 :: TxsExample
test1 = emptyExample
{ exampleName = "Spec Produce 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecProduce_Stepper_Model"]
, expectedResult = Pass
}
test2 :: TxsExample
test2 = emptyExample
{ exampleName = "Spec Measure 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecMeasure_Stepper_Model"]
, expectedResult = Pass
}
test3 :: TxsExample
test3 = emptyExample
{ exampleName = "Spec Correct 100"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_SpecCorrect_Stepper_Model"]
, expectedResult = Pass
}
test4 :: TxsExample
test4 = emptyExample
{ exampleName = "Multiple Loops Stepper 30"
, txsModelFiles = [multipleControlLoopTxsPath]
, txsCmdsFiles = [txsCmdPath exampDir "MultipleControlLoops_Spec_Stepper_Model"]
, expectedResult = Pass
}
examples :: [TxsExample]
examples = [test0, test1, test2, test3, test4]
exampleSet :: TxsExampleSet
exampleSet = TxsExampleSet "Control Loop #model" examples
|
6825f9e355de8d9d243ca7f0622bb588cbe63cc4362997587b0c5347a1512cdc | LambdaHack/LambdaHack | UIOptions.hs | # LANGUAGE DeriveGeneric #
-- | UI client options specified in the config file.
module Game.LambdaHack.Client.UI.UIOptions
( UIOptions(..)
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Control.DeepSeq
import Data.Binary
import GHC.Generics (Generic)
import Game.LambdaHack.Client.UI.HumanCmd
import qualified Game.LambdaHack.Client.UI.Key as K
import Game.LambdaHack.Common.ClientOptions (FullscreenMode)
import Game.LambdaHack.Common.Misc
import qualified Game.LambdaHack.Definition.Color as Color
import Game.LambdaHack.Definition.Defs
-- | Options that affect the UI of the client, specified in the config file.
-- More documentation is in the default config file.
data UIOptions = UIOptions
{ uCommands :: [(K.KM, CmdTriple)]
, uHeroNames :: [(Int, (Text, Text))]
, uVi :: Bool
, uLeftHand :: Bool
, uChosenFontset :: Text
, uAllFontsScale :: Double
, uFullscreenMode :: FullscreenMode
, uhpWarningPercent :: Int
, uMsgWrapColumn :: X
, uHistoryMax :: Int
, uMaxFps :: Double
, uNoAnim :: Bool
, uOverrideCmdline :: [String]
, uFonts :: [(Text, FontDefinition)]
, uFontsets :: [(Text, FontSet)]
, uMessageColors :: [(String, Color.Color)]
}
deriving (Show, Generic)
instance NFData UIOptions
instance Binary UIOptions
| null | https://raw.githubusercontent.com/LambdaHack/LambdaHack/9dc1b41b756a8e98c157f0917a28abcc6703fb79/engine-src/Game/LambdaHack/Client/UI/UIOptions.hs | haskell | | UI client options specified in the config file.
| Options that affect the UI of the client, specified in the config file.
More documentation is in the default config file. | # LANGUAGE DeriveGeneric #
module Game.LambdaHack.Client.UI.UIOptions
( UIOptions(..)
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Control.DeepSeq
import Data.Binary
import GHC.Generics (Generic)
import Game.LambdaHack.Client.UI.HumanCmd
import qualified Game.LambdaHack.Client.UI.Key as K
import Game.LambdaHack.Common.ClientOptions (FullscreenMode)
import Game.LambdaHack.Common.Misc
import qualified Game.LambdaHack.Definition.Color as Color
import Game.LambdaHack.Definition.Defs
data UIOptions = UIOptions
{ uCommands :: [(K.KM, CmdTriple)]
, uHeroNames :: [(Int, (Text, Text))]
, uVi :: Bool
, uLeftHand :: Bool
, uChosenFontset :: Text
, uAllFontsScale :: Double
, uFullscreenMode :: FullscreenMode
, uhpWarningPercent :: Int
, uMsgWrapColumn :: X
, uHistoryMax :: Int
, uMaxFps :: Double
, uNoAnim :: Bool
, uOverrideCmdline :: [String]
, uFonts :: [(Text, FontDefinition)]
, uFontsets :: [(Text, FontSet)]
, uMessageColors :: [(String, Color.Color)]
}
deriving (Show, Generic)
instance NFData UIOptions
instance Binary UIOptions
|
cffc98cb5561a63daa895e7b357b2452b58c7a22bc26c25a6ac66bce5c054532 | aiya000/haskell-examples | Main.hs | import Control.Zipper
-- data Top
data h i a
-- data a :@ i
-- type h :>> a = Zipper h Int a
--
-- zipper :: a -> Top :>> a
main :: IO ()
main = do
print $ (rezip . zipper) 10
| null | https://raw.githubusercontent.com/aiya000/haskell-examples/a337ba0e86be8bb1333e7eea852ba5fa1d177d8a/Control/Zipper/Main.hs | haskell | data Top
data a :@ i
type h :>> a = Zipper h Int a
zipper :: a -> Top :>> a | import Control.Zipper
data h i a
main :: IO ()
main = do
print $ (rezip . zipper) 10
|
0405d7c8307cef0320b5483134bd5014f8ebe5426fb54cdb0f01d13e86fb39f2 | ocaml-multicore/tezos | proxy.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2020 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
module L = (val Tezos_proxy.Logger.logger ~protocol_name:Protocol.name
: Tezos_proxy.Logger.S)
let proxy_block_header (rpc_context : RPC_context.generic)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) =
let rpc_context = new Protocol_client_context.wrap_rpc_context rpc_context in
L.emit
L.proxy_block_header
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block )
>>= fun () ->
Protocol_client_context.Alpha_block_services.header
rpc_context
~chain
~block
()
module ProtoRpc : Tezos_proxy.Proxy_proto.PROTO_RPC = struct
(** Split done only when the mode is [Tezos_proxy.Proxy.server]. Getting
an entire big map at once is useful for dapp developers that
iterate a lot on big maps and that use proxy servers in their
internal infra. *)
let split_server key =
match key with
(* matches paths like:
big_maps/index/i/contents/tail *)
| "big_maps" :: "index" :: i :: "contents" :: tail ->
Some (["big_maps"; "index"; i; "contents"], tail)
| _ -> None
(** Split that is always done, no matter the mode *)
let split_always key =
match key with
(* matches paths like:
contracts/index/000002298c03ed7d454a101eb7022bc95f7e5f41ac78/tail *)
| "contracts" :: "index" :: i :: tail ->
Some (["contracts"; "index"; i], tail)
| "cycle" :: i :: tail -> Some (["cycle"; i], tail)
(* matches paths like:
rolls/owner/snapshot/19/1/tail *)
| "rolls" :: "owner" :: "snapshot" :: i :: j :: tail ->
Some (["rolls"; "owner"; "snapshot"; i; j], tail)
| "v1" :: tail -> Some (["v1"], tail)
| _ -> None
let split_key (mode : Tezos_proxy.Proxy.mode) (key : Proxy_context.M.key) :
(Proxy_context.M.key * Proxy_context.M.key) option =
match split_always key with
| Some _ as res ->
res (* No need to inspect the mode, this split is always done *)
| None -> (
match mode with
| Client ->
(* There are strictly less splits in Client mode: return immediately *)
None
| Server -> split_server key)
let failure_is_permanent = function
| ["pending_migration_balance_updates"]
| ["pending_migration_operation_results"] ->
true
| _ -> false
let do_rpc (pgi : Tezos_proxy.Proxy.proxy_getter_input)
(key : Proxy_context.M.key) =
let chain = pgi.chain in
let block = pgi.block in
L.emit
L.proxy_block_rpc
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block,
key )
>>= fun () ->
Protocol_client_context.Alpha_block_services.Context.read
pgi.rpc_context
~chain
~block
key
>>=? fun (raw_context : Block_services.raw_context) ->
L.emit L.tree_received
@@ Int64.of_int (Tezos_proxy.Proxy_getter.raw_context_size raw_context)
>>= fun () -> return raw_context
end
let initial_context
(proxy_builder :
Tezos_proxy.Proxy_proto.proto_rpc ->
Tezos_proxy.Proxy_getter.proxy_m Lwt.t)
(rpc_context : RPC_context.generic) (mode : Tezos_proxy.Proxy.mode)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) :
Environment_context.Context.t Lwt.t =
let p_rpc = (module ProtoRpc : Tezos_proxy.Proxy_proto.PROTO_RPC) in
proxy_builder p_rpc >>= fun (module M) ->
L.emit
L.proxy_getter_created
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block )
>>= fun () ->
let pgi : Tezos_proxy.Proxy.proxy_getter_input =
{rpc_context = (rpc_context :> RPC_context.simple); mode; chain; block}
in
let module N : Proxy_context.M.ProxyDelegate = struct
let proxy_dir_mem = M.proxy_dir_mem pgi
let proxy_get = M.proxy_get pgi
let proxy_mem = M.proxy_mem pgi
end in
let empty = Proxy_context.empty @@ Some (module N) in
let version_value = "hangzhou_011" in
Tezos_protocol_environment.Context.add
empty
["version"]
(Bytes.of_string version_value)
>>= fun ctxt -> Protocol.Main.init_context ctxt
let time_between_blocks (rpc_context : RPC_context.generic)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) =
let open Protocol in
let rpc_context = new Protocol_client_context.wrap_rpc_context rpc_context in
Constants_services.all rpc_context (chain, block) >>=? fun constants ->
let times = constants.parametric.time_between_blocks in
return @@ Option.map Alpha_context.Period.to_seconds (List.hd times)
let init_env_rpc_context (_printer : Tezos_client_base.Client_context.printer)
(proxy_builder :
Tezos_proxy.Proxy_proto.proto_rpc ->
Tezos_proxy.Proxy_getter.proxy_m Lwt.t)
(rpc_context : RPC_context.generic) (mode : Tezos_proxy.Proxy.mode)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) :
Tezos_protocol_environment.rpc_context tzresult Lwt.t =
proxy_block_header rpc_context chain block >>=? fun {shell; hash; _} ->
let block_hash = hash in
initial_context proxy_builder rpc_context mode chain block >>= fun context ->
return {Tezos_protocol_environment.block_hash; block_header = shell; context}
let () =
let open Tezos_proxy.Registration in
let module M : Proxy_sig = struct
module Protocol = Protocol_client_context.Lifted_protocol
let protocol_hash = Protocol.hash
let directory = Plugin.RPC.rpc_services
let hash = Protocol_client_context.Alpha_block_services.hash
let init_env_rpc_context = init_env_rpc_context
let time_between_blocks = time_between_blocks
include Light.M
end in
register_proxy_context (module M)
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_011_PtHangz2/lib_client/proxy.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Split done only when the mode is [Tezos_proxy.Proxy.server]. Getting
an entire big map at once is useful for dapp developers that
iterate a lot on big maps and that use proxy servers in their
internal infra.
matches paths like:
big_maps/index/i/contents/tail
* Split that is always done, no matter the mode
matches paths like:
contracts/index/000002298c03ed7d454a101eb7022bc95f7e5f41ac78/tail
matches paths like:
rolls/owner/snapshot/19/1/tail
No need to inspect the mode, this split is always done
There are strictly less splits in Client mode: return immediately | Copyright ( c ) 2020 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
module L = (val Tezos_proxy.Logger.logger ~protocol_name:Protocol.name
: Tezos_proxy.Logger.S)
let proxy_block_header (rpc_context : RPC_context.generic)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) =
let rpc_context = new Protocol_client_context.wrap_rpc_context rpc_context in
L.emit
L.proxy_block_header
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block )
>>= fun () ->
Protocol_client_context.Alpha_block_services.header
rpc_context
~chain
~block
()
module ProtoRpc : Tezos_proxy.Proxy_proto.PROTO_RPC = struct
let split_server key =
match key with
| "big_maps" :: "index" :: i :: "contents" :: tail ->
Some (["big_maps"; "index"; i; "contents"], tail)
| _ -> None
let split_always key =
match key with
| "contracts" :: "index" :: i :: tail ->
Some (["contracts"; "index"; i], tail)
| "cycle" :: i :: tail -> Some (["cycle"; i], tail)
| "rolls" :: "owner" :: "snapshot" :: i :: j :: tail ->
Some (["rolls"; "owner"; "snapshot"; i; j], tail)
| "v1" :: tail -> Some (["v1"], tail)
| _ -> None
let split_key (mode : Tezos_proxy.Proxy.mode) (key : Proxy_context.M.key) :
(Proxy_context.M.key * Proxy_context.M.key) option =
match split_always key with
| Some _ as res ->
| None -> (
match mode with
| Client ->
None
| Server -> split_server key)
let failure_is_permanent = function
| ["pending_migration_balance_updates"]
| ["pending_migration_operation_results"] ->
true
| _ -> false
let do_rpc (pgi : Tezos_proxy.Proxy.proxy_getter_input)
(key : Proxy_context.M.key) =
let chain = pgi.chain in
let block = pgi.block in
L.emit
L.proxy_block_rpc
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block,
key )
>>= fun () ->
Protocol_client_context.Alpha_block_services.Context.read
pgi.rpc_context
~chain
~block
key
>>=? fun (raw_context : Block_services.raw_context) ->
L.emit L.tree_received
@@ Int64.of_int (Tezos_proxy.Proxy_getter.raw_context_size raw_context)
>>= fun () -> return raw_context
end
let initial_context
(proxy_builder :
Tezos_proxy.Proxy_proto.proto_rpc ->
Tezos_proxy.Proxy_getter.proxy_m Lwt.t)
(rpc_context : RPC_context.generic) (mode : Tezos_proxy.Proxy.mode)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) :
Environment_context.Context.t Lwt.t =
let p_rpc = (module ProtoRpc : Tezos_proxy.Proxy_proto.PROTO_RPC) in
proxy_builder p_rpc >>= fun (module M) ->
L.emit
L.proxy_getter_created
( Tezos_shell_services.Block_services.chain_to_string chain,
Tezos_shell_services.Block_services.to_string block )
>>= fun () ->
let pgi : Tezos_proxy.Proxy.proxy_getter_input =
{rpc_context = (rpc_context :> RPC_context.simple); mode; chain; block}
in
let module N : Proxy_context.M.ProxyDelegate = struct
let proxy_dir_mem = M.proxy_dir_mem pgi
let proxy_get = M.proxy_get pgi
let proxy_mem = M.proxy_mem pgi
end in
let empty = Proxy_context.empty @@ Some (module N) in
let version_value = "hangzhou_011" in
Tezos_protocol_environment.Context.add
empty
["version"]
(Bytes.of_string version_value)
>>= fun ctxt -> Protocol.Main.init_context ctxt
let time_between_blocks (rpc_context : RPC_context.generic)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) =
let open Protocol in
let rpc_context = new Protocol_client_context.wrap_rpc_context rpc_context in
Constants_services.all rpc_context (chain, block) >>=? fun constants ->
let times = constants.parametric.time_between_blocks in
return @@ Option.map Alpha_context.Period.to_seconds (List.hd times)
let init_env_rpc_context (_printer : Tezos_client_base.Client_context.printer)
(proxy_builder :
Tezos_proxy.Proxy_proto.proto_rpc ->
Tezos_proxy.Proxy_getter.proxy_m Lwt.t)
(rpc_context : RPC_context.generic) (mode : Tezos_proxy.Proxy.mode)
(chain : Tezos_shell_services.Block_services.chain)
(block : Tezos_shell_services.Block_services.block) :
Tezos_protocol_environment.rpc_context tzresult Lwt.t =
proxy_block_header rpc_context chain block >>=? fun {shell; hash; _} ->
let block_hash = hash in
initial_context proxy_builder rpc_context mode chain block >>= fun context ->
return {Tezos_protocol_environment.block_hash; block_header = shell; context}
let () =
let open Tezos_proxy.Registration in
let module M : Proxy_sig = struct
module Protocol = Protocol_client_context.Lifted_protocol
let protocol_hash = Protocol.hash
let directory = Plugin.RPC.rpc_services
let hash = Protocol_client_context.Alpha_block_services.hash
let init_env_rpc_context = init_env_rpc_context
let time_between_blocks = time_between_blocks
include Light.M
end in
register_proxy_context (module M)
|
ccff23fddcc371bc1a2059aa99301944aeddeba5f50548e0261d357cd99750b2 | green-labs/hands-on-clojure | solution.clj | (ns solution)
(comment
# 14 functions
8
# 16 hello world
(fn [name] (str "Hello, " name "!"))
# 17 map
'(6 7 8)
# 23 reverse a sequence
(fn [sx] (reduce conj '() sx))
# 24 sum it all up
(fn [sx] (apply + sx))
# 27 palindrom detector
(fn [v] (= (vec v) (reverse (vec v))))
# 32 duplicate a sequence
(fn [v] (apply concat (map vector v v)))
# 44 rotate sequence
(fn [offset v]
(let [length (count v)]
(->> (cycle v)
(drop (mod offset length))
(take length))))
# 59 juxtaposition
(fn [& fs]
(fn [& args]
(map (fn [v] (apply v args)) fs)))
# 70 word sorting
(fn [s]
(->> (clojure.string/split s #" ")
(sort-by (fn [v] (.toUpperCase v)))
(map (fn [s] (clojure.string/replace s #"[,.?!;:]" ""))))
(println "Welcome to clojure world!")))
| null | https://raw.githubusercontent.com/green-labs/hands-on-clojure/a4770bf053591521d3c39270d5e054cbf1799720/src/solution.clj | clojure | (ns solution)
(comment
# 14 functions
8
# 16 hello world
(fn [name] (str "Hello, " name "!"))
# 17 map
'(6 7 8)
# 23 reverse a sequence
(fn [sx] (reduce conj '() sx))
# 24 sum it all up
(fn [sx] (apply + sx))
# 27 palindrom detector
(fn [v] (= (vec v) (reverse (vec v))))
# 32 duplicate a sequence
(fn [v] (apply concat (map vector v v)))
# 44 rotate sequence
(fn [offset v]
(let [length (count v)]
(->> (cycle v)
(drop (mod offset length))
(take length))))
# 59 juxtaposition
(fn [& fs]
(fn [& args]
(map (fn [v] (apply v args)) fs)))
# 70 word sorting
(fn [s]
(->> (clojure.string/split s #" ")
(sort-by (fn [v] (.toUpperCase v)))
(map (fn [s] (clojure.string/replace s #"[,.?!;:]" ""))))
(println "Welcome to clojure world!")))
| |
788e7a147f2df3c534e951d2bfb785535283cd348327dc97194c130b830ce29b | beamjs/erlv8 | gen_server2.erl | This file is a copy of gen_server.erl from the R13B-1 Erlang / OTP
%% distribution, with the following modifications:
%%
1 ) the module name is gen_server2
%%
2 ) more efficient handling of selective receives in callbacks
%% gen_server2 processes drain their message queue into an internal
%% buffer before invoking any callback module functions. Messages are
%% dequeued from the buffer for processing. Thus the effective message
%% queue of a gen_server2 process is the concatenation of the internal
%% buffer and the real message queue.
%% As a result of the draining, any selective receive invoked inside a
%% callback is less likely to have to scan a large message queue.
%%
3 ) gen_server2 : cast is guaranteed to be order - preserving
%% The original code could reorder messages when communicating with a
%% process on a remote node that was not currently connected.
%%
4 ) The callback module can optionally implement prioritise_call/3 ,
%% prioritise_cast/2 and prioritise_info/2. These functions take
Message , From and State or just Message and State and return a
%% single integer representing the priority attached to the message.
%% Messages with higher priorities are processed before requests with
%% lower priorities. The default priority is 0.
%%
5 ) The callback module can optionally implement
%% handle_pre_hibernate/1 and handle_post_hibernate/1. These will be
%% called immediately prior to and post hibernation, respectively. If
handle_pre_hibernate returns { hibernate , NewState } then the process
%% will hibernate. If the module does not implement
%% handle_pre_hibernate/1 then the default action is to hibernate.
%%
6 ) init can return a 4th arg , { backoff , InitialTimeout ,
MinimumTimeout , DesiredHibernatePeriod } ( all in
%% milliseconds). Then, on all callbacks which can return a timeout
%% (including init), timeout can be 'hibernate'. When this is the
%% case, the current timeout value will be used (initially, the
InitialTimeout supplied from init ) . After this timeout has
%% occurred, hibernation will occur as normal. Upon awaking, a new
%% current timeout value will be calculated.
%%
%% The purpose is that the gen_server2 takes care of adjusting the
%% current timeout value such that the process will increase the
%% timeout value repeatedly if it is unable to sleep for the
DesiredHibernatePeriod . If it is able to sleep for the
%% DesiredHibernatePeriod it will decrease the current timeout down to
the MinimumTimeout , so that the process is put to sleep sooner ( and
%% hopefully stays asleep for longer). In short, should a process
%% using this receive a burst of messages, it should not hibernate
%% between those messages, but as the messages become less frequent,
%% the process will not only hibernate, it will do so sooner after
%% each message.
%%
%% When using this backoff mechanism, normal timeout values (i.e. not
%% 'hibernate') can still be used, and if they are used then the
handle_info(timeout , State ) will be called as normal . In this case ,
returning ' hibernate ' from handle_info(timeout , State ) will not
%% hibernate the process immediately, as it would if backoff wasn't
%% being used. Instead it'll wait for the current timeout as described
%% above.
All modifications are ( C ) 2009 - 2010 LShift Ltd.
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved via the world wide web at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
The Initial Developer of the Original Code is Ericsson Utvecklings AB .
Portions created by Ericsson are Copyright 1999 ,
%% AB. All Rights Reserved.''
%%
%% $Id$
%%
-module(gen_server2).
%%% ---------------------------------------------------
%%%
%%% The idea behind THIS server is that the user module
%%% provides (different) functions to handle different
%%% kind of inputs.
%%% If the Parent process terminates the Module:terminate/2
%%% function is called.
%%%
%%% The user module should export:
%%%
%%% init(Args)
%%% ==> {ok, State}
{ ok , State , Timeout }
{ ok , State , Timeout , Backoff }
%%% ignore
%%% {stop, Reason}
%%%
handle_call(Msg , { From , Tag } , State )
%%%
%%% ==> {reply, Reply, State}
{ reply , Reply , State , Timeout }
{ noreply , State }
{ noreply , State , Timeout }
%%% {stop, Reason, Reply, State}
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
handle_cast(Msg , State )
%%%
= = > { noreply , State }
{ noreply , State , Timeout }
%%% {stop, Reason, State}
%%% Reason = normal | shutdown | Term terminate(State) is called
%%%
handle_info(Info , State ) Info is e.g. { ' EXIT ' , P , R } , { nodedown , N } , ...
%%%
= = > { noreply , State }
{ noreply , State , Timeout }
%%% {stop, Reason, State}
%%% Reason = normal | shutdown | Term, terminate(State) is called
%%%
%%% terminate(Reason, State) Let the user module clean up
%%% always called when server terminates
%%%
%%% ==> ok
%%%
%%% handle_pre_hibernate(State)
%%%
%%% ==> {hibernate, State}
%%% {stop, Reason, State}
%%% Reason = normal | shutdown | Term, terminate(State) is called
%%%
%%% handle_post_hibernate(State)
%%%
= = > { noreply , State }
%%% {stop, Reason, State}
%%% Reason = normal | shutdown | Term, terminate(State) is called
%%%
%%% The work flow (of the server) can be described as follows:
%%%
%%% User module Generic
%%% ----------- -------
%%% start -----> start
%%% init <----- .
%%%
%%% loop
%%% handle_call <----- .
%%% -----> reply
%%%
%%% handle_cast <----- .
%%%
%%% handle_info <----- .
%%%
%%% terminate <----- .
%%%
%%% -----> reply
%%%
%%%
%%% ---------------------------------------------------
%% API
-export([start/3, start/4,
start_link/3, start_link/4,
call/2, call/3,
cast/2, reply/2,
abcast/2, abcast/3,
multi_call/2, multi_call/3, multi_call/4,
enter_loop/3, enter_loop/4, enter_loop/5, enter_loop/6, wake_hib/1]).
-export([behaviour_info/1]).
%% System exports
-export([system_continue/3,
system_terminate/4,
system_code_change/4,
format_status/2]).
%% Internal exports
-export([init_it/6]).
-import(error_logger, [format/2]).
State record
-record(gs2_state, {parent, name, state, mod, time,
timeout_state, queue, debug, prioritise_call,
prioritise_cast, prioritise_info}).
%%%=========================================================================
%%% Specs. These exist only to shut up dialyzer's warnings
%%%=========================================================================
-ifdef(use_specs).
-type(gs2_state() :: #gs2_state{}).
-spec(handle_common_termination/3 ::
(any(), atom(), gs2_state()) -> no_return()).
-spec(hibernate/1 :: (gs2_state()) -> no_return()).
-spec(pre_hibernate/1 :: (gs2_state()) -> no_return()).
-spec(system_terminate/4 :: (_, _, _, gs2_state()) -> no_return()).
-endif.
%%%=========================================================================
%%% API
%%%=========================================================================
behaviour_info(callbacks) ->
[{init,1},{handle_call,3},{handle_cast,2},{handle_info,2},
{terminate,2},{code_change,3}];
behaviour_info(_Other) ->
undefined.
%%% -----------------------------------------------------------------
%%% Starts a generic server.
start(Mod , , Options )
start(Name , , , Options )
start_link(Mod , , Options )
start_link(Name , , , Options ) where :
%%% Name ::= {local, atom()} | {global, atom()}
%%% Mod ::= atom(), callback module implementing the 'real' server
: : = term ( ) , init arguments ( to Mod : init/1 )
%%% Options ::= [{timeout, Timeout} | {debug, [Flag]}]
%%% Flag ::= trace | log | {logfile, File} | statistics | debug
( debug = = log & & statistics )
Returns : { ok , Pid } |
{ error , { already_started , Pid } } |
%%% {error, Reason}
%%% -----------------------------------------------------------------
start(Mod, Args, Options) ->
gen:start(?MODULE, nolink, Mod, Args, Options).
start(Name, Mod, Args, Options) ->
gen:start(?MODULE, nolink, Name, Mod, Args, Options).
start_link(Mod, Args, Options) ->
gen:start(?MODULE, link, Mod, Args, Options).
start_link(Name, Mod, Args, Options) ->
gen:start(?MODULE, link, Name, Mod, Args, Options).
%% -----------------------------------------------------------------
%% Make a call to a generic server.
%% If the server is located at another node, that node will
%% be monitored.
%% If the client is trapping exits and is linked server termination
%% is handled here (? Shall we do that here (or rely on timeouts) ?).
%% -----------------------------------------------------------------
call(Name, Request) ->
case catch gen:call(Name, '$gen_call', Request) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, call, [Name, Request]}})
end.
call(Name, Request, Timeout) ->
case catch gen:call(Name, '$gen_call', Request, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, call, [Name, Request, Timeout]}})
end.
%% -----------------------------------------------------------------
%% Make a cast to a generic server.
%% -----------------------------------------------------------------
cast({global,Name}, Request) ->
catch global:send(Name, cast_msg(Request)),
ok;
cast({Name,Node}=Dest, Request) when is_atom(Name), is_atom(Node) ->
do_cast(Dest, Request);
cast(Dest, Request) when is_atom(Dest) ->
do_cast(Dest, Request);
cast(Dest, Request) when is_pid(Dest) ->
do_cast(Dest, Request).
do_cast(Dest, Request) ->
do_send(Dest, cast_msg(Request)),
ok.
cast_msg(Request) -> {'$gen_cast',Request}.
%% -----------------------------------------------------------------
%% Send a reply to the client.
%% -----------------------------------------------------------------
reply({To, Tag}, Reply) ->
catch To ! {Tag, Reply}.
%% -----------------------------------------------------------------
%% Asyncronous broadcast, returns nothing, it's just send'n pray
%% -----------------------------------------------------------------
abcast(Name, Request) when is_atom(Name) ->
do_abcast([node() | nodes()], Name, cast_msg(Request)).
abcast(Nodes, Name, Request) when is_list(Nodes), is_atom(Name) ->
do_abcast(Nodes, Name, cast_msg(Request)).
do_abcast([Node|Nodes], Name, Msg) when is_atom(Node) ->
do_send({Name,Node},Msg),
do_abcast(Nodes, Name, Msg);
do_abcast([], _,_) -> abcast.
%%% -----------------------------------------------------------------
%%% Make a call to servers at several nodes.
%%% Returns: {[Replies],[BadNodes]}
%%% A Timeout can be given
%%%
%%% A middleman process is used in case late answers arrives after
%%% the timeout. If they would be allowed to glog the callers message
%%% queue, it would probably become confused. Late answers will
%%% now arrive to the terminated middleman and so be discarded.
%%% -----------------------------------------------------------------
multi_call(Name, Req)
when is_atom(Name) ->
do_multi_call([node() | nodes()], Name, Req, infinity).
multi_call(Nodes, Name, Req)
when is_list(Nodes), is_atom(Name) ->
do_multi_call(Nodes, Name, Req, infinity).
multi_call(Nodes, Name, Req, infinity) ->
do_multi_call(Nodes, Name, Req, infinity);
multi_call(Nodes, Name, Req, Timeout)
when is_list(Nodes), is_atom(Name), is_integer(Timeout), Timeout >= 0 ->
do_multi_call(Nodes, Name, Req, Timeout).
%%-----------------------------------------------------------------
enter_loop(Mod , Options , State , < ServerName > , < TimeOut > , < Backoff > ) - > _
%%
%% Description: Makes an existing process into a gen_server.
%% The calling process will enter the gen_server receive
%% loop and become a gen_server process.
The process * must * have been started using one of the
%% start functions in proc_lib, see proc_lib(3).
%% The user is responsible for any initialization of the
%% process, including registering a name for it.
%%-----------------------------------------------------------------
enter_loop(Mod, Options, State) ->
enter_loop(Mod, Options, State, self(), infinity, undefined).
enter_loop(Mod, Options, State, Backoff = {backoff, _, _ , _}) ->
enter_loop(Mod, Options, State, self(), infinity, Backoff);
enter_loop(Mod, Options, State, ServerName = {_, _}) ->
enter_loop(Mod, Options, State, ServerName, infinity, undefined);
enter_loop(Mod, Options, State, Timeout) ->
enter_loop(Mod, Options, State, self(), Timeout, undefined).
enter_loop(Mod, Options, State, ServerName, Backoff = {backoff, _, _, _}) ->
enter_loop(Mod, Options, State, ServerName, infinity, Backoff);
enter_loop(Mod, Options, State, ServerName, Timeout) ->
enter_loop(Mod, Options, State, ServerName, Timeout, undefined).
enter_loop(Mod, Options, State, ServerName, Timeout, Backoff) ->
Name = get_proc_name(ServerName),
Parent = get_parent(),
Debug = debug_options(Name, Options),
Queue = priority_queue:new(),
Backoff1 = extend_backoff(Backoff),
loop(find_prioritisers(
#gs2_state { parent = Parent, name = Name, state = State,
mod = Mod, time = Timeout, timeout_state = Backoff1,
queue = Queue, debug = Debug })).
%%%========================================================================
%%% Gen-callback functions
%%%========================================================================
%%% ---------------------------------------------------
%%% Initiate the new process.
Register the name using the Rfunc function
%%% Calls the Mod:init/Args function.
%%% Finally an acknowledge is sent to Parent and the main
%%% loop is entered.
%%% ---------------------------------------------------
init_it(Starter, self, Name, Mod, Args, Options) ->
init_it(Starter, self(), Name, Mod, Args, Options);
init_it(Starter, Parent, Name0, Mod, Args, Options) ->
Name = name(Name0),
Debug = debug_options(Name, Options),
Queue = priority_queue:new(),
GS2State = find_prioritisers(
#gs2_state { parent = Parent,
name = Name,
mod = Mod,
queue = Queue,
debug = Debug }),
case catch Mod:init(Args) of
{ok, State} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = infinity,
timeout_state = undefined });
{ok, State, Timeout} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = Timeout,
timeout_state = undefined });
{ok, State, Timeout, Backoff = {backoff, _, _, _}} ->
Backoff1 = extend_backoff(Backoff),
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = Timeout,
timeout_state = Backoff1 });
{stop, Reason} ->
%% For consistency, we must make sure that the
%% registered name (if any) is unregistered before
%% the parent process is notified about the failure.
%% (Otherwise, the parent process could get
%% an 'already_started' error if it immediately
%% tried starting the process again.)
unregister_name(Name0),
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
ignore ->
unregister_name(Name0),
proc_lib:init_ack(Starter, ignore),
exit(normal);
{'EXIT', Reason} ->
unregister_name(Name0),
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
Else ->
Error = {bad_return_value, Else},
proc_lib:init_ack(Starter, {error, Error}),
exit(Error)
end.
name({local,Name}) -> Name;
name({global,Name}) -> Name;
name(Pid ) when is_pid(Pid ) - > Pid ;
%% when R12 goes away, drop the line beneath and uncomment the line above
name(Name) -> Name.
unregister_name({local,Name}) ->
_ = (catch unregister(Name));
unregister_name({global,Name}) ->
_ = global:unregister_name(Name);
unregister_name(Pid) when is_pid(Pid) ->
Pid;
% Under R12 let's just ignore it, as we have a single term as Name.
% On R13 it will never get here, as we get tuple with 'local/global' atom.
unregister_name(_Name) -> ok.
extend_backoff(undefined) ->
undefined;
extend_backoff({backoff, InitialTimeout, MinimumTimeout, DesiredHibPeriod}) ->
{backoff, InitialTimeout, MinimumTimeout, DesiredHibPeriod, now()}.
%%%========================================================================
Internal functions
%%%========================================================================
%%% ---------------------------------------------------
%%% The MAIN loop.
%%% ---------------------------------------------------
loop(GS2State = #gs2_state { time = hibernate,
timeout_state = undefined }) ->
pre_hibernate(GS2State);
loop(GS2State) ->
process_next_msg(drain(GS2State)).
drain(GS2State) ->
receive
Input -> drain(in(Input, GS2State))
after 0 -> GS2State
end.
process_next_msg(GS2State = #gs2_state { time = Time,
timeout_state = TimeoutState,
queue = Queue }) ->
case priority_queue:out(Queue) of
{{value, Msg}, Queue1} ->
process_msg(Msg, GS2State #gs2_state { queue = Queue1 });
{empty, Queue1} ->
{Time1, HibOnTimeout}
= case {Time, TimeoutState} of
{hibernate, {backoff, Current, _Min, _Desired, _RSt}} ->
{Current, true};
{hibernate, _} ->
wake_hib/7 will set Time to hibernate . If
%% we were woken and didn't receive a msg
%% then we will get here and need a sensible
%% value for Time1, otherwise we crash.
%% R13B1 always waits infinitely when waking
%% from hibernation, so that's what we do
%% here too.
{infinity, false};
_ -> {Time, false}
end,
receive
Input ->
Time could be ' hibernate ' here , so * do n't * call loop
process_next_msg(
drain(in(Input, GS2State #gs2_state { queue = Queue1 })))
after Time1 ->
case HibOnTimeout of
true ->
pre_hibernate(
GS2State #gs2_state { queue = Queue1 });
false ->
process_msg(timeout,
GS2State #gs2_state { queue = Queue1 })
end
end
end.
wake_hib(GS2State = #gs2_state { timeout_state = TS }) ->
TimeoutState1 = case TS of
undefined ->
undefined;
{SleptAt, TimeoutState} ->
adjust_timeout_state(SleptAt, now(), TimeoutState)
end,
post_hibernate(
drain(GS2State #gs2_state { timeout_state = TimeoutState1 })).
hibernate(GS2State = #gs2_state { timeout_state = TimeoutState }) ->
TS = case TimeoutState of
undefined -> undefined;
{backoff, _, _, _, _} -> {now(), TimeoutState}
end,
proc_lib:hibernate(?MODULE, wake_hib,
[GS2State #gs2_state { timeout_state = TS }]).
pre_hibernate(GS2State = #gs2_state { state = State,
mod = Mod }) ->
case erlang:function_exported(Mod, handle_pre_hibernate, 1) of
true ->
case catch Mod:handle_pre_hibernate(State) of
{hibernate, NState} ->
hibernate(GS2State #gs2_state { state = NState } );
Reply ->
handle_common_termination(Reply, pre_hibernate, GS2State)
end;
false ->
hibernate(GS2State)
end.
post_hibernate(GS2State = #gs2_state { state = State,
mod = Mod }) ->
case erlang:function_exported(Mod, handle_post_hibernate, 1) of
true ->
case catch Mod:handle_post_hibernate(State) of
{noreply, NState} ->
process_next_msg(GS2State #gs2_state { state = NState,
time = infinity });
{noreply, NState, Time} ->
process_next_msg(GS2State #gs2_state { state = NState,
time = Time });
Reply ->
handle_common_termination(Reply, post_hibernate, GS2State)
end;
false ->
%% use hibernate here, not infinity. This matches
%% R13B. The key is that we should be able to get through
to process_msg calling : handle_system_msg with Time
%% still set to hibernate, iff that msg is the very msg
that woke us up ( or the first msg we receive after
%% waking up).
process_next_msg(GS2State #gs2_state { time = hibernate })
end.
adjust_timeout_state(SleptAt, AwokeAt, {backoff, CurrentTO, MinimumTO,
DesiredHibPeriod, RandomState}) ->
NapLengthMicros = timer:now_diff(AwokeAt, SleptAt),
CurrentMicros = CurrentTO * 1000,
MinimumMicros = MinimumTO * 1000,
DesiredHibMicros = DesiredHibPeriod * 1000,
GapBetweenMessagesMicros = NapLengthMicros + CurrentMicros,
Base =
If enough time has passed between the last two messages then we
%% should consider sleeping sooner. Otherwise stay awake longer.
case GapBetweenMessagesMicros > (MinimumMicros + DesiredHibMicros) of
true -> lists:max([MinimumTO, CurrentTO div 2]);
false -> CurrentTO
end,
{Extra, RandomState1} = random:uniform_s(Base, RandomState),
CurrentTO1 = Base + Extra,
{backoff, CurrentTO1, MinimumTO, DesiredHibPeriod, RandomState1}.
in({'$gen_cast', Msg}, GS2State = #gs2_state { prioritise_cast = PC,
queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
{'$gen_cast', Msg},
PC(Msg, GS2State), Queue) };
in({'$gen_call', From, Msg}, GS2State = #gs2_state { prioritise_call = PC,
queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
{'$gen_call', From, Msg},
PC(Msg, From, GS2State), Queue) };
in(Input, GS2State = #gs2_state { prioritise_info = PI, queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
Input, PI(Input, GS2State), Queue) }.
process_msg(Msg,
GS2State = #gs2_state { parent = Parent,
name = Name,
debug = Debug }) ->
case Msg of
{system, From, Req} ->
sys:handle_system_msg(
Req, From, Parent, ?MODULE, Debug,
GS2State);
gen_server puts Hib on the end as the 7th arg , but that
%% version of the function seems not to be documented so
%% leaving out for now.
{'EXIT', Parent, Reason} ->
terminate(Reason, Msg, GS2State);
_Msg when Debug =:= [] ->
handle_msg(Msg, GS2State);
_Msg ->
Debug1 = sys:handle_debug(Debug, fun print_event/3,
Name, {in, Msg}),
handle_msg(Msg, GS2State #gs2_state { debug = Debug1 })
end.
%%% ---------------------------------------------------
%%% Send/recive functions
%%% ---------------------------------------------------
do_send(Dest, Msg) ->
catch erlang:send(Dest, Msg).
do_multi_call(Nodes, Name, Req, infinity) ->
Tag = make_ref(),
Monitors = send_nodes(Nodes, Name, Tag, Req),
rec_nodes(Tag, Monitors, Name, undefined);
do_multi_call(Nodes, Name, Req, Timeout) ->
Tag = make_ref(),
Caller = self(),
Receiver =
spawn(
fun () ->
%% Middleman process. Should be unsensitive to regular
%% exit signals. The sychronization is needed in case
%% the receiver would exit before the caller started
%% the monitor.
process_flag(trap_exit, true),
Mref = erlang:monitor(process, Caller),
receive
{Caller,Tag} ->
Monitors = send_nodes(Nodes, Name, Tag, Req),
TimerId = erlang:start_timer(Timeout, self(), ok),
Result = rec_nodes(Tag, Monitors, Name, TimerId),
exit({self(),Tag,Result});
{'DOWN',Mref,_,_,_} ->
Caller died before sending us the go - ahead .
%% Give up silently.
exit(normal)
end
end),
Mref = erlang:monitor(process, Receiver),
Receiver ! {self(),Tag},
receive
{'DOWN',Mref,_,_,{Receiver,Tag,Result}} ->
Result;
{'DOWN',Mref,_,_,Reason} ->
%% The middleman code failed. Or someone did
%% exit(_, kill) on the middleman process => Reason==killed
exit(Reason)
end.
send_nodes(Nodes, Name, Tag, Req) ->
send_nodes(Nodes, Name, Tag, Req, []).
send_nodes([Node|Tail], Name, Tag, Req, Monitors)
when is_atom(Node) ->
Monitor = start_monitor(Node, Name),
%% Handle non-existing names in rec_nodes.
catch {Name, Node} ! {'$gen_call', {self(), {Tag, Node}}, Req},
send_nodes(Tail, Name, Tag, Req, [Monitor | Monitors]);
send_nodes([_Node|Tail], Name, Tag, Req, Monitors) ->
Skip non - atom Node
send_nodes(Tail, Name, Tag, Req, Monitors);
send_nodes([], _Name, _Tag, _Req, Monitors) ->
Monitors.
%% Against old nodes:
If no reply has been delivered within 2 secs . ( per node ) check that
%% the server really exists and wait for ever for the answer.
%%
%% Against contemporary nodes:
Wait for reply , server ' DOWN ' , or timeout from TimerId .
rec_nodes(Tag, Nodes, Name, TimerId) ->
rec_nodes(Tag, Nodes, Name, [], [], 2000, TimerId).
rec_nodes(Tag, [{N,R}|Tail], Name, Badnodes, Replies, Time, TimerId ) ->
receive
{'DOWN', R, _, _, _} ->
rec_nodes(Tag, Tail, Name, [N|Badnodes], Replies, Time, TimerId);
{{Tag, N}, Reply} -> %% Tag is bound !!!
unmonitor(R),
rec_nodes(Tag, Tail, Name, Badnodes,
[{N,Reply}|Replies], Time, TimerId);
{timeout, TimerId, _} ->
unmonitor(R),
%% Collect all replies that already have arrived
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes(Tag, [N|Tail], Name, Badnodes, Replies, Time, TimerId) ->
%% R6 node
receive
{nodedown, N} ->
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, [N|Badnodes], Replies, 2000, TimerId);
{{Tag, N}, Reply} -> %% Tag is bound !!!
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, Badnodes,
[{N,Reply}|Replies], 2000, TimerId);
{timeout, TimerId, _} ->
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
%% Collect all replies that already have arrived
rec_nodes_rest(Tag, Tail, Name, [N | Badnodes], Replies)
after Time ->
case rpc:call(N, erlang, whereis, [Name]) of
Pid when is_pid(Pid) -> % It exists try again.
rec_nodes(Tag, [N|Tail], Name, Badnodes,
Replies, infinity, TimerId);
_ -> % badnode
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, [N|Badnodes],
Replies, 2000, TimerId)
end
end;
rec_nodes(_, [], _, Badnodes, Replies, _, TimerId) ->
case catch erlang:cancel_timer(TimerId) of
false -> % It has already sent it's message
receive
{timeout, TimerId, _} -> ok
after 0 ->
ok
end;
Timer was cancelled , or was ' undefined '
ok
end,
{Replies, Badnodes}.
%% Collect all replies that already have arrived
rec_nodes_rest(Tag, [{N,R}|Tail], Name, Badnodes, Replies) ->
receive
{'DOWN', R, _, _, _} ->
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies);
{{Tag, N}, Reply} -> %% Tag is bound !!!
unmonitor(R),
rec_nodes_rest(Tag, Tail, Name, Badnodes, [{N,Reply}|Replies])
after 0 ->
unmonitor(R),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes_rest(Tag, [N|Tail], Name, Badnodes, Replies) ->
%% R6 node
receive
{nodedown, N} ->
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies);
{{Tag, N}, Reply} -> %% Tag is bound !!!
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, Badnodes, [{N,Reply}|Replies])
after 0 ->
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes_rest(_Tag, [], _Name, Badnodes, Replies) ->
{Replies, Badnodes}.
%%% ---------------------------------------------------
%%% Monitor functions
%%% ---------------------------------------------------
start_monitor(Node, Name) when is_atom(Node), is_atom(Name) ->
if node() =:= nonode@nohost, Node =/= nonode@nohost ->
Ref = make_ref(),
self() ! {'DOWN', Ref, process, {Name, Node}, noconnection},
{Node, Ref};
true ->
case catch erlang:monitor(process, {Name, Node}) of
{'EXIT', _} ->
%% Remote node is R6
monitor_node(Node, true),
Node;
Ref when is_reference(Ref) ->
{Node, Ref}
end
end.
%% Cancels a monitor started with Ref=erlang:monitor(_, _).
unmonitor(Ref) when is_reference(Ref) ->
erlang:demonitor(Ref),
receive
{'DOWN', Ref, _, _, _} ->
true
after 0 ->
true
end.
%%% ---------------------------------------------------
%%% Message handling functions
%%% ---------------------------------------------------
dispatch({'$gen_cast', Msg}, Mod, State) ->
Mod:handle_cast(Msg, State);
dispatch(Info, Mod, State) ->
Mod:handle_info(Info, State).
common_reply(_Name, From, Reply, _NState, [] = _Debug) ->
reply(From, Reply),
[];
common_reply(Name, From, Reply, NState, Debug) ->
reply(Name, From, Reply, NState, Debug).
common_debug([] = _Debug, _Func, _Info, _Event) ->
[];
common_debug(Debug, Func, Info, Event) ->
sys:handle_debug(Debug, Func, Info, Event).
handle_msg({'$gen_call', From, Msg}, GS2State = #gs2_state { mod = Mod,
state = State,
name = Name,
debug = Debug }) ->
case catch Mod:handle_call(Msg, From, State) of
{reply, Reply, NState} ->
Debug1 = common_reply(Name, From, Reply, NState, Debug),
loop(GS2State #gs2_state { state = NState,
time = infinity,
debug = Debug1 });
{reply, Reply, NState, Time1} ->
Debug1 = common_reply(Name, From, Reply, NState, Debug),
loop(GS2State #gs2_state { state = NState,
time = Time1,
debug = Debug1});
{noreply, NState} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state {state = NState,
time = infinity,
debug = Debug1});
{noreply, NState, Time1} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state {state = NState,
time = Time1,
debug = Debug1});
{stop, Reason, Reply, NState} ->
{'EXIT', R} =
(catch terminate(Reason, Msg,
GS2State #gs2_state { state = NState })),
reply(Name, From, Reply, NState, Debug),
exit(R);
Other ->
handle_common_reply(Other, Msg, GS2State)
end;
handle_msg(Msg, GS2State = #gs2_state { mod = Mod, state = State }) ->
Reply = (catch dispatch(Msg, Mod, State)),
handle_common_reply(Reply, Msg, GS2State).
handle_common_reply(Reply, Msg, GS2State = #gs2_state { name = Name,
debug = Debug}) ->
case Reply of
{noreply, NState} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state { state = NState,
time = infinity,
debug = Debug1 });
{noreply, NState, Time1} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state { state = NState,
time = Time1,
debug = Debug1 });
_ ->
handle_common_termination(Reply, Msg, GS2State)
end.
handle_common_termination(Reply, Msg, GS2State) ->
case Reply of
{stop, Reason, NState} ->
terminate(Reason, Msg, GS2State #gs2_state { state = NState });
{'EXIT', What} ->
terminate(What, Msg, GS2State);
_ ->
terminate({bad_return_value, Reply}, Msg, GS2State)
end.
reply(Name, {To, Tag}, Reply, State, Debug) ->
reply({To, Tag}, Reply),
sys:handle_debug(
Debug, fun print_event/3, Name, {out, Reply, To, State}).
%%-----------------------------------------------------------------
%% Callback functions for system messages handling.
%%-----------------------------------------------------------------
system_continue(Parent, Debug, GS2State) ->
loop(GS2State #gs2_state { parent = Parent, debug = Debug }).
system_terminate(Reason, _Parent, Debug, GS2State) ->
terminate(Reason, [], GS2State #gs2_state { debug = Debug }).
system_code_change(GS2State = #gs2_state { mod = Mod,
state = State },
_Module, OldVsn, Extra) ->
case catch Mod:code_change(OldVsn, State, Extra) of
{ok, NewState} ->
NewGS2State = find_prioritisers(
GS2State #gs2_state { state = NewState }),
{ok, [NewGS2State]};
Else ->
Else
end.
%%-----------------------------------------------------------------
%% Format debug messages. Print them as the call-back module sees
%% them, not as the real erlang messages. Use trace for that.
%%-----------------------------------------------------------------
print_event(Dev, {in, Msg}, Name) ->
case Msg of
{'$gen_call', {From, _Tag}, Call} ->
io:format(Dev, "*DBG* ~p got call ~p from ~w~n",
[Name, Call, From]);
{'$gen_cast', Cast} ->
io:format(Dev, "*DBG* ~p got cast ~p~n",
[Name, Cast]);
_ ->
io:format(Dev, "*DBG* ~p got ~p~n", [Name, Msg])
end;
print_event(Dev, {out, Msg, To, State}, Name) ->
io:format(Dev, "*DBG* ~p sent ~p to ~w, new state ~w~n",
[Name, Msg, To, State]);
print_event(Dev, {noreply, State}, Name) ->
io:format(Dev, "*DBG* ~p new state ~w~n", [Name, State]);
print_event(Dev, Event, Name) ->
io:format(Dev, "*DBG* ~p dbg ~p~n", [Name, Event]).
%%% ---------------------------------------------------
%%% Terminate the server.
%%% ---------------------------------------------------
terminate(Reason, Msg, #gs2_state { name = Name,
mod = Mod,
state = State,
debug = Debug }) ->
case catch Mod:terminate(Reason, State) of
{'EXIT', R} ->
error_info(R, Reason, Name, Msg, State, Debug),
exit(R);
_ ->
case Reason of
normal ->
exit(normal);
shutdown ->
exit(shutdown);
{shutdown,_}=Shutdown ->
exit(Shutdown);
_ ->
error_info(Reason, undefined, Name, Msg, State, Debug),
exit(Reason)
end
end.
error_info(_Reason, _RootCause, application_controller, _Msg, _State, _Debug) ->
%% OTP-5811 Don't send an error report if it's the system process
%% application_controller which is terminating - let init take care
%% of it instead
ok;
error_info(Reason, RootCause, Name, Msg, State, Debug) ->
Reason1 = error_reason(Reason),
Fmt =
"** Generic server ~p terminating~n"
"** Last message in was ~p~n"
"** When Server state == ~p~n"
"** Reason for termination == ~n** ~p~n",
case RootCause of
undefined -> format(Fmt, [Name, Msg, State, Reason1]);
_ -> format(Fmt ++ "** In 'terminate' callback "
"with reason ==~n** ~p~n",
[Name, Msg, State, Reason1,
error_reason(RootCause)])
end,
sys:print_log(Debug),
ok.
error_reason({undef,[{M,F,A}|MFAs]} = Reason) ->
case code:is_loaded(M) of
false -> {'module could not be loaded',[{M,F,A}|MFAs]};
_ -> case erlang:function_exported(M, F, length(A)) of
true -> Reason;
false -> {'function not exported',[{M,F,A}|MFAs]}
end
end;
error_reason(Reason) ->
Reason.
%%% ---------------------------------------------------
%%% Misc. functions.
%%% ---------------------------------------------------
opt(Op, [{Op, Value}|_]) ->
{ok, Value};
opt(Op, [_|Options]) ->
opt(Op, Options);
opt(_, []) ->
false.
debug_options(Name, Opts) ->
case opt(debug, Opts) of
{ok, Options} -> dbg_options(Name, Options);
_ -> dbg_options(Name, [])
end.
dbg_options(Name, []) ->
Opts =
case init:get_argument(generic_debug) of
error ->
[];
_ ->
[log, statistics]
end,
dbg_opts(Name, Opts);
dbg_options(Name, Opts) ->
dbg_opts(Name, Opts).
dbg_opts(Name, Opts) ->
case catch sys:debug_options(Opts) of
{'EXIT',_} ->
format("~p: ignoring erroneous debug options - ~p~n",
[Name, Opts]),
[];
Dbg ->
Dbg
end.
get_proc_name(Pid) when is_pid(Pid) ->
Pid;
get_proc_name({local, Name}) ->
case process_info(self(), registered_name) of
{registered_name, Name} ->
Name;
{registered_name, _Name} ->
exit(process_not_registered);
[] ->
exit(process_not_registered)
end;
get_proc_name({global, Name}) ->
case global:safe_whereis_name(Name) of
undefined ->
exit(process_not_registered_globally);
Pid when Pid =:= self() ->
Name;
_Pid ->
exit(process_not_registered_globally)
end.
get_parent() ->
case get('$ancestors') of
[Parent | _] when is_pid(Parent)->
Parent;
[Parent | _] when is_atom(Parent)->
name_to_pid(Parent);
_ ->
exit(process_was_not_started_by_proc_lib)
end.
name_to_pid(Name) ->
case whereis(Name) of
undefined ->
case global:safe_whereis_name(Name) of
undefined ->
exit(could_not_find_registerd_name);
Pid ->
Pid
end;
Pid ->
Pid
end.
find_prioritisers(GS2State = #gs2_state { mod = Mod }) ->
PrioriCall = function_exported_or_default(
Mod, 'prioritise_call', 3,
fun (_Msg, _From, _State) -> 0 end),
PrioriCast = function_exported_or_default(Mod, 'prioritise_cast', 2,
fun (_Msg, _State) -> 0 end),
PrioriInfo = function_exported_or_default(Mod, 'prioritise_info', 2,
fun (_Msg, _State) -> 0 end),
GS2State #gs2_state { prioritise_call = PrioriCall,
prioritise_cast = PrioriCast,
prioritise_info = PrioriInfo }.
function_exported_or_default(Mod, Fun, Arity, Default) ->
case erlang:function_exported(Mod, Fun, Arity) of
true -> case Arity of
2 -> fun (Msg, GS2State = #gs2_state { state = State }) ->
case catch Mod:Fun(Msg, State) of
Res when is_integer(Res) ->
Res;
Err ->
handle_common_termination(Err, Msg, GS2State)
end
end;
3 -> fun (Msg, From, GS2State = #gs2_state { state = State }) ->
case catch Mod:Fun(Msg, From, State) of
Res when is_integer(Res) ->
Res;
Err ->
handle_common_termination(Err, Msg, GS2State)
end
end
end;
false -> Default
end.
%%-----------------------------------------------------------------
%% Status information
%%-----------------------------------------------------------------
format_status(Opt, StatusData) ->
[PDict, SysState, Parent, Debug,
#gs2_state{name = Name, state = State, mod = Mod, queue = Queue}] =
StatusData,
NameTag = if is_pid(Name) ->
pid_to_list(Name);
is_atom(Name) ->
Name
end,
Header = lists:concat(["Status for generic server ", NameTag]),
Log = sys:get_debug(log, Debug, []),
Specfic =
case erlang:function_exported(Mod, format_status, 2) of
true -> case catch Mod:format_status(Opt, [PDict, State]) of
{'EXIT', _} -> [{data, [{"State", State}]}];
Else -> Else
end;
_ -> [{data, [{"State", State}]}]
end,
[{header, Header},
{data, [{"Status", SysState},
{"Parent", Parent},
{"Logged events", Log},
{"Queued messages", priority_queue:to_list(Queue)}]} |
Specfic].
| null | https://raw.githubusercontent.com/beamjs/erlv8/157a7db0a9c284ea1da107fe3272ff7b19813d26/src/gen_server2.erl | erlang | distribution, with the following modifications:
gen_server2 processes drain their message queue into an internal
buffer before invoking any callback module functions. Messages are
dequeued from the buffer for processing. Thus the effective message
queue of a gen_server2 process is the concatenation of the internal
buffer and the real message queue.
As a result of the draining, any selective receive invoked inside a
callback is less likely to have to scan a large message queue.
The original code could reorder messages when communicating with a
process on a remote node that was not currently connected.
prioritise_cast/2 and prioritise_info/2. These functions take
single integer representing the priority attached to the message.
Messages with higher priorities are processed before requests with
lower priorities. The default priority is 0.
handle_pre_hibernate/1 and handle_post_hibernate/1. These will be
called immediately prior to and post hibernation, respectively. If
will hibernate. If the module does not implement
handle_pre_hibernate/1 then the default action is to hibernate.
milliseconds). Then, on all callbacks which can return a timeout
(including init), timeout can be 'hibernate'. When this is the
case, the current timeout value will be used (initially, the
occurred, hibernation will occur as normal. Upon awaking, a new
current timeout value will be calculated.
The purpose is that the gen_server2 takes care of adjusting the
current timeout value such that the process will increase the
timeout value repeatedly if it is unable to sleep for the
DesiredHibernatePeriod it will decrease the current timeout down to
hopefully stays asleep for longer). In short, should a process
using this receive a burst of messages, it should not hibernate
between those messages, but as the messages become less frequent,
the process will not only hibernate, it will do so sooner after
each message.
When using this backoff mechanism, normal timeout values (i.e. not
'hibernate') can still be used, and if they are used then the
hibernate the process immediately, as it would if backoff wasn't
being used. Instead it'll wait for the current timeout as described
above.
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved via the world wide web at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
AB. All Rights Reserved.''
$Id$
---------------------------------------------------
The idea behind THIS server is that the user module
provides (different) functions to handle different
kind of inputs.
If the Parent process terminates the Module:terminate/2
function is called.
The user module should export:
init(Args)
==> {ok, State}
ignore
{stop, Reason}
==> {reply, Reply, State}
{stop, Reason, Reply, State}
Reason = normal | shutdown | Term terminate(State) is called
{stop, Reason, State}
Reason = normal | shutdown | Term terminate(State) is called
{stop, Reason, State}
Reason = normal | shutdown | Term, terminate(State) is called
terminate(Reason, State) Let the user module clean up
always called when server terminates
==> ok
handle_pre_hibernate(State)
==> {hibernate, State}
{stop, Reason, State}
Reason = normal | shutdown | Term, terminate(State) is called
handle_post_hibernate(State)
{stop, Reason, State}
Reason = normal | shutdown | Term, terminate(State) is called
The work flow (of the server) can be described as follows:
User module Generic
----------- -------
start -----> start
init <----- .
loop
handle_call <----- .
-----> reply
handle_cast <----- .
handle_info <----- .
terminate <----- .
-----> reply
---------------------------------------------------
API
System exports
Internal exports
=========================================================================
Specs. These exist only to shut up dialyzer's warnings
=========================================================================
=========================================================================
API
=========================================================================
-----------------------------------------------------------------
Starts a generic server.
Name ::= {local, atom()} | {global, atom()}
Mod ::= atom(), callback module implementing the 'real' server
Options ::= [{timeout, Timeout} | {debug, [Flag]}]
Flag ::= trace | log | {logfile, File} | statistics | debug
{error, Reason}
-----------------------------------------------------------------
-----------------------------------------------------------------
Make a call to a generic server.
If the server is located at another node, that node will
be monitored.
If the client is trapping exits and is linked server termination
is handled here (? Shall we do that here (or rely on timeouts) ?).
-----------------------------------------------------------------
-----------------------------------------------------------------
Make a cast to a generic server.
-----------------------------------------------------------------
-----------------------------------------------------------------
Send a reply to the client.
-----------------------------------------------------------------
-----------------------------------------------------------------
Asyncronous broadcast, returns nothing, it's just send'n pray
-----------------------------------------------------------------
-----------------------------------------------------------------
Make a call to servers at several nodes.
Returns: {[Replies],[BadNodes]}
A Timeout can be given
A middleman process is used in case late answers arrives after
the timeout. If they would be allowed to glog the callers message
queue, it would probably become confused. Late answers will
now arrive to the terminated middleman and so be discarded.
-----------------------------------------------------------------
-----------------------------------------------------------------
Description: Makes an existing process into a gen_server.
The calling process will enter the gen_server receive
loop and become a gen_server process.
start functions in proc_lib, see proc_lib(3).
The user is responsible for any initialization of the
process, including registering a name for it.
-----------------------------------------------------------------
========================================================================
Gen-callback functions
========================================================================
---------------------------------------------------
Initiate the new process.
Calls the Mod:init/Args function.
Finally an acknowledge is sent to Parent and the main
loop is entered.
---------------------------------------------------
For consistency, we must make sure that the
registered name (if any) is unregistered before
the parent process is notified about the failure.
(Otherwise, the parent process could get
an 'already_started' error if it immediately
tried starting the process again.)
when R12 goes away, drop the line beneath and uncomment the line above
Under R12 let's just ignore it, as we have a single term as Name.
On R13 it will never get here, as we get tuple with 'local/global' atom.
========================================================================
========================================================================
---------------------------------------------------
The MAIN loop.
---------------------------------------------------
we were woken and didn't receive a msg
then we will get here and need a sensible
value for Time1, otherwise we crash.
R13B1 always waits infinitely when waking
from hibernation, so that's what we do
here too.
use hibernate here, not infinity. This matches
R13B. The key is that we should be able to get through
still set to hibernate, iff that msg is the very msg
waking up).
should consider sleeping sooner. Otherwise stay awake longer.
version of the function seems not to be documented so
leaving out for now.
---------------------------------------------------
Send/recive functions
---------------------------------------------------
Middleman process. Should be unsensitive to regular
exit signals. The sychronization is needed in case
the receiver would exit before the caller started
the monitor.
Give up silently.
The middleman code failed. Or someone did
exit(_, kill) on the middleman process => Reason==killed
Handle non-existing names in rec_nodes.
Against old nodes:
the server really exists and wait for ever for the answer.
Against contemporary nodes:
Tag is bound !!!
Collect all replies that already have arrived
R6 node
Tag is bound !!!
Collect all replies that already have arrived
It exists try again.
badnode
It has already sent it's message
Collect all replies that already have arrived
Tag is bound !!!
R6 node
Tag is bound !!!
---------------------------------------------------
Monitor functions
---------------------------------------------------
Remote node is R6
Cancels a monitor started with Ref=erlang:monitor(_, _).
---------------------------------------------------
Message handling functions
---------------------------------------------------
-----------------------------------------------------------------
Callback functions for system messages handling.
-----------------------------------------------------------------
-----------------------------------------------------------------
Format debug messages. Print them as the call-back module sees
them, not as the real erlang messages. Use trace for that.
-----------------------------------------------------------------
---------------------------------------------------
Terminate the server.
---------------------------------------------------
OTP-5811 Don't send an error report if it's the system process
application_controller which is terminating - let init take care
of it instead
---------------------------------------------------
Misc. functions.
---------------------------------------------------
-----------------------------------------------------------------
Status information
----------------------------------------------------------------- | This file is a copy of gen_server.erl from the R13B-1 Erlang / OTP
1 ) the module name is gen_server2
2 ) more efficient handling of selective receives in callbacks
3 ) gen_server2 : cast is guaranteed to be order - preserving
4 ) The callback module can optionally implement prioritise_call/3 ,
Message , From and State or just Message and State and return a
5 ) The callback module can optionally implement
handle_pre_hibernate returns { hibernate , NewState } then the process
6 ) init can return a 4th arg , { backoff , InitialTimeout ,
MinimumTimeout , DesiredHibernatePeriod } ( all in
InitialTimeout supplied from init ) . After this timeout has
DesiredHibernatePeriod . If it is able to sleep for the
the MinimumTimeout , so that the process is put to sleep sooner ( and
handle_info(timeout , State ) will be called as normal . In this case ,
returning ' hibernate ' from handle_info(timeout , State ) will not
All modifications are ( C ) 2009 - 2010 LShift Ltd.
` ` The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Initial Developer of the Original Code is Ericsson Utvecklings AB .
Portions created by Ericsson are Copyright 1999 ,
-module(gen_server2).
{ ok , State , Timeout }
{ ok , State , Timeout , Backoff }
handle_call(Msg , { From , Tag } , State )
{ reply , Reply , State , Timeout }
{ noreply , State }
{ noreply , State , Timeout }
handle_cast(Msg , State )
= = > { noreply , State }
{ noreply , State , Timeout }
handle_info(Info , State ) Info is e.g. { ' EXIT ' , P , R } , { nodedown , N } , ...
= = > { noreply , State }
{ noreply , State , Timeout }
= = > { noreply , State }
-export([start/3, start/4,
start_link/3, start_link/4,
call/2, call/3,
cast/2, reply/2,
abcast/2, abcast/3,
multi_call/2, multi_call/3, multi_call/4,
enter_loop/3, enter_loop/4, enter_loop/5, enter_loop/6, wake_hib/1]).
-export([behaviour_info/1]).
-export([system_continue/3,
system_terminate/4,
system_code_change/4,
format_status/2]).
-export([init_it/6]).
-import(error_logger, [format/2]).
State record
-record(gs2_state, {parent, name, state, mod, time,
timeout_state, queue, debug, prioritise_call,
prioritise_cast, prioritise_info}).
-ifdef(use_specs).
-type(gs2_state() :: #gs2_state{}).
-spec(handle_common_termination/3 ::
(any(), atom(), gs2_state()) -> no_return()).
-spec(hibernate/1 :: (gs2_state()) -> no_return()).
-spec(pre_hibernate/1 :: (gs2_state()) -> no_return()).
-spec(system_terminate/4 :: (_, _, _, gs2_state()) -> no_return()).
-endif.
behaviour_info(callbacks) ->
[{init,1},{handle_call,3},{handle_cast,2},{handle_info,2},
{terminate,2},{code_change,3}];
behaviour_info(_Other) ->
undefined.
start(Mod , , Options )
start(Name , , , Options )
start_link(Mod , , Options )
start_link(Name , , , Options ) where :
: : = term ( ) , init arguments ( to Mod : init/1 )
( debug = = log & & statistics )
Returns : { ok , Pid } |
{ error , { already_started , Pid } } |
start(Mod, Args, Options) ->
gen:start(?MODULE, nolink, Mod, Args, Options).
start(Name, Mod, Args, Options) ->
gen:start(?MODULE, nolink, Name, Mod, Args, Options).
start_link(Mod, Args, Options) ->
gen:start(?MODULE, link, Mod, Args, Options).
start_link(Name, Mod, Args, Options) ->
gen:start(?MODULE, link, Name, Mod, Args, Options).
call(Name, Request) ->
case catch gen:call(Name, '$gen_call', Request) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, call, [Name, Request]}})
end.
call(Name, Request, Timeout) ->
case catch gen:call(Name, '$gen_call', Request, Timeout) of
{ok,Res} ->
Res;
{'EXIT',Reason} ->
exit({Reason, {?MODULE, call, [Name, Request, Timeout]}})
end.
cast({global,Name}, Request) ->
catch global:send(Name, cast_msg(Request)),
ok;
cast({Name,Node}=Dest, Request) when is_atom(Name), is_atom(Node) ->
do_cast(Dest, Request);
cast(Dest, Request) when is_atom(Dest) ->
do_cast(Dest, Request);
cast(Dest, Request) when is_pid(Dest) ->
do_cast(Dest, Request).
do_cast(Dest, Request) ->
do_send(Dest, cast_msg(Request)),
ok.
cast_msg(Request) -> {'$gen_cast',Request}.
reply({To, Tag}, Reply) ->
catch To ! {Tag, Reply}.
abcast(Name, Request) when is_atom(Name) ->
do_abcast([node() | nodes()], Name, cast_msg(Request)).
abcast(Nodes, Name, Request) when is_list(Nodes), is_atom(Name) ->
do_abcast(Nodes, Name, cast_msg(Request)).
do_abcast([Node|Nodes], Name, Msg) when is_atom(Node) ->
do_send({Name,Node},Msg),
do_abcast(Nodes, Name, Msg);
do_abcast([], _,_) -> abcast.
multi_call(Name, Req)
when is_atom(Name) ->
do_multi_call([node() | nodes()], Name, Req, infinity).
multi_call(Nodes, Name, Req)
when is_list(Nodes), is_atom(Name) ->
do_multi_call(Nodes, Name, Req, infinity).
multi_call(Nodes, Name, Req, infinity) ->
do_multi_call(Nodes, Name, Req, infinity);
multi_call(Nodes, Name, Req, Timeout)
when is_list(Nodes), is_atom(Name), is_integer(Timeout), Timeout >= 0 ->
do_multi_call(Nodes, Name, Req, Timeout).
enter_loop(Mod , Options , State , < ServerName > , < TimeOut > , < Backoff > ) - > _
The process * must * have been started using one of the
enter_loop(Mod, Options, State) ->
enter_loop(Mod, Options, State, self(), infinity, undefined).
enter_loop(Mod, Options, State, Backoff = {backoff, _, _ , _}) ->
enter_loop(Mod, Options, State, self(), infinity, Backoff);
enter_loop(Mod, Options, State, ServerName = {_, _}) ->
enter_loop(Mod, Options, State, ServerName, infinity, undefined);
enter_loop(Mod, Options, State, Timeout) ->
enter_loop(Mod, Options, State, self(), Timeout, undefined).
enter_loop(Mod, Options, State, ServerName, Backoff = {backoff, _, _, _}) ->
enter_loop(Mod, Options, State, ServerName, infinity, Backoff);
enter_loop(Mod, Options, State, ServerName, Timeout) ->
enter_loop(Mod, Options, State, ServerName, Timeout, undefined).
enter_loop(Mod, Options, State, ServerName, Timeout, Backoff) ->
Name = get_proc_name(ServerName),
Parent = get_parent(),
Debug = debug_options(Name, Options),
Queue = priority_queue:new(),
Backoff1 = extend_backoff(Backoff),
loop(find_prioritisers(
#gs2_state { parent = Parent, name = Name, state = State,
mod = Mod, time = Timeout, timeout_state = Backoff1,
queue = Queue, debug = Debug })).
Register the name using the Rfunc function
init_it(Starter, self, Name, Mod, Args, Options) ->
init_it(Starter, self(), Name, Mod, Args, Options);
init_it(Starter, Parent, Name0, Mod, Args, Options) ->
Name = name(Name0),
Debug = debug_options(Name, Options),
Queue = priority_queue:new(),
GS2State = find_prioritisers(
#gs2_state { parent = Parent,
name = Name,
mod = Mod,
queue = Queue,
debug = Debug }),
case catch Mod:init(Args) of
{ok, State} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = infinity,
timeout_state = undefined });
{ok, State, Timeout} ->
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = Timeout,
timeout_state = undefined });
{ok, State, Timeout, Backoff = {backoff, _, _, _}} ->
Backoff1 = extend_backoff(Backoff),
proc_lib:init_ack(Starter, {ok, self()}),
loop(GS2State #gs2_state { state = State,
time = Timeout,
timeout_state = Backoff1 });
{stop, Reason} ->
unregister_name(Name0),
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
ignore ->
unregister_name(Name0),
proc_lib:init_ack(Starter, ignore),
exit(normal);
{'EXIT', Reason} ->
unregister_name(Name0),
proc_lib:init_ack(Starter, {error, Reason}),
exit(Reason);
Else ->
Error = {bad_return_value, Else},
proc_lib:init_ack(Starter, {error, Error}),
exit(Error)
end.
name({local,Name}) -> Name;
name({global,Name}) -> Name;
name(Pid ) when is_pid(Pid ) - > Pid ;
name(Name) -> Name.
unregister_name({local,Name}) ->
_ = (catch unregister(Name));
unregister_name({global,Name}) ->
_ = global:unregister_name(Name);
unregister_name(Pid) when is_pid(Pid) ->
Pid;
unregister_name(_Name) -> ok.
extend_backoff(undefined) ->
undefined;
extend_backoff({backoff, InitialTimeout, MinimumTimeout, DesiredHibPeriod}) ->
{backoff, InitialTimeout, MinimumTimeout, DesiredHibPeriod, now()}.
Internal functions
loop(GS2State = #gs2_state { time = hibernate,
timeout_state = undefined }) ->
pre_hibernate(GS2State);
loop(GS2State) ->
process_next_msg(drain(GS2State)).
drain(GS2State) ->
receive
Input -> drain(in(Input, GS2State))
after 0 -> GS2State
end.
process_next_msg(GS2State = #gs2_state { time = Time,
timeout_state = TimeoutState,
queue = Queue }) ->
case priority_queue:out(Queue) of
{{value, Msg}, Queue1} ->
process_msg(Msg, GS2State #gs2_state { queue = Queue1 });
{empty, Queue1} ->
{Time1, HibOnTimeout}
= case {Time, TimeoutState} of
{hibernate, {backoff, Current, _Min, _Desired, _RSt}} ->
{Current, true};
{hibernate, _} ->
wake_hib/7 will set Time to hibernate . If
{infinity, false};
_ -> {Time, false}
end,
receive
Input ->
Time could be ' hibernate ' here , so * do n't * call loop
process_next_msg(
drain(in(Input, GS2State #gs2_state { queue = Queue1 })))
after Time1 ->
case HibOnTimeout of
true ->
pre_hibernate(
GS2State #gs2_state { queue = Queue1 });
false ->
process_msg(timeout,
GS2State #gs2_state { queue = Queue1 })
end
end
end.
wake_hib(GS2State = #gs2_state { timeout_state = TS }) ->
TimeoutState1 = case TS of
undefined ->
undefined;
{SleptAt, TimeoutState} ->
adjust_timeout_state(SleptAt, now(), TimeoutState)
end,
post_hibernate(
drain(GS2State #gs2_state { timeout_state = TimeoutState1 })).
hibernate(GS2State = #gs2_state { timeout_state = TimeoutState }) ->
TS = case TimeoutState of
undefined -> undefined;
{backoff, _, _, _, _} -> {now(), TimeoutState}
end,
proc_lib:hibernate(?MODULE, wake_hib,
[GS2State #gs2_state { timeout_state = TS }]).
pre_hibernate(GS2State = #gs2_state { state = State,
mod = Mod }) ->
case erlang:function_exported(Mod, handle_pre_hibernate, 1) of
true ->
case catch Mod:handle_pre_hibernate(State) of
{hibernate, NState} ->
hibernate(GS2State #gs2_state { state = NState } );
Reply ->
handle_common_termination(Reply, pre_hibernate, GS2State)
end;
false ->
hibernate(GS2State)
end.
post_hibernate(GS2State = #gs2_state { state = State,
mod = Mod }) ->
case erlang:function_exported(Mod, handle_post_hibernate, 1) of
true ->
case catch Mod:handle_post_hibernate(State) of
{noreply, NState} ->
process_next_msg(GS2State #gs2_state { state = NState,
time = infinity });
{noreply, NState, Time} ->
process_next_msg(GS2State #gs2_state { state = NState,
time = Time });
Reply ->
handle_common_termination(Reply, post_hibernate, GS2State)
end;
false ->
to process_msg calling : handle_system_msg with Time
that woke us up ( or the first msg we receive after
process_next_msg(GS2State #gs2_state { time = hibernate })
end.
adjust_timeout_state(SleptAt, AwokeAt, {backoff, CurrentTO, MinimumTO,
DesiredHibPeriod, RandomState}) ->
NapLengthMicros = timer:now_diff(AwokeAt, SleptAt),
CurrentMicros = CurrentTO * 1000,
MinimumMicros = MinimumTO * 1000,
DesiredHibMicros = DesiredHibPeriod * 1000,
GapBetweenMessagesMicros = NapLengthMicros + CurrentMicros,
Base =
If enough time has passed between the last two messages then we
case GapBetweenMessagesMicros > (MinimumMicros + DesiredHibMicros) of
true -> lists:max([MinimumTO, CurrentTO div 2]);
false -> CurrentTO
end,
{Extra, RandomState1} = random:uniform_s(Base, RandomState),
CurrentTO1 = Base + Extra,
{backoff, CurrentTO1, MinimumTO, DesiredHibPeriod, RandomState1}.
in({'$gen_cast', Msg}, GS2State = #gs2_state { prioritise_cast = PC,
queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
{'$gen_cast', Msg},
PC(Msg, GS2State), Queue) };
in({'$gen_call', From, Msg}, GS2State = #gs2_state { prioritise_call = PC,
queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
{'$gen_call', From, Msg},
PC(Msg, From, GS2State), Queue) };
in(Input, GS2State = #gs2_state { prioritise_info = PI, queue = Queue }) ->
GS2State #gs2_state { queue = priority_queue:in(
Input, PI(Input, GS2State), Queue) }.
process_msg(Msg,
GS2State = #gs2_state { parent = Parent,
name = Name,
debug = Debug }) ->
case Msg of
{system, From, Req} ->
sys:handle_system_msg(
Req, From, Parent, ?MODULE, Debug,
GS2State);
gen_server puts Hib on the end as the 7th arg , but that
{'EXIT', Parent, Reason} ->
terminate(Reason, Msg, GS2State);
_Msg when Debug =:= [] ->
handle_msg(Msg, GS2State);
_Msg ->
Debug1 = sys:handle_debug(Debug, fun print_event/3,
Name, {in, Msg}),
handle_msg(Msg, GS2State #gs2_state { debug = Debug1 })
end.
do_send(Dest, Msg) ->
catch erlang:send(Dest, Msg).
do_multi_call(Nodes, Name, Req, infinity) ->
Tag = make_ref(),
Monitors = send_nodes(Nodes, Name, Tag, Req),
rec_nodes(Tag, Monitors, Name, undefined);
do_multi_call(Nodes, Name, Req, Timeout) ->
Tag = make_ref(),
Caller = self(),
Receiver =
spawn(
fun () ->
process_flag(trap_exit, true),
Mref = erlang:monitor(process, Caller),
receive
{Caller,Tag} ->
Monitors = send_nodes(Nodes, Name, Tag, Req),
TimerId = erlang:start_timer(Timeout, self(), ok),
Result = rec_nodes(Tag, Monitors, Name, TimerId),
exit({self(),Tag,Result});
{'DOWN',Mref,_,_,_} ->
Caller died before sending us the go - ahead .
exit(normal)
end
end),
Mref = erlang:monitor(process, Receiver),
Receiver ! {self(),Tag},
receive
{'DOWN',Mref,_,_,{Receiver,Tag,Result}} ->
Result;
{'DOWN',Mref,_,_,Reason} ->
exit(Reason)
end.
send_nodes(Nodes, Name, Tag, Req) ->
send_nodes(Nodes, Name, Tag, Req, []).
send_nodes([Node|Tail], Name, Tag, Req, Monitors)
when is_atom(Node) ->
Monitor = start_monitor(Node, Name),
catch {Name, Node} ! {'$gen_call', {self(), {Tag, Node}}, Req},
send_nodes(Tail, Name, Tag, Req, [Monitor | Monitors]);
send_nodes([_Node|Tail], Name, Tag, Req, Monitors) ->
Skip non - atom Node
send_nodes(Tail, Name, Tag, Req, Monitors);
send_nodes([], _Name, _Tag, _Req, Monitors) ->
Monitors.
If no reply has been delivered within 2 secs . ( per node ) check that
Wait for reply , server ' DOWN ' , or timeout from TimerId .
rec_nodes(Tag, Nodes, Name, TimerId) ->
rec_nodes(Tag, Nodes, Name, [], [], 2000, TimerId).
rec_nodes(Tag, [{N,R}|Tail], Name, Badnodes, Replies, Time, TimerId ) ->
receive
{'DOWN', R, _, _, _} ->
rec_nodes(Tag, Tail, Name, [N|Badnodes], Replies, Time, TimerId);
unmonitor(R),
rec_nodes(Tag, Tail, Name, Badnodes,
[{N,Reply}|Replies], Time, TimerId);
{timeout, TimerId, _} ->
unmonitor(R),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes(Tag, [N|Tail], Name, Badnodes, Replies, Time, TimerId) ->
receive
{nodedown, N} ->
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, [N|Badnodes], Replies, 2000, TimerId);
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, Badnodes,
[{N,Reply}|Replies], 2000, TimerId);
{timeout, TimerId, _} ->
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, [N | Badnodes], Replies)
after Time ->
case rpc:call(N, erlang, whereis, [Name]) of
rec_nodes(Tag, [N|Tail], Name, Badnodes,
Replies, infinity, TimerId);
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes(Tag, Tail, Name, [N|Badnodes],
Replies, 2000, TimerId)
end
end;
rec_nodes(_, [], _, Badnodes, Replies, _, TimerId) ->
case catch erlang:cancel_timer(TimerId) of
receive
{timeout, TimerId, _} -> ok
after 0 ->
ok
end;
Timer was cancelled , or was ' undefined '
ok
end,
{Replies, Badnodes}.
rec_nodes_rest(Tag, [{N,R}|Tail], Name, Badnodes, Replies) ->
receive
{'DOWN', R, _, _, _} ->
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies);
unmonitor(R),
rec_nodes_rest(Tag, Tail, Name, Badnodes, [{N,Reply}|Replies])
after 0 ->
unmonitor(R),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes_rest(Tag, [N|Tail], Name, Badnodes, Replies) ->
receive
{nodedown, N} ->
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies);
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, Badnodes, [{N,Reply}|Replies])
after 0 ->
receive {nodedown, N} -> ok after 0 -> ok end,
monitor_node(N, false),
rec_nodes_rest(Tag, Tail, Name, [N|Badnodes], Replies)
end;
rec_nodes_rest(_Tag, [], _Name, Badnodes, Replies) ->
{Replies, Badnodes}.
start_monitor(Node, Name) when is_atom(Node), is_atom(Name) ->
if node() =:= nonode@nohost, Node =/= nonode@nohost ->
Ref = make_ref(),
self() ! {'DOWN', Ref, process, {Name, Node}, noconnection},
{Node, Ref};
true ->
case catch erlang:monitor(process, {Name, Node}) of
{'EXIT', _} ->
monitor_node(Node, true),
Node;
Ref when is_reference(Ref) ->
{Node, Ref}
end
end.
unmonitor(Ref) when is_reference(Ref) ->
erlang:demonitor(Ref),
receive
{'DOWN', Ref, _, _, _} ->
true
after 0 ->
true
end.
dispatch({'$gen_cast', Msg}, Mod, State) ->
Mod:handle_cast(Msg, State);
dispatch(Info, Mod, State) ->
Mod:handle_info(Info, State).
common_reply(_Name, From, Reply, _NState, [] = _Debug) ->
reply(From, Reply),
[];
common_reply(Name, From, Reply, NState, Debug) ->
reply(Name, From, Reply, NState, Debug).
common_debug([] = _Debug, _Func, _Info, _Event) ->
[];
common_debug(Debug, Func, Info, Event) ->
sys:handle_debug(Debug, Func, Info, Event).
handle_msg({'$gen_call', From, Msg}, GS2State = #gs2_state { mod = Mod,
state = State,
name = Name,
debug = Debug }) ->
case catch Mod:handle_call(Msg, From, State) of
{reply, Reply, NState} ->
Debug1 = common_reply(Name, From, Reply, NState, Debug),
loop(GS2State #gs2_state { state = NState,
time = infinity,
debug = Debug1 });
{reply, Reply, NState, Time1} ->
Debug1 = common_reply(Name, From, Reply, NState, Debug),
loop(GS2State #gs2_state { state = NState,
time = Time1,
debug = Debug1});
{noreply, NState} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state {state = NState,
time = infinity,
debug = Debug1});
{noreply, NState, Time1} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state {state = NState,
time = Time1,
debug = Debug1});
{stop, Reason, Reply, NState} ->
{'EXIT', R} =
(catch terminate(Reason, Msg,
GS2State #gs2_state { state = NState })),
reply(Name, From, Reply, NState, Debug),
exit(R);
Other ->
handle_common_reply(Other, Msg, GS2State)
end;
handle_msg(Msg, GS2State = #gs2_state { mod = Mod, state = State }) ->
Reply = (catch dispatch(Msg, Mod, State)),
handle_common_reply(Reply, Msg, GS2State).
handle_common_reply(Reply, Msg, GS2State = #gs2_state { name = Name,
debug = Debug}) ->
case Reply of
{noreply, NState} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state { state = NState,
time = infinity,
debug = Debug1 });
{noreply, NState, Time1} ->
Debug1 = common_debug(Debug, fun print_event/3, Name,
{noreply, NState}),
loop(GS2State #gs2_state { state = NState,
time = Time1,
debug = Debug1 });
_ ->
handle_common_termination(Reply, Msg, GS2State)
end.
handle_common_termination(Reply, Msg, GS2State) ->
case Reply of
{stop, Reason, NState} ->
terminate(Reason, Msg, GS2State #gs2_state { state = NState });
{'EXIT', What} ->
terminate(What, Msg, GS2State);
_ ->
terminate({bad_return_value, Reply}, Msg, GS2State)
end.
reply(Name, {To, Tag}, Reply, State, Debug) ->
reply({To, Tag}, Reply),
sys:handle_debug(
Debug, fun print_event/3, Name, {out, Reply, To, State}).
system_continue(Parent, Debug, GS2State) ->
loop(GS2State #gs2_state { parent = Parent, debug = Debug }).
system_terminate(Reason, _Parent, Debug, GS2State) ->
terminate(Reason, [], GS2State #gs2_state { debug = Debug }).
system_code_change(GS2State = #gs2_state { mod = Mod,
state = State },
_Module, OldVsn, Extra) ->
case catch Mod:code_change(OldVsn, State, Extra) of
{ok, NewState} ->
NewGS2State = find_prioritisers(
GS2State #gs2_state { state = NewState }),
{ok, [NewGS2State]};
Else ->
Else
end.
print_event(Dev, {in, Msg}, Name) ->
case Msg of
{'$gen_call', {From, _Tag}, Call} ->
io:format(Dev, "*DBG* ~p got call ~p from ~w~n",
[Name, Call, From]);
{'$gen_cast', Cast} ->
io:format(Dev, "*DBG* ~p got cast ~p~n",
[Name, Cast]);
_ ->
io:format(Dev, "*DBG* ~p got ~p~n", [Name, Msg])
end;
print_event(Dev, {out, Msg, To, State}, Name) ->
io:format(Dev, "*DBG* ~p sent ~p to ~w, new state ~w~n",
[Name, Msg, To, State]);
print_event(Dev, {noreply, State}, Name) ->
io:format(Dev, "*DBG* ~p new state ~w~n", [Name, State]);
print_event(Dev, Event, Name) ->
io:format(Dev, "*DBG* ~p dbg ~p~n", [Name, Event]).
terminate(Reason, Msg, #gs2_state { name = Name,
mod = Mod,
state = State,
debug = Debug }) ->
case catch Mod:terminate(Reason, State) of
{'EXIT', R} ->
error_info(R, Reason, Name, Msg, State, Debug),
exit(R);
_ ->
case Reason of
normal ->
exit(normal);
shutdown ->
exit(shutdown);
{shutdown,_}=Shutdown ->
exit(Shutdown);
_ ->
error_info(Reason, undefined, Name, Msg, State, Debug),
exit(Reason)
end
end.
error_info(_Reason, _RootCause, application_controller, _Msg, _State, _Debug) ->
ok;
error_info(Reason, RootCause, Name, Msg, State, Debug) ->
Reason1 = error_reason(Reason),
Fmt =
"** Generic server ~p terminating~n"
"** Last message in was ~p~n"
"** When Server state == ~p~n"
"** Reason for termination == ~n** ~p~n",
case RootCause of
undefined -> format(Fmt, [Name, Msg, State, Reason1]);
_ -> format(Fmt ++ "** In 'terminate' callback "
"with reason ==~n** ~p~n",
[Name, Msg, State, Reason1,
error_reason(RootCause)])
end,
sys:print_log(Debug),
ok.
error_reason({undef,[{M,F,A}|MFAs]} = Reason) ->
case code:is_loaded(M) of
false -> {'module could not be loaded',[{M,F,A}|MFAs]};
_ -> case erlang:function_exported(M, F, length(A)) of
true -> Reason;
false -> {'function not exported',[{M,F,A}|MFAs]}
end
end;
error_reason(Reason) ->
Reason.
opt(Op, [{Op, Value}|_]) ->
{ok, Value};
opt(Op, [_|Options]) ->
opt(Op, Options);
opt(_, []) ->
false.
debug_options(Name, Opts) ->
case opt(debug, Opts) of
{ok, Options} -> dbg_options(Name, Options);
_ -> dbg_options(Name, [])
end.
dbg_options(Name, []) ->
Opts =
case init:get_argument(generic_debug) of
error ->
[];
_ ->
[log, statistics]
end,
dbg_opts(Name, Opts);
dbg_options(Name, Opts) ->
dbg_opts(Name, Opts).
dbg_opts(Name, Opts) ->
case catch sys:debug_options(Opts) of
{'EXIT',_} ->
format("~p: ignoring erroneous debug options - ~p~n",
[Name, Opts]),
[];
Dbg ->
Dbg
end.
get_proc_name(Pid) when is_pid(Pid) ->
Pid;
get_proc_name({local, Name}) ->
case process_info(self(), registered_name) of
{registered_name, Name} ->
Name;
{registered_name, _Name} ->
exit(process_not_registered);
[] ->
exit(process_not_registered)
end;
get_proc_name({global, Name}) ->
case global:safe_whereis_name(Name) of
undefined ->
exit(process_not_registered_globally);
Pid when Pid =:= self() ->
Name;
_Pid ->
exit(process_not_registered_globally)
end.
get_parent() ->
case get('$ancestors') of
[Parent | _] when is_pid(Parent)->
Parent;
[Parent | _] when is_atom(Parent)->
name_to_pid(Parent);
_ ->
exit(process_was_not_started_by_proc_lib)
end.
name_to_pid(Name) ->
case whereis(Name) of
undefined ->
case global:safe_whereis_name(Name) of
undefined ->
exit(could_not_find_registerd_name);
Pid ->
Pid
end;
Pid ->
Pid
end.
find_prioritisers(GS2State = #gs2_state { mod = Mod }) ->
PrioriCall = function_exported_or_default(
Mod, 'prioritise_call', 3,
fun (_Msg, _From, _State) -> 0 end),
PrioriCast = function_exported_or_default(Mod, 'prioritise_cast', 2,
fun (_Msg, _State) -> 0 end),
PrioriInfo = function_exported_or_default(Mod, 'prioritise_info', 2,
fun (_Msg, _State) -> 0 end),
GS2State #gs2_state { prioritise_call = PrioriCall,
prioritise_cast = PrioriCast,
prioritise_info = PrioriInfo }.
function_exported_or_default(Mod, Fun, Arity, Default) ->
case erlang:function_exported(Mod, Fun, Arity) of
true -> case Arity of
2 -> fun (Msg, GS2State = #gs2_state { state = State }) ->
case catch Mod:Fun(Msg, State) of
Res when is_integer(Res) ->
Res;
Err ->
handle_common_termination(Err, Msg, GS2State)
end
end;
3 -> fun (Msg, From, GS2State = #gs2_state { state = State }) ->
case catch Mod:Fun(Msg, From, State) of
Res when is_integer(Res) ->
Res;
Err ->
handle_common_termination(Err, Msg, GS2State)
end
end
end;
false -> Default
end.
format_status(Opt, StatusData) ->
[PDict, SysState, Parent, Debug,
#gs2_state{name = Name, state = State, mod = Mod, queue = Queue}] =
StatusData,
NameTag = if is_pid(Name) ->
pid_to_list(Name);
is_atom(Name) ->
Name
end,
Header = lists:concat(["Status for generic server ", NameTag]),
Log = sys:get_debug(log, Debug, []),
Specfic =
case erlang:function_exported(Mod, format_status, 2) of
true -> case catch Mod:format_status(Opt, [PDict, State]) of
{'EXIT', _} -> [{data, [{"State", State}]}];
Else -> Else
end;
_ -> [{data, [{"State", State}]}]
end,
[{header, Header},
{data, [{"Status", SysState},
{"Parent", Parent},
{"Logged events", Log},
{"Queued messages", priority_queue:to_list(Queue)}]} |
Specfic].
|
06fcb02e5d0cb10e9e0294cf06c69b148d168852095c36bf9176b6557f2d317f | somnusand/Poker | hackney_connect.erl | %%% -*- erlang -*-
%%%
This file is part of hackney released under the Apache 2 license .
%%% See the NOTICE for more information.
%%%
-module(hackney_connect).
-export([connect/3, connect/4, connect/5,
create_connection/4, create_connection/5,
maybe_connect/1,
reconnect/4,
set_sockopts/2,
ssl_opts/2,
check_or_close/1,
close/1,
is_pool/1]).
-export([partial_chain/1]).
-include("hackney.hrl").
-include_lib("hackney_internal.hrl").
-include_lib("public_key/include/OTP-PUB-KEY.hrl").
connect(Transport, Host, Port) ->
connect(Transport, Host, Port, []).
connect(Transport, Host, Port, Options) ->
connect(Transport, Host, Port, Options, false).
connect(Transport, Host, Port, Options, Dynamic) when is_binary(Host) ->
connect(Transport, binary_to_list(Host), Port, Options, Dynamic);
connect(Transport, Host, Port, Options, Dynamic) ->
?report_debug("connect", [{transport, Transport},
{host, Host},
{port, Port},
{dynamic, Dynamic}]),
case create_connection(Transport, idna:utf8_to_ascii(Host), Port,
Options, Dynamic) of
{ok, #client{request_ref=Ref}} ->
{ok, Ref};
Error ->
Error
end.
%% @doc create a connection and return a client state
create_connection(Transport, Host, Port, Options) ->
create_connection(Transport, Host, Port, Options, true).
create_connection(Transport, Host, Port, Options, Dynamic)
when is_list(Options) ->
Netloc = case {Transport, Port} of
{hackney_tcp, 80} -> list_to_binary(Host);
{hackney_ssl, 443} -> list_to_binary(Host);
_ ->
iolist_to_binary([Host, ":", integer_to_list(Port)])
end,
%% default timeout
Timeout = proplists:get_value(recv_timeout, Options, ?RECV_TIMEOUT),
FollowRedirect = proplists:get_value(follow_redirect, Options, false),
MaxRedirect = proplists:get_value(max_redirect, Options, 5),
ForceRedirect = proplists:get_value(force_redirect, Options, false),
Async = proplists:get_value(async, Options, false),
StreamTo = proplists:get_value(stream_to, Options, false),
WithBody = proplists:get_value(with_body, Options, false),
MaxBody = proplists:get_value(max_body, Options),
%% get mod metrics
Engine = metrics:init(hackney_util:mod_metrics()),
%% initial state
InitialState = #client{mod_metrics=Engine,
transport=Transport,
host=Host,
port=Port,
netloc=Netloc,
options=Options,
dynamic=Dynamic,
recv_timeout=Timeout,
follow_redirect=FollowRedirect,
max_redirect=MaxRedirect,
retries=MaxRedirect,
force_redirect=ForceRedirect,
async=Async,
with_body=WithBody,
max_body=MaxBody,
stream_to=StreamTo,
buffer = <<>>},
%% if we use a pool then checkout the connection from the pool, else
%% connect the socket to the remote
%%
reconnect(Host, Port, Transport, InitialState).
%% @doc connect a socket and create a client state.
%%
maybe_connect(#client{state=closed, redirect=nil}=Client) ->
%% the socket has been closed, reconnect it.
#client{transport=Transport,
host=Host,
port=Port} = Client,
reconnect(Host, Port, Transport, Client);
maybe_connect(#client{state=closed, redirect=Redirect}=Client) ->
%% connection closed after a redirection, reinit the options and
%% reconnect it.
{Transport, Host, Port, Options} = Redirect,
Client1 = Client#client{options=Options,
redirect=nil},
reconnect(Host, Port, Transport, Client1);
maybe_connect(#client{redirect=nil}=Client) ->
{ok, check_mod_metrics(Client)};
maybe_connect(#client{redirect=Redirect}=Client) ->
%% reinit the options and reconnect the client
{Transport, Host, Port, Options} = Redirect,
reconnect(Host, Port, Transport, Client#client{options=Options,
redirect=nil}).
check_or_close(#client{socket=nil}=Client) ->
Client;
check_or_close(Client) ->
case is_pool(Client) of
false ->
close(Client);
true ->
#client{socket=Socket, socket_ref=Ref, pool_handler=Handler}=Client,
_ = Handler:checkin(Ref, Socket),
Client#client{socket=nil, state=closed}
end.
%% @doc add set sockets options in the client
set_sockopts(#client{transport=Transport, socket=Skt}, Options) ->
Transport:setopts(Skt, Options).
%% @doc close the client
%%
%%
close(#client{socket=nil}=Client) ->
Client#client{state = closed};
close(#client{transport=Transport, socket=Skt}=Client) ->
Transport:close(Skt),
Client#client{state = closed, socket=nil};
close(Ref) when is_reference(Ref) ->
hackney_manager:close_request(Ref).
%% @doc get current pool pid or name used by a client if needed
is_pool(#client{options=Opts}) ->
UseDefaultPool = use_default_pool(),
case proplists:get_value(pool, Opts) of
false ->
false;
undefined when UseDefaultPool =:= true ->
true;
undefined ->
false;
_ ->
true
end.
reconnect(Host, Port, Transport, State) ->
%% if we use a pool then checkout the connection from the pool, else
%% connect the socket to the remote
case is_pool(State) of
false ->
%% the client won't use any pool
do_connect(Host, Port, Transport, check_mod_metrics(State));
true ->
socket_from_pool(Host, Port, Transport, check_mod_metrics(State))
end.
%%
%% internal functions
%%
socket_from_pool(Host, Port, Transport, Client0) ->
PoolHandler = hackney_app:get_app_env(pool_handler, hackney_pool),
PoolName = proplists:get_value(pool, Client0#client.options, default),
Metrics = Client0#client.mod_metrics,
%% new request
{_RequestRef, Client} = hackney_manager:new_request(Client0),
case PoolHandler:checkout(Host, Port, Transport, Client) of
{ok, Ref, Skt} ->
?report_debug("reuse a connection", [{pool, PoolName}]),
metrics:update_meter(Metrics, [hackney_pool, PoolName, take_rate], 1),
metrics:increment_counter(Metrics, [hackney_pool, Host, reuse_connection]),
Client1 = Client#client{socket=Skt,
socket_ref=Ref,
pool_handler=PoolHandler,
state = connected},
hackney_manager:update_state(Client1),
{ok, Client1};
{error, no_socket, Ref} ->
?report_trace("no socket in the pool", [{pool, PoolName}]),
metrics:increment_counter(Metrics, [hackney_pool, PoolName, no_socket]),
do_connect(Host, Port, Transport, Client#client{socket_ref=Ref},
pool);
Error ->
Error
end.
do_connect(Host, Port, Transport, Client) ->
do_connect(Host, Port, Transport, Client, direct).
do_connect(Host, Port, Transport, #client{mod_metrics=Metrics,
options=Opts}=Client0, Type) ->
Begin = os:timestamp(),
{_RequestRef, Client} = case Type of
pool ->
{Client0#client.request_ref, Client0};
direct ->
hackney_manager:new_request(Client0)
end,
ConnectOpts0 = proplists:get_value(connect_options, Opts, []),
ConnectTimeout = proplists:get_value(connect_timeout, Opts, 8000),
%% handle ipv6
ConnectOpts1 = case lists:member(inet, ConnectOpts0) orelse
lists:member(inet6, ConnectOpts0) of
true ->
ConnectOpts0;
false ->
case hackney_util:is_ipv6(Host) of
true ->
[inet6 | ConnectOpts0];
false ->
ConnectOpts0
end
end,
ConnectOpts = case Transport of
hackney_ssl ->
ConnectOpts1 ++ ssl_opts(Host, Opts);
_ ->
ConnectOpts1
end,
case Transport:connect(Host, Port, ConnectOpts, ConnectTimeout) of
{ok, Skt} ->
?report_trace("new connection", []),
ConnectTime = timer:now_diff(os:timestamp(), Begin)/1000,
metrics:update_histogram(Metrics, [hackney, Host, connect_time], ConnectTime),
metrics:increment_counter(Metrics, [hackney_pool, Host, new_connection]),
Client1 = Client#client{socket=Skt,
state = connected},
hackney_manager:update_state(Client1),
{ok, Client1};
{error, timeout} ->
?report_trace("connect timeout", []),
metrics:increment_counter(Metrics, [hackney, Host, connect_timeout]),
hackney_manager:cancel_request(Client),
{error, connect_timeout};
Error ->
?report_trace("connect error", []),
metrics:increment_counter(Metrics, [hackney, Host, connect_error]),
hackney_manager:cancel_request(Client),
Error
end.
use_default_pool() ->
case application:get_env(hackney, use_default_pool) of
{ok, Val} ->
Val;
_ ->
true
end.
check_mod_metrics(#client{mod_metrics=Mod}=State)
when Mod /= nil, Mod /= undefined ->
State;
check_mod_metrics(State) ->
State#client{mod_metrics=metrics:init(hackney_util:mod_metrics())}.
ssl_opts(Host, Options) ->
case proplists:get_value(ssl_options, Options) of
undefined ->
Insecure = proplists:get_value(insecure, Options),
UseSecureSsl = check_ssl_version(),
CACerts = certifi:cacerts(),
case {Insecure, UseSecureSsl} of
{true, _} ->
[{verify, verify_none}];
{_, true} ->
VerifyFun = {fun ssl_verify_hostname:verify_fun/3,
[{check_hostname, Host}]},
[{verify, verify_peer},
{depth, 99},
{cacerts, CACerts},
{partial_chain, fun partial_chain/1},
{verify_fun, VerifyFun}];
{_, _} ->
[{cacerts, CACerts},
{verify, verify_peer}, {depth, 2}]
end;
SSLOpts ->
SSLOpts
end.
code from rebar3 undert BSD license
partial_chain(Certs) ->
Certs1 = lists:reverse([{Cert, public_key:pkix_decode_cert(Cert, otp)} ||
Cert <- Certs]),
CACerts = certifi:cacerts(),
CACerts1 = [public_key:pkix_decode_cert(Cert, otp) || Cert <- CACerts],
case find(fun({_, Cert}) ->
check_cert(CACerts1, Cert)
end, Certs1) of
{ok, Trusted} ->
{trusted_ca, element(1, Trusted)};
_ ->
unknown_ca
end.
extract_public_key_info(Cert) ->
((Cert#'OTPCertificate'.tbsCertificate)#'OTPTBSCertificate'.subjectPublicKeyInfo).
check_cert(CACerts, Cert) ->
lists:any(fun(CACert) ->
extract_public_key_info(CACert) == extract_public_key_info(Cert)
end, CACerts).
check_ssl_version() ->
case application:get_key(ssl, vsn) of
{ok, Vsn} ->
parse_vsn(Vsn) >= {5, 3, 6};
_ ->
false
end.
parse_vsn(Vsn) ->
version_pad(string:tokens(Vsn, ".")).
version_pad([Major]) ->
{list_to_integer(Major), 0, 0};
version_pad([Major, Minor]) ->
{list_to_integer(Major), list_to_integer(Minor), 0};
version_pad([Major, Minor, Patch]) ->
{list_to_integer(Major), list_to_integer(Minor), list_to_integer(Patch)};
version_pad([Major, Minor, Patch | _]) ->
{list_to_integer(Major), list_to_integer(Minor), list_to_integer(Patch)}.
-spec find(fun(), list()) -> {ok, term()} | error.
find(Fun, [Head|Tail]) when is_function(Fun) ->
case Fun(Head) of
true ->
{ok, Head};
false ->
find(Fun, Tail)
end;
find(_Fun, []) ->
error.
| null | https://raw.githubusercontent.com/somnusand/Poker/4934582a4a37f28c53108a6f6e09b55d21925ffa/server/deps/hackney/src/hackney_connect.erl | erlang | -*- erlang -*-
See the NOTICE for more information.
@doc create a connection and return a client state
default timeout
get mod metrics
initial state
if we use a pool then checkout the connection from the pool, else
connect the socket to the remote
@doc connect a socket and create a client state.
the socket has been closed, reconnect it.
connection closed after a redirection, reinit the options and
reconnect it.
reinit the options and reconnect the client
@doc add set sockets options in the client
@doc close the client
@doc get current pool pid or name used by a client if needed
if we use a pool then checkout the connection from the pool, else
connect the socket to the remote
the client won't use any pool
internal functions
new request
handle ipv6 | This file is part of hackney released under the Apache 2 license .
-module(hackney_connect).
-export([connect/3, connect/4, connect/5,
create_connection/4, create_connection/5,
maybe_connect/1,
reconnect/4,
set_sockopts/2,
ssl_opts/2,
check_or_close/1,
close/1,
is_pool/1]).
-export([partial_chain/1]).
-include("hackney.hrl").
-include_lib("hackney_internal.hrl").
-include_lib("public_key/include/OTP-PUB-KEY.hrl").
connect(Transport, Host, Port) ->
connect(Transport, Host, Port, []).
connect(Transport, Host, Port, Options) ->
connect(Transport, Host, Port, Options, false).
connect(Transport, Host, Port, Options, Dynamic) when is_binary(Host) ->
connect(Transport, binary_to_list(Host), Port, Options, Dynamic);
connect(Transport, Host, Port, Options, Dynamic) ->
?report_debug("connect", [{transport, Transport},
{host, Host},
{port, Port},
{dynamic, Dynamic}]),
case create_connection(Transport, idna:utf8_to_ascii(Host), Port,
Options, Dynamic) of
{ok, #client{request_ref=Ref}} ->
{ok, Ref};
Error ->
Error
end.
create_connection(Transport, Host, Port, Options) ->
create_connection(Transport, Host, Port, Options, true).
create_connection(Transport, Host, Port, Options, Dynamic)
when is_list(Options) ->
Netloc = case {Transport, Port} of
{hackney_tcp, 80} -> list_to_binary(Host);
{hackney_ssl, 443} -> list_to_binary(Host);
_ ->
iolist_to_binary([Host, ":", integer_to_list(Port)])
end,
Timeout = proplists:get_value(recv_timeout, Options, ?RECV_TIMEOUT),
FollowRedirect = proplists:get_value(follow_redirect, Options, false),
MaxRedirect = proplists:get_value(max_redirect, Options, 5),
ForceRedirect = proplists:get_value(force_redirect, Options, false),
Async = proplists:get_value(async, Options, false),
StreamTo = proplists:get_value(stream_to, Options, false),
WithBody = proplists:get_value(with_body, Options, false),
MaxBody = proplists:get_value(max_body, Options),
Engine = metrics:init(hackney_util:mod_metrics()),
InitialState = #client{mod_metrics=Engine,
transport=Transport,
host=Host,
port=Port,
netloc=Netloc,
options=Options,
dynamic=Dynamic,
recv_timeout=Timeout,
follow_redirect=FollowRedirect,
max_redirect=MaxRedirect,
retries=MaxRedirect,
force_redirect=ForceRedirect,
async=Async,
with_body=WithBody,
max_body=MaxBody,
stream_to=StreamTo,
buffer = <<>>},
reconnect(Host, Port, Transport, InitialState).
maybe_connect(#client{state=closed, redirect=nil}=Client) ->
#client{transport=Transport,
host=Host,
port=Port} = Client,
reconnect(Host, Port, Transport, Client);
maybe_connect(#client{state=closed, redirect=Redirect}=Client) ->
{Transport, Host, Port, Options} = Redirect,
Client1 = Client#client{options=Options,
redirect=nil},
reconnect(Host, Port, Transport, Client1);
maybe_connect(#client{redirect=nil}=Client) ->
{ok, check_mod_metrics(Client)};
maybe_connect(#client{redirect=Redirect}=Client) ->
{Transport, Host, Port, Options} = Redirect,
reconnect(Host, Port, Transport, Client#client{options=Options,
redirect=nil}).
check_or_close(#client{socket=nil}=Client) ->
Client;
check_or_close(Client) ->
case is_pool(Client) of
false ->
close(Client);
true ->
#client{socket=Socket, socket_ref=Ref, pool_handler=Handler}=Client,
_ = Handler:checkin(Ref, Socket),
Client#client{socket=nil, state=closed}
end.
set_sockopts(#client{transport=Transport, socket=Skt}, Options) ->
Transport:setopts(Skt, Options).
close(#client{socket=nil}=Client) ->
Client#client{state = closed};
close(#client{transport=Transport, socket=Skt}=Client) ->
Transport:close(Skt),
Client#client{state = closed, socket=nil};
close(Ref) when is_reference(Ref) ->
hackney_manager:close_request(Ref).
is_pool(#client{options=Opts}) ->
UseDefaultPool = use_default_pool(),
case proplists:get_value(pool, Opts) of
false ->
false;
undefined when UseDefaultPool =:= true ->
true;
undefined ->
false;
_ ->
true
end.
reconnect(Host, Port, Transport, State) ->
case is_pool(State) of
false ->
do_connect(Host, Port, Transport, check_mod_metrics(State));
true ->
socket_from_pool(Host, Port, Transport, check_mod_metrics(State))
end.
socket_from_pool(Host, Port, Transport, Client0) ->
PoolHandler = hackney_app:get_app_env(pool_handler, hackney_pool),
PoolName = proplists:get_value(pool, Client0#client.options, default),
Metrics = Client0#client.mod_metrics,
{_RequestRef, Client} = hackney_manager:new_request(Client0),
case PoolHandler:checkout(Host, Port, Transport, Client) of
{ok, Ref, Skt} ->
?report_debug("reuse a connection", [{pool, PoolName}]),
metrics:update_meter(Metrics, [hackney_pool, PoolName, take_rate], 1),
metrics:increment_counter(Metrics, [hackney_pool, Host, reuse_connection]),
Client1 = Client#client{socket=Skt,
socket_ref=Ref,
pool_handler=PoolHandler,
state = connected},
hackney_manager:update_state(Client1),
{ok, Client1};
{error, no_socket, Ref} ->
?report_trace("no socket in the pool", [{pool, PoolName}]),
metrics:increment_counter(Metrics, [hackney_pool, PoolName, no_socket]),
do_connect(Host, Port, Transport, Client#client{socket_ref=Ref},
pool);
Error ->
Error
end.
do_connect(Host, Port, Transport, Client) ->
do_connect(Host, Port, Transport, Client, direct).
do_connect(Host, Port, Transport, #client{mod_metrics=Metrics,
options=Opts}=Client0, Type) ->
Begin = os:timestamp(),
{_RequestRef, Client} = case Type of
pool ->
{Client0#client.request_ref, Client0};
direct ->
hackney_manager:new_request(Client0)
end,
ConnectOpts0 = proplists:get_value(connect_options, Opts, []),
ConnectTimeout = proplists:get_value(connect_timeout, Opts, 8000),
ConnectOpts1 = case lists:member(inet, ConnectOpts0) orelse
lists:member(inet6, ConnectOpts0) of
true ->
ConnectOpts0;
false ->
case hackney_util:is_ipv6(Host) of
true ->
[inet6 | ConnectOpts0];
false ->
ConnectOpts0
end
end,
ConnectOpts = case Transport of
hackney_ssl ->
ConnectOpts1 ++ ssl_opts(Host, Opts);
_ ->
ConnectOpts1
end,
case Transport:connect(Host, Port, ConnectOpts, ConnectTimeout) of
{ok, Skt} ->
?report_trace("new connection", []),
ConnectTime = timer:now_diff(os:timestamp(), Begin)/1000,
metrics:update_histogram(Metrics, [hackney, Host, connect_time], ConnectTime),
metrics:increment_counter(Metrics, [hackney_pool, Host, new_connection]),
Client1 = Client#client{socket=Skt,
state = connected},
hackney_manager:update_state(Client1),
{ok, Client1};
{error, timeout} ->
?report_trace("connect timeout", []),
metrics:increment_counter(Metrics, [hackney, Host, connect_timeout]),
hackney_manager:cancel_request(Client),
{error, connect_timeout};
Error ->
?report_trace("connect error", []),
metrics:increment_counter(Metrics, [hackney, Host, connect_error]),
hackney_manager:cancel_request(Client),
Error
end.
use_default_pool() ->
case application:get_env(hackney, use_default_pool) of
{ok, Val} ->
Val;
_ ->
true
end.
check_mod_metrics(#client{mod_metrics=Mod}=State)
when Mod /= nil, Mod /= undefined ->
State;
check_mod_metrics(State) ->
State#client{mod_metrics=metrics:init(hackney_util:mod_metrics())}.
ssl_opts(Host, Options) ->
case proplists:get_value(ssl_options, Options) of
undefined ->
Insecure = proplists:get_value(insecure, Options),
UseSecureSsl = check_ssl_version(),
CACerts = certifi:cacerts(),
case {Insecure, UseSecureSsl} of
{true, _} ->
[{verify, verify_none}];
{_, true} ->
VerifyFun = {fun ssl_verify_hostname:verify_fun/3,
[{check_hostname, Host}]},
[{verify, verify_peer},
{depth, 99},
{cacerts, CACerts},
{partial_chain, fun partial_chain/1},
{verify_fun, VerifyFun}];
{_, _} ->
[{cacerts, CACerts},
{verify, verify_peer}, {depth, 2}]
end;
SSLOpts ->
SSLOpts
end.
code from rebar3 undert BSD license
partial_chain(Certs) ->
Certs1 = lists:reverse([{Cert, public_key:pkix_decode_cert(Cert, otp)} ||
Cert <- Certs]),
CACerts = certifi:cacerts(),
CACerts1 = [public_key:pkix_decode_cert(Cert, otp) || Cert <- CACerts],
case find(fun({_, Cert}) ->
check_cert(CACerts1, Cert)
end, Certs1) of
{ok, Trusted} ->
{trusted_ca, element(1, Trusted)};
_ ->
unknown_ca
end.
extract_public_key_info(Cert) ->
((Cert#'OTPCertificate'.tbsCertificate)#'OTPTBSCertificate'.subjectPublicKeyInfo).
check_cert(CACerts, Cert) ->
lists:any(fun(CACert) ->
extract_public_key_info(CACert) == extract_public_key_info(Cert)
end, CACerts).
check_ssl_version() ->
case application:get_key(ssl, vsn) of
{ok, Vsn} ->
parse_vsn(Vsn) >= {5, 3, 6};
_ ->
false
end.
parse_vsn(Vsn) ->
version_pad(string:tokens(Vsn, ".")).
version_pad([Major]) ->
{list_to_integer(Major), 0, 0};
version_pad([Major, Minor]) ->
{list_to_integer(Major), list_to_integer(Minor), 0};
version_pad([Major, Minor, Patch]) ->
{list_to_integer(Major), list_to_integer(Minor), list_to_integer(Patch)};
version_pad([Major, Minor, Patch | _]) ->
{list_to_integer(Major), list_to_integer(Minor), list_to_integer(Patch)}.
-spec find(fun(), list()) -> {ok, term()} | error.
find(Fun, [Head|Tail]) when is_function(Fun) ->
case Fun(Head) of
true ->
{ok, Head};
false ->
find(Fun, Tail)
end;
find(_Fun, []) ->
error.
|
422d9409d860d7254579a82238f3edb89f5b89e592549665d991e9007837c086 | ormf/cm | dk1-answers.lisp | (in-package :cm)
;;; Etude 1: Write a counterpoint receiver that plays back a
;;; transposed version of whatever the performer plays on the
;;; disklavier at a specified time interval in the future. (Risset)
( load " # P"/private / Network / Servers / camilx2.music.uiuc.edu / Users / Faculty / hkt/404b / " )
(setq *ms* (midishare-open))
(ms:output (ms:new typeNote :pitch 60 :vel 64 :dur 1000 :port *dk*
:chan 0)
*ms*)
(ms:output (ms:new typeNote :pitch 60 :vel 64 :dur 1000 :port *dk*
:chan 0)
*ms*
2000)
(defun etude1 (ev)
(ms:pitch ev (+ (ms:pitch ev) 12))
(ms:output ev *ms*))
(set-receiver! #'etude1 *ms*)
(remove-receiver! *ms*)
(defparameter *transp* 12)
(defparameter *future* 1000)
(defun etude1 (ev)
(ms:pitch ev (+ (ms:pitch ev) *transp*))
(ms:output ev *ms* *future*))
(set-receiver! #'etude1 *ms*)
(setq *transp* 13)
(setq *future* 100)
(remove-receiver! *ms*)
;;; Etude 2: Change the receiver to play a "warped" (rescaled) version
;;; of the pianists input (Risset)
(defun etude2 (ev)
(ms:pitch ev (int (rescale (ms:pitch ev)
60 71 72 94)))
(ms:output ev *ms* *future*))
(setq *future* 500)
(set-receiver! #'etude2 *ms*)
(remove-receiver! *ms*)
;;; Etude 3: Change the receiver to treat the amplitde of the incoming
;;; notes as a scaler on the time delay: the louder the notes the
;;; closer the repition interval; the softer the notes the farter the
;;; repetition interval
(defun etude3 (ev)
(setq *future* (int (rescale (ms:vel ev)
0 127
2000 00)))
(ms:output ev *ms* *future*))
(set-receiver! #'etude3 *ms*)
(remove-receiver! *ms*)
;;; Etude 4: Use the rescale function to also "invert" the melody
;;; played by the performer
;;; Etude 5: Write an inverting receiver that "mirrors" whatever the
performed playse around some specfiied ( Risset )
(setq *ms* (midishare-open))
(defparameter *mk* 60) ; kenym around which i will invert
(defun mirror (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
(t
(ms:midiFreeEv ev)))
)
(set-receiver! #'mirror *ms*)
(remove-receiver! *ms*)
(defparameter *tk* 108)
(defparameter *bk* 21)
(defun mirror2 (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
((= (ms:pitch ev) *mk*)
(ms:pitch ev *tk*)
(let ((newev (ms:midiCopyEv ev)))
(ms:pitch newev *bk*)
(ms:output newev *ms* )
(ms:output ev *ms* ) ))
(t
(ms:midiFreeEv ev)))
)
(set-receiver! #'mirror2 *ms*)
(remove-receiver! *ms*)
(defun dk-mirror (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
((= (ms:pitch ev) *mk*)
(ms:pitch ev *tk*)
(let ((newev (ms:midiCopyEv ev)))
(ms:pitch newev *bk*)
(ms:output newev *ms* )
(ms:output ev *ms* ) ))
(t
(ms:midiFreeEv ev))))
(defun mirror3 (ev)
(cond ((and (= (ms:port ev) *dk*)
(keyEv? ev))
(dk-mirror ev))
((= (ms:port ev) *jv*)
(setq *mk* (ms:pitch ev))
(ms:midiFreeEv ev)
)))
(set-receiver! #'mirror3 *ms*)
(remove-receiver! *ms*)
Etude 6 : Change the receiver to also accept input from the JV . JV
keydowns will set the inversion point for the processing .
Working with DK Pedal information . Pedal data is encoded as MIDI
;;; Controller messages. For info about MIDI Controllers see:
;;; /~jglatt/tech/midispec/ctllist.htm
right pedal : 0 to 127 ( if DK in half - pedal mode )
middle pedal : 0 or 127
left pedal : 0 TO 127
;right (down and up)
# < MidiEv CtrlChange [ 4/0 3728950ms ] 64 127 >
# < MidiEv CtrlChange [ 4/0 3729250ms ] 64 0 >
;middle
# < MidiEv CtrlChange [ 4/0 3733624ms ] 66 127 >
# < MidiEv CtrlChange [ 4/0 3733932ms ] 66 0 >
;left
# < MidiEv CtrlChange [ 4/0 3736466ms ] 67 127 >
# < MidiEv CtrlChange [ 4/0 3736753ms ] 67 0 > ?
;;; Use the typeControl MidiEV for control information
(ms:output
(ms:new typeCtrlChange :controller *rp* :change 0
:port *dk* :chan 2)
*ms*)
Etude : 7 : Write a receive hook that prints out only Pedal information
;;; sent from the disklavier.
(defun prinev (ev)
(ms:midiPrintEv ev)
(ms:midiFreeEv ev))
(set-receiver! #'prinev *ms*)
(remove-receiver! *ms*)
Disklavier MIDI Input Settings
There are two important MIDI settings on the Disklavier that
;;; affect real time performance:
1 . MIDI IN needs to be in HP ( Half Pedal ) mode to send / receive
continuous Pedal information . Otherwise sustain values 0 - 63 = are O
( off ) and 64 - 127 are 1 ( on )
2 . MIDI IN is either in REALTIME mode or DELAY mode ( 500ms ) .
DK must be in " half - pedal mode " ( HP ) to receive continuous
;;; controller information for left and right pedals, otherwise values
are " binary " , ie 0 OR 127 . When the Disklavier is in Half pedal
mode the pedal information is sent / received on channel 2 .
When MIDI IN is in REALTIME mode , then the delay is
;;; (bascially) the same as that discussed in the Risset article. When
DK is in DELAY mode then an outomatic 500ms delay is added . This
kind of " built in " delay is called LATENCY and is a important
;;; basic concept in realtime audio/midi work. Every device and/or
;;; software has latency, it it only a question of degree. The smaller
the latency the more reponsize the " realtime " system is . 500ms
latency is HUGE , more typical latency values are 1 - 50ms .
To put the DK in either HP ( half pedal ) or REALTIME / modes :
1 [ Press / EDIT ] to enter Editing screen .
2 [ Press ENTER ]
3 [ Press ENTER ] to select MIDI IN . The page shows :
MIDI IN CH = HP [ Use dial to select 1 - 16 or HP ]
;;; MIDI IN=REALTIME [Press -> to select, use dial to switch
between REALTIME / modes .
4 [ Press / EDIT ] to quit
;;;
For more information see Chapter 15 of Manual ( pg 100 )
;;; Etude 8: Write a function called dkped that will create any of the
three pedal control values based on a symbolx pedal value passed
as the 1st argument . The second argument will be the pedal value
( 0 - 127 ) . HINT : Use CASE or COND to distinguish the three pedals
The symbokc names to allow for each pedal are :
right pedal : 64 : rp : right : damper : sustain
middle pedal : 66 : mp : middle : sostenuto
middle pedal : 68 : lp : left : una - corde : soft
(defun dkped (ped val)
)
| null | https://raw.githubusercontent.com/ormf/cm/26843eec009bd6c214992a8e67c49fffa16d9530/doc/404B-SoundSynth-AlgoComp/www-camil.music.uiuc.edu_16080/classes/404B/lisp/dk1-answers.lisp | lisp | Etude 1: Write a counterpoint receiver that plays back a
transposed version of whatever the performer plays on the
disklavier at a specified time interval in the future. (Risset)
Etude 2: Change the receiver to play a "warped" (rescaled) version
of the pianists input (Risset)
Etude 3: Change the receiver to treat the amplitde of the incoming
notes as a scaler on the time delay: the louder the notes the
closer the repition interval; the softer the notes the farter the
repetition interval
Etude 4: Use the rescale function to also "invert" the melody
played by the performer
Etude 5: Write an inverting receiver that "mirrors" whatever the
kenym around which i will invert
Controller messages. For info about MIDI Controllers see:
/~jglatt/tech/midispec/ctllist.htm
right (down and up)
middle
left
Use the typeControl MidiEV for control information
sent from the disklavier.
affect real time performance:
controller information for left and right pedals, otherwise values
(bascially) the same as that discussed in the Risset article. When
basic concept in realtime audio/midi work. Every device and/or
software has latency, it it only a question of degree. The smaller
MIDI IN=REALTIME [Press -> to select, use dial to switch
Etude 8: Write a function called dkped that will create any of the | (in-package :cm)
( load " # P"/private / Network / Servers / camilx2.music.uiuc.edu / Users / Faculty / hkt/404b / " )
(setq *ms* (midishare-open))
(ms:output (ms:new typeNote :pitch 60 :vel 64 :dur 1000 :port *dk*
:chan 0)
*ms*)
(ms:output (ms:new typeNote :pitch 60 :vel 64 :dur 1000 :port *dk*
:chan 0)
*ms*
2000)
(defun etude1 (ev)
(ms:pitch ev (+ (ms:pitch ev) 12))
(ms:output ev *ms*))
(set-receiver! #'etude1 *ms*)
(remove-receiver! *ms*)
(defparameter *transp* 12)
(defparameter *future* 1000)
(defun etude1 (ev)
(ms:pitch ev (+ (ms:pitch ev) *transp*))
(ms:output ev *ms* *future*))
(set-receiver! #'etude1 *ms*)
(setq *transp* 13)
(setq *future* 100)
(remove-receiver! *ms*)
(defun etude2 (ev)
(ms:pitch ev (int (rescale (ms:pitch ev)
60 71 72 94)))
(ms:output ev *ms* *future*))
(setq *future* 500)
(set-receiver! #'etude2 *ms*)
(remove-receiver! *ms*)
(defun etude3 (ev)
(setq *future* (int (rescale (ms:vel ev)
0 127
2000 00)))
(ms:output ev *ms* *future*))
(set-receiver! #'etude3 *ms*)
(remove-receiver! *ms*)
performed playse around some specfiied ( Risset )
(setq *ms* (midishare-open))
(defun mirror (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
(t
(ms:midiFreeEv ev)))
)
(set-receiver! #'mirror *ms*)
(remove-receiver! *ms*)
(defparameter *tk* 108)
(defparameter *bk* 21)
(defun mirror2 (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
((= (ms:pitch ev) *mk*)
(ms:pitch ev *tk*)
(let ((newev (ms:midiCopyEv ev)))
(ms:pitch newev *bk*)
(ms:output newev *ms* )
(ms:output ev *ms* ) ))
(t
(ms:midiFreeEv ev)))
)
(set-receiver! #'mirror2 *ms*)
(remove-receiver! *ms*)
(defun dk-mirror (ev)
(cond ((> (ms:pitch ev) *mk*)
(let* (
(delta (- (ms:pitch ev) *mk*))
(newkeynum (- *mk* delta))
)
update ev with new keynum
(ms:pitch ev newkeynum)
(ms:output ev *ms*)))
((= (ms:pitch ev) *mk*)
(ms:pitch ev *tk*)
(let ((newev (ms:midiCopyEv ev)))
(ms:pitch newev *bk*)
(ms:output newev *ms* )
(ms:output ev *ms* ) ))
(t
(ms:midiFreeEv ev))))
(defun mirror3 (ev)
(cond ((and (= (ms:port ev) *dk*)
(keyEv? ev))
(dk-mirror ev))
((= (ms:port ev) *jv*)
(setq *mk* (ms:pitch ev))
(ms:midiFreeEv ev)
)))
(set-receiver! #'mirror3 *ms*)
(remove-receiver! *ms*)
Etude 6 : Change the receiver to also accept input from the JV . JV
keydowns will set the inversion point for the processing .
Working with DK Pedal information . Pedal data is encoded as MIDI
right pedal : 0 to 127 ( if DK in half - pedal mode )
middle pedal : 0 or 127
left pedal : 0 TO 127
# < MidiEv CtrlChange [ 4/0 3728950ms ] 64 127 >
# < MidiEv CtrlChange [ 4/0 3729250ms ] 64 0 >
# < MidiEv CtrlChange [ 4/0 3733624ms ] 66 127 >
# < MidiEv CtrlChange [ 4/0 3733932ms ] 66 0 >
# < MidiEv CtrlChange [ 4/0 3736466ms ] 67 127 >
# < MidiEv CtrlChange [ 4/0 3736753ms ] 67 0 > ?
(ms:output
(ms:new typeCtrlChange :controller *rp* :change 0
:port *dk* :chan 2)
*ms*)
Etude : 7 : Write a receive hook that prints out only Pedal information
(defun prinev (ev)
(ms:midiPrintEv ev)
(ms:midiFreeEv ev))
(set-receiver! #'prinev *ms*)
(remove-receiver! *ms*)
Disklavier MIDI Input Settings
There are two important MIDI settings on the Disklavier that
1 . MIDI IN needs to be in HP ( Half Pedal ) mode to send / receive
continuous Pedal information . Otherwise sustain values 0 - 63 = are O
( off ) and 64 - 127 are 1 ( on )
2 . MIDI IN is either in REALTIME mode or DELAY mode ( 500ms ) .
DK must be in " half - pedal mode " ( HP ) to receive continuous
are " binary " , ie 0 OR 127 . When the Disklavier is in Half pedal
mode the pedal information is sent / received on channel 2 .
When MIDI IN is in REALTIME mode , then the delay is
DK is in DELAY mode then an outomatic 500ms delay is added . This
kind of " built in " delay is called LATENCY and is a important
the latency the more reponsize the " realtime " system is . 500ms
latency is HUGE , more typical latency values are 1 - 50ms .
To put the DK in either HP ( half pedal ) or REALTIME / modes :
1 [ Press / EDIT ] to enter Editing screen .
2 [ Press ENTER ]
3 [ Press ENTER ] to select MIDI IN . The page shows :
MIDI IN CH = HP [ Use dial to select 1 - 16 or HP ]
between REALTIME / modes .
4 [ Press / EDIT ] to quit
For more information see Chapter 15 of Manual ( pg 100 )
three pedal control values based on a symbolx pedal value passed
as the 1st argument . The second argument will be the pedal value
( 0 - 127 ) . HINT : Use CASE or COND to distinguish the three pedals
The symbokc names to allow for each pedal are :
right pedal : 64 : rp : right : damper : sustain
middle pedal : 66 : mp : middle : sostenuto
middle pedal : 68 : lp : left : una - corde : soft
(defun dkped (ped val)
)
|
a9c24b3c1ce5ea1ae0aa7b7e911e73a38afb3a00a690157a1e9c0a336dc243e0 | aeternity/aesophia | aeso_scan_lib.erl | %%% -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
%%%-------------------------------------------------------------------
( C ) 2017 , Aeternity Anstalt
%%% @doc A customisable lexer.
%%% @end
%%%-------------------------------------------------------------------
-module(aeso_scan_lib).
-export([compile/1, string/3,
token/1, token/2, symbol/0, skip/0,
override/2, push/2, pop/1]).
-export_type([lexer/0, token_spec/0, token_action/0, token/0, pos/0, regex/0]).
%% -- Exported types --
-type regex() :: iodata() | unicode:charlist().
-type pos() :: {integer(), integer()}.
-type lex_state() :: atom().
-type token() :: {atom(), pos(), term()} | {atom(), pos()}.
-type token_spec() :: {regex(), token_action()}.
-opaque token_action() :: fun((string(), pos()) -> {tok_result(), state_change()}).
-opaque lexer() :: [{lex_state(),
fun((string(), pos()) -> {ok, tok_result(), string(), pos()}
| end_of_file | error)}].
%% -- Internal types --
-type tok_result() :: {token, token()} | skip.
-type state_change() :: none | pop | {push, lex_state()}.
%% @doc Compile a lexer specification. Takes the regexps for each state and
%% combines them into a single big regexp that is then compiled with re:compile/1.
Note : contrary to lexer generators like , we do n't have longest match
%% semantics (since this isn't supported by re). Use override/2 instead.
-spec compile([{lex_state(), [token_spec()]}]) -> lexer().
compile(TokenSpecs) ->
[{S, compile_spec(Spec)} || {S, Spec} <- TokenSpecs].
compile_spec(TokenSpecs) ->
WithIxs = lists:zip(lists:seq(1, length(TokenSpecs)), TokenSpecs),
{ok, Regex} = re:compile(["^(", name(0), string:join([ ["(", name(I), R, ")"] || {I, {R, _}} <- WithIxs ], "|"),")"]),
Actions = [ Fun || {_, Fun} <- TokenSpecs ],
fun ("", _Pos) -> end_of_file;
(S, Pos) ->
case re:run(S, Regex, [{capture, all_names}]) of
{match, [{0, N} | Capture]} ->
Index = 1 + length(lists:takewhile(fun({P, _}) -> P == -1 end, Capture)),
Action = lists:nth(Index, Actions),
{TokS, Rest} = lists:split(N, S),
Tok = Action(TokS, Pos),
{ok, Tok, Rest, next_pos(TokS, Pos)};
nomatch ->
error
end
end.
%% @doc Produce a token with the given tag and the matched string as the
%% value.
-spec token(atom()) -> token_action().
token(Tag) ->
token(Tag, fun(X) -> X end).
%% @doc Produce a token with the given tag and the value computed from the
%% matched string using the function.
-spec token(atom(), fun((string()) -> term())) -> token_action().
token(Tag, Fun) ->
fun(S, P) -> {{token, {Tag, P, Fun(S)}}, none} end.
%% @doc Produce a token with the matched string (converted to an atom) as the
%% tag and no value.
-spec symbol() -> token_action().
symbol() ->
fun(S, P) -> {{token, {list_to_atom(S), P}}, none} end.
%% @doc Skip the matched string, producing no token.
-spec skip() -> token_action().
skip() ->
fun(_, _) -> {skip, none} end.
%% @doc Enter the given state and perform the given action. The argument action
%% should not change the state.
-spec push(lex_state(), token_action()) -> token_action().
push(State, Action) ->
fun(S, P) -> {Res, _} = Action(S, P), {Res, {push, State}} end.
%% @doc Exit from the current state and perform the given action. The argument
%% action should not change the state.
-spec pop(token_action()) -> token_action().
pop(Action) ->
fun(S, P) -> {Res, _} = Action(S, P), {Res, pop} end.
@doc Match using the first spec , but if the second spec also matches use
that one instead . Use this for overlapping tokens ( like identifiers and
%% keywords), since matching does not have longest-match semantics.
-spec override(token_spec(), token_spec()) -> token_spec().
override({Re1, Action1}, {Re2, Action2}) ->
{ok, Compiled} = re:compile(["^(", Re2, ")$"]),
{Re1, fun(S, P) ->
case re:run(S, Compiled, [{capture, none}]) of
match -> Action2(S, P);
nomatch -> Action1(S, P)
end end}.
%% @doc Run a lexer. Takes the starting state and the string to lex.
-spec string(lexer(), lex_state(), string()) -> {ok, [token()]} | {error, term()}.
string(Lexer, State, String) -> string(Lexer, [State], String, {1, 1}).
string(Lexer, Stack, String, Pos) ->
Lines = string:split(String, "\n", all),
string(Lexer, Stack, Lines, Pos, []).
string(_Lexers, [], [Line | _Rest], Pos, _Acc) ->
{error, {{Line,Pos}, scan_error_no_state}};
string(_Lexers, _Stack, [], _Pos, Acc) ->
{ok, lists:reverse(Acc)};
string(Lexers, [State | Stack], [Line | Lines], Pos, Acc) ->
Lexer = proplists:get_value(State, Lexers, State),
case Lexer(Line, Pos) of
{ok, {Res, StateChange}, Line1, Pos1} ->
Acc1 = case Res of
{token, Tok} -> [Tok | Acc];
skip -> Acc
end,
Stack1 = case StateChange of
none -> [State | Stack];
pop -> Stack;
{push, State1} -> [State1, State | Stack]
end,
string(Lexers, Stack1, [Line1 | Lines], Pos1, Acc1);
end_of_file -> string(Lexers, [State | Stack], Lines, next_pos("\n", Pos), Acc);
error -> {error, {{Line,Pos}, scan_error}}
end.
%% -- Internal functions -----------------------------------------------------
name(I) ->
io_lib:format("?<A~3.10.0b>", [I]).
-define(TAB_SIZE, 8).
next_pos([], P) -> P;
next_pos([$\n | S], {L, _}) -> next_pos(S, {L + 1, 1});
next_pos([$\t | S], {L, C}) -> next_pos(S, {L, (C + ?TAB_SIZE - 1) div ?TAB_SIZE * ?TAB_SIZE + 1});
next_pos([_ | S], {L, C}) -> next_pos(S, {L, C + 1}).
| null | https://raw.githubusercontent.com/aeternity/aesophia/47878308619ea52197f9a35b2b924da704cbc544/src/aeso_scan_lib.erl | erlang | -*- erlang-indent-level:4; indent-tabs-mode: nil -*-
-------------------------------------------------------------------
@doc A customisable lexer.
@end
-------------------------------------------------------------------
-- Exported types --
-- Internal types --
@doc Compile a lexer specification. Takes the regexps for each state and
combines them into a single big regexp that is then compiled with re:compile/1.
semantics (since this isn't supported by re). Use override/2 instead.
@doc Produce a token with the given tag and the matched string as the
value.
@doc Produce a token with the given tag and the value computed from the
matched string using the function.
@doc Produce a token with the matched string (converted to an atom) as the
tag and no value.
@doc Skip the matched string, producing no token.
@doc Enter the given state and perform the given action. The argument action
should not change the state.
@doc Exit from the current state and perform the given action. The argument
action should not change the state.
keywords), since matching does not have longest-match semantics.
@doc Run a lexer. Takes the starting state and the string to lex.
-- Internal functions ----------------------------------------------------- | ( C ) 2017 , Aeternity Anstalt
-module(aeso_scan_lib).
-export([compile/1, string/3,
token/1, token/2, symbol/0, skip/0,
override/2, push/2, pop/1]).
-export_type([lexer/0, token_spec/0, token_action/0, token/0, pos/0, regex/0]).
-type regex() :: iodata() | unicode:charlist().
-type pos() :: {integer(), integer()}.
-type lex_state() :: atom().
-type token() :: {atom(), pos(), term()} | {atom(), pos()}.
-type token_spec() :: {regex(), token_action()}.
-opaque token_action() :: fun((string(), pos()) -> {tok_result(), state_change()}).
-opaque lexer() :: [{lex_state(),
fun((string(), pos()) -> {ok, tok_result(), string(), pos()}
| end_of_file | error)}].
-type tok_result() :: {token, token()} | skip.
-type state_change() :: none | pop | {push, lex_state()}.
Note : contrary to lexer generators like , we do n't have longest match
-spec compile([{lex_state(), [token_spec()]}]) -> lexer().
compile(TokenSpecs) ->
[{S, compile_spec(Spec)} || {S, Spec} <- TokenSpecs].
compile_spec(TokenSpecs) ->
WithIxs = lists:zip(lists:seq(1, length(TokenSpecs)), TokenSpecs),
{ok, Regex} = re:compile(["^(", name(0), string:join([ ["(", name(I), R, ")"] || {I, {R, _}} <- WithIxs ], "|"),")"]),
Actions = [ Fun || {_, Fun} <- TokenSpecs ],
fun ("", _Pos) -> end_of_file;
(S, Pos) ->
case re:run(S, Regex, [{capture, all_names}]) of
{match, [{0, N} | Capture]} ->
Index = 1 + length(lists:takewhile(fun({P, _}) -> P == -1 end, Capture)),
Action = lists:nth(Index, Actions),
{TokS, Rest} = lists:split(N, S),
Tok = Action(TokS, Pos),
{ok, Tok, Rest, next_pos(TokS, Pos)};
nomatch ->
error
end
end.
-spec token(atom()) -> token_action().
token(Tag) ->
token(Tag, fun(X) -> X end).
-spec token(atom(), fun((string()) -> term())) -> token_action().
token(Tag, Fun) ->
fun(S, P) -> {{token, {Tag, P, Fun(S)}}, none} end.
-spec symbol() -> token_action().
symbol() ->
fun(S, P) -> {{token, {list_to_atom(S), P}}, none} end.
-spec skip() -> token_action().
skip() ->
fun(_, _) -> {skip, none} end.
-spec push(lex_state(), token_action()) -> token_action().
push(State, Action) ->
fun(S, P) -> {Res, _} = Action(S, P), {Res, {push, State}} end.
-spec pop(token_action()) -> token_action().
pop(Action) ->
fun(S, P) -> {Res, _} = Action(S, P), {Res, pop} end.
@doc Match using the first spec , but if the second spec also matches use
that one instead . Use this for overlapping tokens ( like identifiers and
-spec override(token_spec(), token_spec()) -> token_spec().
override({Re1, Action1}, {Re2, Action2}) ->
{ok, Compiled} = re:compile(["^(", Re2, ")$"]),
{Re1, fun(S, P) ->
case re:run(S, Compiled, [{capture, none}]) of
match -> Action2(S, P);
nomatch -> Action1(S, P)
end end}.
-spec string(lexer(), lex_state(), string()) -> {ok, [token()]} | {error, term()}.
string(Lexer, State, String) -> string(Lexer, [State], String, {1, 1}).
string(Lexer, Stack, String, Pos) ->
Lines = string:split(String, "\n", all),
string(Lexer, Stack, Lines, Pos, []).
string(_Lexers, [], [Line | _Rest], Pos, _Acc) ->
{error, {{Line,Pos}, scan_error_no_state}};
string(_Lexers, _Stack, [], _Pos, Acc) ->
{ok, lists:reverse(Acc)};
string(Lexers, [State | Stack], [Line | Lines], Pos, Acc) ->
Lexer = proplists:get_value(State, Lexers, State),
case Lexer(Line, Pos) of
{ok, {Res, StateChange}, Line1, Pos1} ->
Acc1 = case Res of
{token, Tok} -> [Tok | Acc];
skip -> Acc
end,
Stack1 = case StateChange of
none -> [State | Stack];
pop -> Stack;
{push, State1} -> [State1, State | Stack]
end,
string(Lexers, Stack1, [Line1 | Lines], Pos1, Acc1);
end_of_file -> string(Lexers, [State | Stack], Lines, next_pos("\n", Pos), Acc);
error -> {error, {{Line,Pos}, scan_error}}
end.
name(I) ->
io_lib:format("?<A~3.10.0b>", [I]).
-define(TAB_SIZE, 8).
next_pos([], P) -> P;
next_pos([$\n | S], {L, _}) -> next_pos(S, {L + 1, 1});
next_pos([$\t | S], {L, C}) -> next_pos(S, {L, (C + ?TAB_SIZE - 1) div ?TAB_SIZE * ?TAB_SIZE + 1});
next_pos([_ | S], {L, C}) -> next_pos(S, {L, C + 1}).
|
838a16366f03178581d3da7e9aa75b08e6f39109371f95f805b0eb3595348777 | ocaml-obuild/obuild | c.ml | let foo = "B.C.foo"
| null | https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/tests/full/autopack2/src/b/c.ml | ocaml | let foo = "B.C.foo"
| |
f9b6cea60e0bb434eb6eb0c4ae56aff861c9914f5ab0f62aa0227bcf15599a6e | samply/blaze | spec.clj | (ns blaze.fhir.structure-definition-repo.spec
(:require
[blaze.fhir.structure-definition-repo.protocols :as p]
[clojure.spec.alpha :as s]))
(defn structure-definition-repo? [x]
(satisfies? p/StructureDefinitionRepo x))
(s/def :blaze.fhir/structure-definition-repo
structure-definition-repo?)
| null | https://raw.githubusercontent.com/samply/blaze/ccfad24c890c25a87ba4e3cde035ba8dbfd4d239/modules/fhir-structure/src/blaze/fhir/structure_definition_repo/spec.clj | clojure | (ns blaze.fhir.structure-definition-repo.spec
(:require
[blaze.fhir.structure-definition-repo.protocols :as p]
[clojure.spec.alpha :as s]))
(defn structure-definition-repo? [x]
(satisfies? p/StructureDefinitionRepo x))
(s/def :blaze.fhir/structure-definition-repo
structure-definition-repo?)
| |
ffe7e68103c4689b23d372104288fc703b884bc76bc98cafa1adb2c6824d5348 | facebook/flow | parser_utils_output_printers_tests.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
let tests = "printers" >::: [Pretty_printer_test.tests]
let () = run_test_tt_main tests
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/parser_utils/output/printers/__tests__/parser_utils_output_printers_tests.ml | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
let tests = "printers" >::: [Pretty_printer_test.tests]
let () = run_test_tt_main tests
| |
8f8de6a9470e5f24c3fd2824025a6633cc6fc689ea22f421d03865f3ec921c40 | mbj/stratosphere | VpcConfigProperty.hs | module Stratosphere.SageMaker.DataQualityJobDefinition.VpcConfigProperty (
VpcConfigProperty(..), mkVpcConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data VpcConfigProperty
= VpcConfigProperty {securityGroupIds :: (ValueList Prelude.Text),
subnets :: (ValueList Prelude.Text)}
mkVpcConfigProperty ::
ValueList Prelude.Text
-> ValueList Prelude.Text -> VpcConfigProperty
mkVpcConfigProperty securityGroupIds subnets
= VpcConfigProperty
{securityGroupIds = securityGroupIds, subnets = subnets}
instance ToResourceProperties VpcConfigProperty where
toResourceProperties VpcConfigProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::DataQualityJobDefinition.VpcConfig",
supportsTags = Prelude.False,
properties = ["SecurityGroupIds" JSON..= securityGroupIds,
"Subnets" JSON..= subnets]}
instance JSON.ToJSON VpcConfigProperty where
toJSON VpcConfigProperty {..}
= JSON.object
["SecurityGroupIds" JSON..= securityGroupIds,
"Subnets" JSON..= subnets]
instance Property "SecurityGroupIds" VpcConfigProperty where
type PropertyType "SecurityGroupIds" VpcConfigProperty = ValueList Prelude.Text
set newValue VpcConfigProperty {..}
= VpcConfigProperty {securityGroupIds = newValue, ..}
instance Property "Subnets" VpcConfigProperty where
type PropertyType "Subnets" VpcConfigProperty = ValueList Prelude.Text
set newValue VpcConfigProperty {..}
= VpcConfigProperty {subnets = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/DataQualityJobDefinition/VpcConfigProperty.hs | haskell | module Stratosphere.SageMaker.DataQualityJobDefinition.VpcConfigProperty (
VpcConfigProperty(..), mkVpcConfigProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data VpcConfigProperty
= VpcConfigProperty {securityGroupIds :: (ValueList Prelude.Text),
subnets :: (ValueList Prelude.Text)}
mkVpcConfigProperty ::
ValueList Prelude.Text
-> ValueList Prelude.Text -> VpcConfigProperty
mkVpcConfigProperty securityGroupIds subnets
= VpcConfigProperty
{securityGroupIds = securityGroupIds, subnets = subnets}
instance ToResourceProperties VpcConfigProperty where
toResourceProperties VpcConfigProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::DataQualityJobDefinition.VpcConfig",
supportsTags = Prelude.False,
properties = ["SecurityGroupIds" JSON..= securityGroupIds,
"Subnets" JSON..= subnets]}
instance JSON.ToJSON VpcConfigProperty where
toJSON VpcConfigProperty {..}
= JSON.object
["SecurityGroupIds" JSON..= securityGroupIds,
"Subnets" JSON..= subnets]
instance Property "SecurityGroupIds" VpcConfigProperty where
type PropertyType "SecurityGroupIds" VpcConfigProperty = ValueList Prelude.Text
set newValue VpcConfigProperty {..}
= VpcConfigProperty {securityGroupIds = newValue, ..}
instance Property "Subnets" VpcConfigProperty where
type PropertyType "Subnets" VpcConfigProperty = ValueList Prelude.Text
set newValue VpcConfigProperty {..}
= VpcConfigProperty {subnets = newValue, ..} | |
fa21f4024f76fe7214268e938ed18b0fc24206259757ce44937141869650b7b6 | heyoka/faxe | faxe.erl | Date : 28.04.17 - 23:17
%% faxe api
Ⓒ 2017
-module(faxe).
-author("Alexander Minichmair").
-include("faxe.hrl").
%% API
-export([
register_task/3,
register_file_task/2,
register_string_task/2,
list_tasks/0,
start_task/1,
start_task/2,
stop_task/1,
stop_task/2,
delete_task/1,
delete_task/2,
register_template_file/2,
register_template_string/2,
task_from_template/3,
task_from_template/2,
join/1, join/0,
list_templates/0,
delete_template/1,
start_many/3,
list_running_tasks/0,
start_permanent_tasks/0,
get_stats/1,
update_file_task/2,
update_string_task/2,
update_task/3,
update/3,
list_permanent_tasks/0,
get_task/1,
ping_task/1,
start_temp/2,
start_file_temp/2,
get_template/1,
list_temporary_tasks/0,
list_tasks_by_template/1,
list_tasks_by_tags/1,
get_all_tags/0,
add_tags/2,
remove_tags/2,
set_tags/2,
get_graph/1,
task_to_graph/1,
start_trace/2,
stop_trace/1,
update_all/0,
stop_task_group/2,
delete_task_group/1,
list_tasks_by_group/1,
set_group_size/2,
update_by_tags/1,
update_by_template/1,
eval_dfs/2,
task_to_graph_running/1,
update_all/1,
update_by_tags/2,
update_by_template/2, start_metrics_trace/2, stop_metrics_trace/1,
reset_tasks/0,
reset_templates/0,
stop_all/0
%% , do_start_task/2
]).
start_permanent_tasks() ->
Tasks = faxe_db:get_permanent_tasks(),
[start_task(T#task.id, true) || T <- Tasks].
start_many(FileName, TaskName, Num) when is_binary(TaskName), is_integer(Num) ->
ok = register_template_file(FileName, TaskName),
start_many(TaskName, Num).
start_many(_TName, 0) -> ok;
start_many(TName, Num) ->
TaskName = <<TName/binary, (integer_to_binary(Num))/binary>>,
ok = task_from_template(TName, TaskName),
start_task(TaskName),
start_many(TName, Num-1).
join() ->
faxe_db:db_init().
join(NodeName) ->
pong = net_adm:ping(NodeName),
faxe_db:db_init().
-spec get_task(term()) -> {error, not_found}|#task{}.
get_task(TaskId) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, not_found};
#task{name = Id} = T ->
Running = supervisor:which_children(graph_sup),
case lists:keyfind(Id, 1, Running) of
{Id, Child, _, _} when is_pid(Child) -> T#task{is_running = is_process_alive(Child)};
_ -> T#task{is_running = false}
end
end.
%% @doc get the graph definition (nodes and edges) as a map
-spec get_graph(non_neg_integer()|binary()|#task{}) -> map() | {error, term()}.
get_graph(#task{} = T) ->
case is_task_alive(T) of
true -> task_to_graph_running(T);
false -> task_to_graph(T)
end;
get_graph(TaskId) ->
case get_task(TaskId) of
#task{} = T1 -> get_graph(T1);
O -> O
end.
task_to_graph_running(#task{pid = GraphPid} = _T) ->
df_graph:graph_def(GraphPid).
task_to_graph(#task{definition = #{edges := Edges, nodes := Nodes} } = _T) ->
G = digraph:new(),
[graph_builder:add_node(G, NName, NType) || {NName, NType, _Opts} <- Nodes],
[graph_builder:add_edge(G, Source, PortOut, Dest, PortIn, M) || {Source, PortOut, Dest, PortIn, M} <- Edges],
graph_builder:to_graph_def(G, Nodes).
-spec get_template(term()) -> {error, not_found}|#template{}.
get_template(TemplateId) ->
case faxe_db:get_template(TemplateId) of
{error, not_found} -> {error, not_found};
#template{} = T -> T
end.
get_all_tags() ->
faxe_db:get_all_tags().
-spec list_tasks() -> list().
list_tasks() ->
add_running_flag(faxe_db:get_all_tasks()).
-spec list_templates() -> list().
list_templates() ->
faxe_db:get_all_templates().
-spec list_running_tasks() -> list(#task{}).
list_running_tasks() ->
Graphs = supervisor:which_children(graph_sup),
[T#task{is_running = true} || T <- faxe_db:get_tasks_by_pids(Graphs)].
list_permanent_tasks() ->
faxe_db:get_permanent_tasks().
list_temporary_tasks() ->
Tasks = ets:tab2list(temp_tasks),
Tasks.
list_tasks_by_template(TemplateId) when is_integer(TemplateId) ->
case get_template(TemplateId) of
#template{name = Name} -> list_tasks_by_template(Name);
Other -> Other
end;
list_tasks_by_template(TemplateName) when is_binary(TemplateName) ->
add_running_flag(faxe_db:get_tasks_by_template(TemplateName)).
list_tasks_by_tags(TagList) when is_list(TagList) ->
add_running_flag(faxe_db:get_tasks_by_tags(TagList)).
list_tasks_by_group(GroupName) when is_binary(GroupName) ->
add_running_flag(faxe_db:get_tasks_by_group(GroupName)).
add_tags(TaskId, Tags) ->
faxe_db:add_tags(TaskId, Tags).
remove_tags(TaskId, Tags) ->
faxe_db:remove_tags(TaskId, Tags).
set_tags(TaskId, Tags) ->
faxe_db:set_tags(TaskId, Tags).
add_running_flag(TaskList) when is_list(TaskList) ->
Running = supervisor:which_children(graph_sup),
F =
fun(#task{name = Id} = T) ->
case lists:keyfind(Id, 1, Running) of
{Id, Child, _, _} when is_pid(Child) -> T#task{is_running = is_process_alive(Child)};
_ -> T#task{is_running = false}
end
end,
lists:map(F, TaskList);
add_running_flag(What) ->
What.
-spec register_file_task(list()|binary(), any()) -> any().
register_file_task(DfsScript, Name) ->
register_task(DfsScript, Name, file).
-spec register_string_task(list()|binary(), any()) -> any().
register_string_task(DfsScript, Name) ->
register_task(DfsScript, Name, data).
-spec register_task(list()|binary(), binary(), atom()) -> ok | {error, task_exists} | {error, term()}.
register_task(DfsScript, Name, Type) ->
case check_task(DfsScript, Name, Type) of
{error, _What} = Err -> Err;
{DFS, Def} ->
Task = #task{
date = faxe_time:now_date(),
dfs = DFS,
definition = Def,
name = Name,
group = Name,
group_leader = true
},
%% flow_changed({flow, Name, register}),
faxe_db:save_task(Task)
end.
-spec check_task(list()|binary(), binary(), atom()) -> {error, Reason :: term()} | {DFS :: binary(), map()}.
check_task(DfsScript, Name, Type) ->
case faxe_db:get_task(Name) of
{error, not_found} ->
case eval_dfs(DfsScript, Type) of
{_DFS, Def} = Res when is_map(Def) ->
Res;
{error, What} -> {error, What}
end;
_T ->
{error, task_exists}
end.
-spec register_template_file(list(), binary()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template_file(DfsFile, TemplateName) ->
StringData = binary_to_list(get_file_dfs(DfsFile)),
register_template_string(StringData, TemplateName).
-spec register_template_string(list(), binary()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template_string(DfsString, TemplateName) ->
register_template(DfsString, TemplateName, data).
-spec register_template(list(), term(), atom()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template(DfsScript, Name, Type) ->
case faxe_db:get_template(Name) of
{error, not_found} ->
case eval_dfs(DfsScript, Type) of
{DFS, Def} when is_map(Def) ->
Template = #template{
date = faxe_time:now_date(),
definition = Def,
name = Name,
dfs = DFS
},
%% flow_changed({template, Name, delete}),
faxe_db:save_template(Template);
{error, What} -> {error, What}
end;
_T ->
{error, template_exists}
end.
task_from_template(TemplateId, TaskName) ->
task_from_template(TemplateId, TaskName, #{}).
task_from_template(TemplateId, TaskName, Vars) when is_map(Vars) ->
case faxe_db:get_task(TaskName) of
{error, not_found} -> case faxe_db:get_template(TemplateId) of
{error, not_found} -> {error, template_not_found};
Template = #template{} -> template_to_task(Template, TaskName, Vars), ok
end;
#task{} -> {error, task_exists}
end.
%% @doc update all tasks that exist, use with care
-spec update_all() -> [ok|{error, term()}].
update_all() ->
update_all(false).
update_all(Force) ->
update_list(list_tasks(), Force).
update_by_tags(Tags) when is_list(Tags) ->
update_by_tags(Tags, false).
update_by_tags(Tags, Force) when is_list(Tags) ->
Tasks = list_tasks_by_tags(Tags),
update_list(Tasks, Force).
update_by_template(TemplateId) ->
update_by_template(TemplateId, false).
update_by_template(TemplateId, Force) ->
Tasks = list_tasks_by_template(TemplateId),
update_list(Tasks, Force).
update_list(TaskList, Force) when is_list(TaskList) ->
F = fun(#task{id = Id, dfs = DfsScript}) -> update_task(DfsScript, Id, Force, data) end,
plists:map(F, TaskList, 3).
-spec update_file_task(list(), integer()|binary()) -> ok|{error, term()}.
update_file_task(DfsFile, TaskId) ->
update_task(DfsFile, TaskId, file).
-spec update_string_task(binary(), integer()|binary()) -> ok|{error, term()}.
update_string_task(DfsScript, TaskId) ->
update_task(DfsScript, TaskId, data).
update_task(DfsScript, TaskId, ScriptType) ->
update_task(DfsScript, TaskId, false, ScriptType).
-spec update_task(list()|binary(), integer()|binary(), true|false, atom()) -> ok|{error, term()}.
update_task(DfsScript, TaskId, Force, ScriptType) ->
Res =
case get_running(TaskId) of
{true, T=#task{}} -> {update_running(DfsScript, T, Force, ScriptType), T};
{false, T=#task{}} -> {maybe_update(DfsScript, T, Force, ScriptType), T};
{ _ , T=#task{group_leader = false } } - > { error , group_leader_update_only } ;
Err -> {Err, nil}
end,
Out =
case Res of
{ok, _Task = #task{group_leader = true, group = Group}} ->
GroupMembers = faxe_db:get_tasks_by_group(Group),
case GroupMembers of
{error, not_found} -> ok;
L when is_list(L) ->
%% update group-members
[update_task(DfsScript, Id, Force, ScriptType)
|| #task{id = Id, group_leader = Lead} <- L, Lead == false],
ok
end;
{{ok, _}, _} -> ok;
{Error, _} -> Error
end,
Out.
maybe_update(DfsScript, T = #task{}, true, ScriptType) ->
update(DfsScript, T, ScriptType);
maybe_update(DfsScript, T = #task{dfs = DFS}, false, ScriptType) ->
case erlang:crc32(DfsScript) =:= erlang:crc32(DFS) of
true -> {ok, no_update};
false -> update(DfsScript, T, ScriptType)
end.
-spec update(list()|binary(), #task{}, atom()) -> ok|{error, term()}.
update(DfsScript, Task, ScriptType) ->
case eval_dfs(DfsScript, ScriptType) of
{DFS, Map} when is_map(Map) ->
NewTask = Task#task{
definition = Map,
dfs = DFS,
date = faxe_time:now_date()},
flow_changed({flow , Task#task.name , update } ) ,
faxe_db:save_task(NewTask);
Err -> Err
end.
-spec update_running(list()|binary(), #task{}, true|false, atom()) -> ok|{error, term()}.
update_running(DfsScript, Task = #task{id = TId, pid = TPid}, Force, ScriptType) ->
case maybe_update(DfsScript, Task, Force, ScriptType) of
{ok, no_update} -> {ok, no_update};
{error, Err} -> {error, Err};
ok ->
%% we use just the task-id to stop and restart the task, otherwise the just updated task would be overwritten
erlang:monitor(process, TPid),
stop_task(Task#task.id, false),
receive
{'DOWN', _MonitorRef, process, TPid, _Info} ->
start_task(TId, Task#task.permanent), ok
after 5000 ->
catch erlang:demonitor(TPid, true), {error, updated_task_start_timeout}
end
end.
-spec eval_dfs(list()|binary(), file|data) ->
{DFSString :: list(), GraphDefinition :: map()} | {error, term()}.
eval_dfs(DfsScript, Type) ->
try faxe_dfs:Type(DfsScript, []) of
{_DFSString, {error, What}} -> {error, What};
{error, What} -> {error, What};
{_DFSString, Def} = Result when is_map(Def) -> Result;
E -> E
catch
throw : Err : Stacktrace - > { error , ;
exit : Err : Stacktrace - > { error , ;
error : Err : Stacktrace - > { error , ;
_:Err:Stacktrace ->
lager:warning("Error: ~p ~nstacktrace: ~p",[Err, Stacktrace]),
{error, Err}
end.
%% @doc get a task by its id and also if it is currently running
-spec get_running(integer()|binary()) -> {error, term()}|{true|false, #task{}}.
get_running(TaskId) ->
case faxe_db:get_task(TaskId) of
{error, Error} -> {error, Error};
T = #task{} ->
case is_task_alive(T) of
true -> {true, T};
false -> {false, T}
end
end.
%% get the dfs binary
get_file_dfs(DfsFile) ->
{ok, DfsParams} = application:get_env(faxe, dfs),
Path = proplists:get_value(script_path, DfsParams),
{ok, Data} = file:read_file(Path++DfsFile),
binary:replace(Data, <<"\\">>, <<>>, [global]).
start_file_temp(DfsScript, TTL) ->
start_temp(DfsScript, file, TTL).
start_temp(DfsScript, TTL) ->
start_temp(DfsScript, data, TTL).
start_temp(DfsScript, Type, TTL) ->
case eval_dfs(DfsScript, Type) of
{DFS, Def} when is_map(Def) ->
Id = list_to_binary(faxe_util:uuid_string()),
case dataflow:create_graph(Id, Def) of
{ok, Graph} ->
_Task = #task{
date = faxe_time:now_date(),
dfs = DFS,
definition = Def,
name = Id
},
ets:insert(temp_tasks, {Id, Graph}),
try df_graph:start_graph(Graph, #task_modes{temporary = true, temp_ttl = TTL}) of
_ ->
{ok, Id}
catch
_:E = E -> lager:error("graph_start_error: ~p",[E]),
{error, {graph_start_error, E}}
end;
{error, E} -> {error, E}
end;
{error, What} -> {error, What}
end.
%%%------------------------------------------------
%%% start task
%%%------------------------------------------------
start_task(TaskId) ->
start_task(TaskId, false).
start_task(TaskId, #task_modes{run_mode = _RunMode} = Mode) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, task_not_found};
T = #task{} -> graph_starter:start_graph(T, Mode), {ok, enqueued_to_start}
end;
start_task(TaskId, Permanent) when Permanent == true orelse Permanent == false ->
start_task(TaskId, push, Permanent).
-spec start_task(integer()|binary(), atom(), true|false) -> ok|{error, term()}.
start_task(TaskId, GraphRunMode, Permanent) ->
start_task(TaskId, #task_modes{run_mode = GraphRunMode, permanent = Permanent}).
do_start_task(T = # task{name = Name , definition = GraphDef } ,
# task_modes{concurrency = Concurrency , permanent = Perm } = Mode ) - >
case dataflow : create_graph(Name , GraphDef ) of
%% {ok, Graph} ->
%% try dataflow:start_graph(Graph, Mode) of
%% _ ->
%% faxe_db:save_task(T#task{pid = Graph, last_start = faxe_time:now_date(), permanent = Perm}),
%% Res =
%% case Concurrency of
%% 1 -> {ok, Graph};
when > 1 - >
%% start_concurrent(T, Mode),
%% {ok, Graph}
%% end,
%%%% flow_changed({task, Name, start}),
%% Res
%% catch
%% _:_ = E ->
%% lager:error("graph_start_error: ~p",[E]),
%% {error, {graph_start_error, E}}
%% end;
{ error , { already_started , _ Pid } } - > { error , already_started }
%% end.
start_concurrent(Task = #task{}, #task_modes{concurrency = Con} = Mode) ->
F = fun(Num) -> start_copy(Task, Mode, Num) end,
lists:map(F, lists:seq(2, Con)).
start_copy(Task = #task{definition = GraphDef, name = TName}, #task_modes{permanent = Perm} = Mode, Num) ->
NumBin = integer_to_binary(Num),
Name = <<TName/binary, "--", NumBin/binary>>,
case faxe_db:get_task(Name) of
{error, not_found} ->
case dataflow:create_graph(Name, GraphDef) of
{ok, Graph} ->
try dataflow:start_graph(Graph, Mode) of
ok ->
faxe_db:save_task(
Task#task{
pid = Graph, name = Name,
id = undefined, group_leader = false,
last_start = faxe_time:now_date(),
permanent = Perm, group = TName})
catch
_:E = E ->
lager:error("graph_start_error: ~p",[E]),
{error, {graph_start_error, E}}
end;
{error, What} -> {error, What}
end;
T = #task{} -> graph_starter:start_graph(T#task{group_leader = false, group = TName}, Mode#task_modes{concurrency = 1})
end
.
%%%-------------------------------------------------
%%% task group
%%%-------------------------------------------------
-spec set_group_size(binary(), non_neg_integer()) -> ok|list().
set_group_size(GroupName, NewSize) when is_binary(GroupName), is_integer(NewSize) ->
case faxe_db:get_tasks_by_group(GroupName) of
{error, not_found} -> {error, group_not_found};
GroupList when is_list(GroupList) ->
Leader = get_group_leader(GroupList),
case is_task_alive(Leader) of
false -> {error, not_running};
true ->
RunningMembers = [T || T <- GroupList, is_task_alive(T)],
case NewSize - length(RunningMembers) of
N when N >= 0 -> %% we want more
start_concurrent(Leader,
#task_modes{concurrency = NewSize, permanent = Leader#task.permanent});
N1 when N1 < 0 -> %% we want less
Num = abs(N1),
SB = byte_size(GroupName),
SortFun =
fun
(#task{name = <<GN:SB/binary, "--", Rank/binary>>},
#task{name = <<GN:SB/binary, "--", OtherRank/binary>>}) ->
binary_to_integer(Rank) > binary_to_integer(OtherRank);
(_, _) -> true
end,
Sorted = lists:sort(SortFun, RunningMembers),
del_group_members(Sorted, Num)
end
end
end.
del_group_members([], _) ->
[];
del_group_members(GroupList, 0) ->
GroupList;
del_group_members([#task{group_leader = true} | R], Num) ->
del_group_members(R, Num);
del_group_members([T=#task{group_leader = false, id = TaskId} | R], Num) ->
do_stop_task(T, false),
faxe_db:delete_task(TaskId),
del_group_members(R, Num - 1).
get_group_leader([]) ->
{error, group_leader_not_found};
get_group_leader([#task{group_leader = false} | R]) ->
get_group_leader(R);
get_group_leader([T=#task{group_leader = true} | _R]) ->
T.
-spec stop_task(integer()|binary()|#task{}) -> ok.
%% @doc just stop the graph process and its children
stop_task(_T=#task{pid = Graph}) when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:stop(Graph);
false -> {error, not_running}
end;
stop_task(TaskId) ->
stop_task(TaskId, false).
-spec stop_task(#task{}|integer()|binary(), true|false) -> ok.
stop_task(T = #task{}, Permanent) ->
do_stop_task(T, Permanent);
stop_task(TaskId, Permanent) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} = T when is_pid(Graph) -> do_stop_task(T, Permanent);
#task{} -> {error, not_running}
end.
%% stop all tasks running with a specific group name
stop_task_group(TaskGroupName, Permanent) ->
Tasks = faxe_db:get_tasks_by_group(TaskGroupName),
case Tasks of
{error, not_found} -> {error, not_found};
TaskList when is_list(TaskList) ->
[do_stop_task(T, Permanent) || T <- TaskList]
end.
stop_all() ->
Tasks = list_running_tasks(),
[stop_task(Task) || Task <- Tasks].
do_stop_task(T = #task{pid = Graph, group_leader = _Leader, group = _Group}, Permanent) ->
case is_task_alive(T) of
true ->
df_graph:stop(Graph),
NewT =
case Permanent of
true -> T#task{permanent = false};
false -> T
end,
Res = faxe_db:save_task(NewT#task{pid = undefined, last_stop = faxe_time:now_date()}),
%% flow_changed({task, T#task.name, stop}),
Res;
%% case Leader of
%% true ->
%% GroupMembers = faxe_db:get_tasks_by_group(Group),
case of
%% {error, not_found} -> ok;
L when ) - >
%% %% stop group-members
%% [do_stop_task(Task, Permanent) || Task <- L], ok
%% end;
%% false -> ok
%% end;
false -> {error, not_running}
end.
-spec delete_task(binary()) -> ok | {error, not_found} | {error, task_is_running}.
delete_task(TaskId) ->
delete_task(TaskId, false).
-spec delete_task(binary(), true|false) -> ok | {error, not_found} | {error, task_is_running}.
delete_task(TaskId, Force) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, not_found};
T = #task{} ->
case is_task_alive(T) of
true ->
case Force of
true ->
stop_task(T),
do_delete_task(T);
false -> {error, task_is_running}
end;
false -> do_delete_task(T)
end
end.
do_delete_task(#task{id = TaskId, group = Group, group_leader = Leader}) ->
case faxe_db:delete_task(TaskId) of
ok ->
case Leader of
true ->
delete_task_group(Group),
flow_changed({flow , TaskId , delete } ) ,
ok;
false -> ok
end;
Else -> Else
end.
%% delete all tasks from db with group == TaskGroupName
delete_task_group(TaskGroupName) ->
Tasks = faxe_db:get_tasks_by_group(TaskGroupName),
case Tasks of
{error, not_found} -> {error, not_found};
TaskList when is_list(TaskList) ->
case lists:all(fun(#task{} = T) -> is_task_alive(T) == false end, TaskList) of
true -> [faxe_db:delete_task(T) || T <- TaskList];
false -> {error, tasks_are_running}
end
end.
delete_template(TaskId) ->
T = faxe_db:get_template(TaskId),
case T of
{error, not_found} -> ok;
#template{} ->
Res = faxe_db:delete_template(TaskId),
flow_changed({template , TaskId , delete } ) ,
Res
end.
%% @doc stop all tasks running, delete all tasks and tags from the database, keep other data
reset_tasks() ->
stop_all(),
{atomic, ok} = faxe_db:reset_tasks(),
ok.
%% @doc delete all templates from the database
reset_templates() ->
stop_all(),
{atomic, ok} = faxe_db:reset_tasks(),
ok.
is_task_alive(#task{pid = Graph}) when is_pid(Graph) ->
is_process_alive(Graph) =:= true;
is_task_alive(_) -> false.
-spec ping_task(term()) -> {ok, NewTimeout::non_neg_integer()} | {error, term()}.
ping_task(TaskId) ->
case ets:lookup(temp_tasks, TaskId) of
[] -> {error, not_found};
[{TaskId, GraphPid}] -> df_graph:ping(GraphPid)
end.
%% @deprecated
get_stats(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:get_stats(Graph);
false -> {error, task_not_running}
end;
#task{} -> {ok, []}
end.
-spec start_trace(non_neg_integer()|binary(), non_neg_integer()|undefined) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
start_trace(TaskId, DrationMs) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:start_trace(Graph, trace_duration(DrationMs)),
{ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
trace_duration(undefined) ->
faxe_config:get(debug_time, 60000);
trace_duration(DurationMs) when is_integer(DurationMs) ->
DurationMs.
-spec stop_trace(non_neg_integer()|binary()) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
stop_trace(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:stop_trace(Graph), {ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
-spec start_metrics_trace(non_neg_integer()|binary(), undefined|non_neg_integer()) ->
{ok, pid()} | {error, not_found} | {error_task_not_running}.
start_metrics_trace(TaskId, DurationMs) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:start_metrics_trace(Graph, trace_duration(DurationMs)),
{ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
-spec stop_metrics_trace(non_neg_integer()|binary()) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
stop_metrics_trace(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:stop_metrics_trace(Graph), {ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec template_to_task(#template{}, binary(), map()) -> ok | {error, term()}.
template_to_task(Template = #template{dfs = DFS}, TaskName, Vars) ->
{DFSString, Def} = faxe_dfs:data(DFS, Vars),
case Def of
_ when is_map(Def) ->
Task = #task{
date = faxe_time:now_date(),
definition = Def,
dfs = DFSString,
name = TaskName,
template = Template#template.name,
template_vars = Vars
},
Res = faxe_db:save_task(Task),
flow_changed({flow , TaskName , register } ) ,
Res;
{error, What} -> {error, What}
end.
flow_changed({Type, Affected, Method}) ->
Msg = #data_point{ts = faxe_time:now(),
fields = #{<<"type">> => Type, <<"affected">> => Affected, <<"method">> => Method}},
gen_event:notify(flow_changed, Msg). | null | https://raw.githubusercontent.com/heyoka/faxe/59b005aa82e99a130e8a07601ff365f1e540ce0a/apps/faxe/src/faxe.erl | erlang | faxe api
API
, do_start_task/2
@doc get the graph definition (nodes and edges) as a map
flow_changed({flow, Name, register}),
flow_changed({template, Name, delete}),
@doc update all tasks that exist, use with care
update group-members
we use just the task-id to stop and restart the task, otherwise the just updated task would be overwritten
@doc get a task by its id and also if it is currently running
get the dfs binary
------------------------------------------------
start task
------------------------------------------------
{ok, Graph} ->
try dataflow:start_graph(Graph, Mode) of
_ ->
faxe_db:save_task(T#task{pid = Graph, last_start = faxe_time:now_date(), permanent = Perm}),
Res =
case Concurrency of
1 -> {ok, Graph};
start_concurrent(T, Mode),
{ok, Graph}
end,
flow_changed({task, Name, start}),
Res
catch
_:_ = E ->
lager:error("graph_start_error: ~p",[E]),
{error, {graph_start_error, E}}
end;
end.
-------------------------------------------------
task group
-------------------------------------------------
we want more
we want less
@doc just stop the graph process and its children
stop all tasks running with a specific group name
flow_changed({task, T#task.name, stop}),
case Leader of
true ->
GroupMembers = faxe_db:get_tasks_by_group(Group),
{error, not_found} -> ok;
%% stop group-members
[do_stop_task(Task, Permanent) || Task <- L], ok
end;
false -> ok
end;
delete all tasks from db with group == TaskGroupName
@doc stop all tasks running, delete all tasks and tags from the database, keep other data
@doc delete all templates from the database
@deprecated
| Date : 28.04.17 - 23:17
Ⓒ 2017
-module(faxe).
-author("Alexander Minichmair").
-include("faxe.hrl").
-export([
register_task/3,
register_file_task/2,
register_string_task/2,
list_tasks/0,
start_task/1,
start_task/2,
stop_task/1,
stop_task/2,
delete_task/1,
delete_task/2,
register_template_file/2,
register_template_string/2,
task_from_template/3,
task_from_template/2,
join/1, join/0,
list_templates/0,
delete_template/1,
start_many/3,
list_running_tasks/0,
start_permanent_tasks/0,
get_stats/1,
update_file_task/2,
update_string_task/2,
update_task/3,
update/3,
list_permanent_tasks/0,
get_task/1,
ping_task/1,
start_temp/2,
start_file_temp/2,
get_template/1,
list_temporary_tasks/0,
list_tasks_by_template/1,
list_tasks_by_tags/1,
get_all_tags/0,
add_tags/2,
remove_tags/2,
set_tags/2,
get_graph/1,
task_to_graph/1,
start_trace/2,
stop_trace/1,
update_all/0,
stop_task_group/2,
delete_task_group/1,
list_tasks_by_group/1,
set_group_size/2,
update_by_tags/1,
update_by_template/1,
eval_dfs/2,
task_to_graph_running/1,
update_all/1,
update_by_tags/2,
update_by_template/2, start_metrics_trace/2, stop_metrics_trace/1,
reset_tasks/0,
reset_templates/0,
stop_all/0
]).
start_permanent_tasks() ->
Tasks = faxe_db:get_permanent_tasks(),
[start_task(T#task.id, true) || T <- Tasks].
start_many(FileName, TaskName, Num) when is_binary(TaskName), is_integer(Num) ->
ok = register_template_file(FileName, TaskName),
start_many(TaskName, Num).
start_many(_TName, 0) -> ok;
start_many(TName, Num) ->
TaskName = <<TName/binary, (integer_to_binary(Num))/binary>>,
ok = task_from_template(TName, TaskName),
start_task(TaskName),
start_many(TName, Num-1).
join() ->
faxe_db:db_init().
join(NodeName) ->
pong = net_adm:ping(NodeName),
faxe_db:db_init().
-spec get_task(term()) -> {error, not_found}|#task{}.
get_task(TaskId) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, not_found};
#task{name = Id} = T ->
Running = supervisor:which_children(graph_sup),
case lists:keyfind(Id, 1, Running) of
{Id, Child, _, _} when is_pid(Child) -> T#task{is_running = is_process_alive(Child)};
_ -> T#task{is_running = false}
end
end.
-spec get_graph(non_neg_integer()|binary()|#task{}) -> map() | {error, term()}.
get_graph(#task{} = T) ->
case is_task_alive(T) of
true -> task_to_graph_running(T);
false -> task_to_graph(T)
end;
get_graph(TaskId) ->
case get_task(TaskId) of
#task{} = T1 -> get_graph(T1);
O -> O
end.
task_to_graph_running(#task{pid = GraphPid} = _T) ->
df_graph:graph_def(GraphPid).
task_to_graph(#task{definition = #{edges := Edges, nodes := Nodes} } = _T) ->
G = digraph:new(),
[graph_builder:add_node(G, NName, NType) || {NName, NType, _Opts} <- Nodes],
[graph_builder:add_edge(G, Source, PortOut, Dest, PortIn, M) || {Source, PortOut, Dest, PortIn, M} <- Edges],
graph_builder:to_graph_def(G, Nodes).
-spec get_template(term()) -> {error, not_found}|#template{}.
get_template(TemplateId) ->
case faxe_db:get_template(TemplateId) of
{error, not_found} -> {error, not_found};
#template{} = T -> T
end.
get_all_tags() ->
faxe_db:get_all_tags().
-spec list_tasks() -> list().
list_tasks() ->
add_running_flag(faxe_db:get_all_tasks()).
-spec list_templates() -> list().
list_templates() ->
faxe_db:get_all_templates().
-spec list_running_tasks() -> list(#task{}).
list_running_tasks() ->
Graphs = supervisor:which_children(graph_sup),
[T#task{is_running = true} || T <- faxe_db:get_tasks_by_pids(Graphs)].
list_permanent_tasks() ->
faxe_db:get_permanent_tasks().
list_temporary_tasks() ->
Tasks = ets:tab2list(temp_tasks),
Tasks.
list_tasks_by_template(TemplateId) when is_integer(TemplateId) ->
case get_template(TemplateId) of
#template{name = Name} -> list_tasks_by_template(Name);
Other -> Other
end;
list_tasks_by_template(TemplateName) when is_binary(TemplateName) ->
add_running_flag(faxe_db:get_tasks_by_template(TemplateName)).
list_tasks_by_tags(TagList) when is_list(TagList) ->
add_running_flag(faxe_db:get_tasks_by_tags(TagList)).
list_tasks_by_group(GroupName) when is_binary(GroupName) ->
add_running_flag(faxe_db:get_tasks_by_group(GroupName)).
add_tags(TaskId, Tags) ->
faxe_db:add_tags(TaskId, Tags).
remove_tags(TaskId, Tags) ->
faxe_db:remove_tags(TaskId, Tags).
set_tags(TaskId, Tags) ->
faxe_db:set_tags(TaskId, Tags).
add_running_flag(TaskList) when is_list(TaskList) ->
Running = supervisor:which_children(graph_sup),
F =
fun(#task{name = Id} = T) ->
case lists:keyfind(Id, 1, Running) of
{Id, Child, _, _} when is_pid(Child) -> T#task{is_running = is_process_alive(Child)};
_ -> T#task{is_running = false}
end
end,
lists:map(F, TaskList);
add_running_flag(What) ->
What.
-spec register_file_task(list()|binary(), any()) -> any().
register_file_task(DfsScript, Name) ->
register_task(DfsScript, Name, file).
-spec register_string_task(list()|binary(), any()) -> any().
register_string_task(DfsScript, Name) ->
register_task(DfsScript, Name, data).
-spec register_task(list()|binary(), binary(), atom()) -> ok | {error, task_exists} | {error, term()}.
register_task(DfsScript, Name, Type) ->
case check_task(DfsScript, Name, Type) of
{error, _What} = Err -> Err;
{DFS, Def} ->
Task = #task{
date = faxe_time:now_date(),
dfs = DFS,
definition = Def,
name = Name,
group = Name,
group_leader = true
},
faxe_db:save_task(Task)
end.
-spec check_task(list()|binary(), binary(), atom()) -> {error, Reason :: term()} | {DFS :: binary(), map()}.
check_task(DfsScript, Name, Type) ->
case faxe_db:get_task(Name) of
{error, not_found} ->
case eval_dfs(DfsScript, Type) of
{_DFS, Def} = Res when is_map(Def) ->
Res;
{error, What} -> {error, What}
end;
_T ->
{error, task_exists}
end.
-spec register_template_file(list(), binary()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template_file(DfsFile, TemplateName) ->
StringData = binary_to_list(get_file_dfs(DfsFile)),
register_template_string(StringData, TemplateName).
-spec register_template_string(list(), binary()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template_string(DfsString, TemplateName) ->
register_template(DfsString, TemplateName, data).
-spec register_template(list(), term(), atom()) ->
'ok'|{error, template_exists}|{error, not_found}|{error, Reason::term()}.
register_template(DfsScript, Name, Type) ->
case faxe_db:get_template(Name) of
{error, not_found} ->
case eval_dfs(DfsScript, Type) of
{DFS, Def} when is_map(Def) ->
Template = #template{
date = faxe_time:now_date(),
definition = Def,
name = Name,
dfs = DFS
},
faxe_db:save_template(Template);
{error, What} -> {error, What}
end;
_T ->
{error, template_exists}
end.
task_from_template(TemplateId, TaskName) ->
task_from_template(TemplateId, TaskName, #{}).
task_from_template(TemplateId, TaskName, Vars) when is_map(Vars) ->
case faxe_db:get_task(TaskName) of
{error, not_found} -> case faxe_db:get_template(TemplateId) of
{error, not_found} -> {error, template_not_found};
Template = #template{} -> template_to_task(Template, TaskName, Vars), ok
end;
#task{} -> {error, task_exists}
end.
-spec update_all() -> [ok|{error, term()}].
update_all() ->
update_all(false).
update_all(Force) ->
update_list(list_tasks(), Force).
update_by_tags(Tags) when is_list(Tags) ->
update_by_tags(Tags, false).
update_by_tags(Tags, Force) when is_list(Tags) ->
Tasks = list_tasks_by_tags(Tags),
update_list(Tasks, Force).
update_by_template(TemplateId) ->
update_by_template(TemplateId, false).
update_by_template(TemplateId, Force) ->
Tasks = list_tasks_by_template(TemplateId),
update_list(Tasks, Force).
update_list(TaskList, Force) when is_list(TaskList) ->
F = fun(#task{id = Id, dfs = DfsScript}) -> update_task(DfsScript, Id, Force, data) end,
plists:map(F, TaskList, 3).
-spec update_file_task(list(), integer()|binary()) -> ok|{error, term()}.
update_file_task(DfsFile, TaskId) ->
update_task(DfsFile, TaskId, file).
-spec update_string_task(binary(), integer()|binary()) -> ok|{error, term()}.
update_string_task(DfsScript, TaskId) ->
update_task(DfsScript, TaskId, data).
update_task(DfsScript, TaskId, ScriptType) ->
update_task(DfsScript, TaskId, false, ScriptType).
-spec update_task(list()|binary(), integer()|binary(), true|false, atom()) -> ok|{error, term()}.
update_task(DfsScript, TaskId, Force, ScriptType) ->
Res =
case get_running(TaskId) of
{true, T=#task{}} -> {update_running(DfsScript, T, Force, ScriptType), T};
{false, T=#task{}} -> {maybe_update(DfsScript, T, Force, ScriptType), T};
{ _ , T=#task{group_leader = false } } - > { error , group_leader_update_only } ;
Err -> {Err, nil}
end,
Out =
case Res of
{ok, _Task = #task{group_leader = true, group = Group}} ->
GroupMembers = faxe_db:get_tasks_by_group(Group),
case GroupMembers of
{error, not_found} -> ok;
L when is_list(L) ->
[update_task(DfsScript, Id, Force, ScriptType)
|| #task{id = Id, group_leader = Lead} <- L, Lead == false],
ok
end;
{{ok, _}, _} -> ok;
{Error, _} -> Error
end,
Out.
maybe_update(DfsScript, T = #task{}, true, ScriptType) ->
update(DfsScript, T, ScriptType);
maybe_update(DfsScript, T = #task{dfs = DFS}, false, ScriptType) ->
case erlang:crc32(DfsScript) =:= erlang:crc32(DFS) of
true -> {ok, no_update};
false -> update(DfsScript, T, ScriptType)
end.
-spec update(list()|binary(), #task{}, atom()) -> ok|{error, term()}.
update(DfsScript, Task, ScriptType) ->
case eval_dfs(DfsScript, ScriptType) of
{DFS, Map} when is_map(Map) ->
NewTask = Task#task{
definition = Map,
dfs = DFS,
date = faxe_time:now_date()},
flow_changed({flow , Task#task.name , update } ) ,
faxe_db:save_task(NewTask);
Err -> Err
end.
-spec update_running(list()|binary(), #task{}, true|false, atom()) -> ok|{error, term()}.
update_running(DfsScript, Task = #task{id = TId, pid = TPid}, Force, ScriptType) ->
case maybe_update(DfsScript, Task, Force, ScriptType) of
{ok, no_update} -> {ok, no_update};
{error, Err} -> {error, Err};
ok ->
erlang:monitor(process, TPid),
stop_task(Task#task.id, false),
receive
{'DOWN', _MonitorRef, process, TPid, _Info} ->
start_task(TId, Task#task.permanent), ok
after 5000 ->
catch erlang:demonitor(TPid, true), {error, updated_task_start_timeout}
end
end.
-spec eval_dfs(list()|binary(), file|data) ->
{DFSString :: list(), GraphDefinition :: map()} | {error, term()}.
eval_dfs(DfsScript, Type) ->
try faxe_dfs:Type(DfsScript, []) of
{_DFSString, {error, What}} -> {error, What};
{error, What} -> {error, What};
{_DFSString, Def} = Result when is_map(Def) -> Result;
E -> E
catch
throw : Err : Stacktrace - > { error , ;
exit : Err : Stacktrace - > { error , ;
error : Err : Stacktrace - > { error , ;
_:Err:Stacktrace ->
lager:warning("Error: ~p ~nstacktrace: ~p",[Err, Stacktrace]),
{error, Err}
end.
-spec get_running(integer()|binary()) -> {error, term()}|{true|false, #task{}}.
get_running(TaskId) ->
case faxe_db:get_task(TaskId) of
{error, Error} -> {error, Error};
T = #task{} ->
case is_task_alive(T) of
true -> {true, T};
false -> {false, T}
end
end.
get_file_dfs(DfsFile) ->
{ok, DfsParams} = application:get_env(faxe, dfs),
Path = proplists:get_value(script_path, DfsParams),
{ok, Data} = file:read_file(Path++DfsFile),
binary:replace(Data, <<"\\">>, <<>>, [global]).
start_file_temp(DfsScript, TTL) ->
start_temp(DfsScript, file, TTL).
start_temp(DfsScript, TTL) ->
start_temp(DfsScript, data, TTL).
start_temp(DfsScript, Type, TTL) ->
case eval_dfs(DfsScript, Type) of
{DFS, Def} when is_map(Def) ->
Id = list_to_binary(faxe_util:uuid_string()),
case dataflow:create_graph(Id, Def) of
{ok, Graph} ->
_Task = #task{
date = faxe_time:now_date(),
dfs = DFS,
definition = Def,
name = Id
},
ets:insert(temp_tasks, {Id, Graph}),
try df_graph:start_graph(Graph, #task_modes{temporary = true, temp_ttl = TTL}) of
_ ->
{ok, Id}
catch
_:E = E -> lager:error("graph_start_error: ~p",[E]),
{error, {graph_start_error, E}}
end;
{error, E} -> {error, E}
end;
{error, What} -> {error, What}
end.
start_task(TaskId) ->
start_task(TaskId, false).
start_task(TaskId, #task_modes{run_mode = _RunMode} = Mode) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, task_not_found};
T = #task{} -> graph_starter:start_graph(T, Mode), {ok, enqueued_to_start}
end;
start_task(TaskId, Permanent) when Permanent == true orelse Permanent == false ->
start_task(TaskId, push, Permanent).
-spec start_task(integer()|binary(), atom(), true|false) -> ok|{error, term()}.
start_task(TaskId, GraphRunMode, Permanent) ->
start_task(TaskId, #task_modes{run_mode = GraphRunMode, permanent = Permanent}).
do_start_task(T = # task{name = Name , definition = GraphDef } ,
# task_modes{concurrency = Concurrency , permanent = Perm } = Mode ) - >
case dataflow : create_graph(Name , GraphDef ) of
when > 1 - >
{ error , { already_started , _ Pid } } - > { error , already_started }
start_concurrent(Task = #task{}, #task_modes{concurrency = Con} = Mode) ->
F = fun(Num) -> start_copy(Task, Mode, Num) end,
lists:map(F, lists:seq(2, Con)).
start_copy(Task = #task{definition = GraphDef, name = TName}, #task_modes{permanent = Perm} = Mode, Num) ->
NumBin = integer_to_binary(Num),
Name = <<TName/binary, "--", NumBin/binary>>,
case faxe_db:get_task(Name) of
{error, not_found} ->
case dataflow:create_graph(Name, GraphDef) of
{ok, Graph} ->
try dataflow:start_graph(Graph, Mode) of
ok ->
faxe_db:save_task(
Task#task{
pid = Graph, name = Name,
id = undefined, group_leader = false,
last_start = faxe_time:now_date(),
permanent = Perm, group = TName})
catch
_:E = E ->
lager:error("graph_start_error: ~p",[E]),
{error, {graph_start_error, E}}
end;
{error, What} -> {error, What}
end;
T = #task{} -> graph_starter:start_graph(T#task{group_leader = false, group = TName}, Mode#task_modes{concurrency = 1})
end
.
-spec set_group_size(binary(), non_neg_integer()) -> ok|list().
set_group_size(GroupName, NewSize) when is_binary(GroupName), is_integer(NewSize) ->
case faxe_db:get_tasks_by_group(GroupName) of
{error, not_found} -> {error, group_not_found};
GroupList when is_list(GroupList) ->
Leader = get_group_leader(GroupList),
case is_task_alive(Leader) of
false -> {error, not_running};
true ->
RunningMembers = [T || T <- GroupList, is_task_alive(T)],
case NewSize - length(RunningMembers) of
start_concurrent(Leader,
#task_modes{concurrency = NewSize, permanent = Leader#task.permanent});
Num = abs(N1),
SB = byte_size(GroupName),
SortFun =
fun
(#task{name = <<GN:SB/binary, "--", Rank/binary>>},
#task{name = <<GN:SB/binary, "--", OtherRank/binary>>}) ->
binary_to_integer(Rank) > binary_to_integer(OtherRank);
(_, _) -> true
end,
Sorted = lists:sort(SortFun, RunningMembers),
del_group_members(Sorted, Num)
end
end
end.
del_group_members([], _) ->
[];
del_group_members(GroupList, 0) ->
GroupList;
del_group_members([#task{group_leader = true} | R], Num) ->
del_group_members(R, Num);
del_group_members([T=#task{group_leader = false, id = TaskId} | R], Num) ->
do_stop_task(T, false),
faxe_db:delete_task(TaskId),
del_group_members(R, Num - 1).
get_group_leader([]) ->
{error, group_leader_not_found};
get_group_leader([#task{group_leader = false} | R]) ->
get_group_leader(R);
get_group_leader([T=#task{group_leader = true} | _R]) ->
T.
-spec stop_task(integer()|binary()|#task{}) -> ok.
stop_task(_T=#task{pid = Graph}) when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:stop(Graph);
false -> {error, not_running}
end;
stop_task(TaskId) ->
stop_task(TaskId, false).
-spec stop_task(#task{}|integer()|binary(), true|false) -> ok.
stop_task(T = #task{}, Permanent) ->
do_stop_task(T, Permanent);
stop_task(TaskId, Permanent) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} = T when is_pid(Graph) -> do_stop_task(T, Permanent);
#task{} -> {error, not_running}
end.
stop_task_group(TaskGroupName, Permanent) ->
Tasks = faxe_db:get_tasks_by_group(TaskGroupName),
case Tasks of
{error, not_found} -> {error, not_found};
TaskList when is_list(TaskList) ->
[do_stop_task(T, Permanent) || T <- TaskList]
end.
stop_all() ->
Tasks = list_running_tasks(),
[stop_task(Task) || Task <- Tasks].
do_stop_task(T = #task{pid = Graph, group_leader = _Leader, group = _Group}, Permanent) ->
case is_task_alive(T) of
true ->
df_graph:stop(Graph),
NewT =
case Permanent of
true -> T#task{permanent = false};
false -> T
end,
Res = faxe_db:save_task(NewT#task{pid = undefined, last_stop = faxe_time:now_date()}),
Res;
case of
L when ) - >
false -> {error, not_running}
end.
-spec delete_task(binary()) -> ok | {error, not_found} | {error, task_is_running}.
delete_task(TaskId) ->
delete_task(TaskId, false).
-spec delete_task(binary(), true|false) -> ok | {error, not_found} | {error, task_is_running}.
delete_task(TaskId, Force) ->
case faxe_db:get_task(TaskId) of
{error, not_found} -> {error, not_found};
T = #task{} ->
case is_task_alive(T) of
true ->
case Force of
true ->
stop_task(T),
do_delete_task(T);
false -> {error, task_is_running}
end;
false -> do_delete_task(T)
end
end.
do_delete_task(#task{id = TaskId, group = Group, group_leader = Leader}) ->
case faxe_db:delete_task(TaskId) of
ok ->
case Leader of
true ->
delete_task_group(Group),
flow_changed({flow , TaskId , delete } ) ,
ok;
false -> ok
end;
Else -> Else
end.
delete_task_group(TaskGroupName) ->
Tasks = faxe_db:get_tasks_by_group(TaskGroupName),
case Tasks of
{error, not_found} -> {error, not_found};
TaskList when is_list(TaskList) ->
case lists:all(fun(#task{} = T) -> is_task_alive(T) == false end, TaskList) of
true -> [faxe_db:delete_task(T) || T <- TaskList];
false -> {error, tasks_are_running}
end
end.
delete_template(TaskId) ->
T = faxe_db:get_template(TaskId),
case T of
{error, not_found} -> ok;
#template{} ->
Res = faxe_db:delete_template(TaskId),
flow_changed({template , TaskId , delete } ) ,
Res
end.
reset_tasks() ->
stop_all(),
{atomic, ok} = faxe_db:reset_tasks(),
ok.
reset_templates() ->
stop_all(),
{atomic, ok} = faxe_db:reset_tasks(),
ok.
is_task_alive(#task{pid = Graph}) when is_pid(Graph) ->
is_process_alive(Graph) =:= true;
is_task_alive(_) -> false.
-spec ping_task(term()) -> {ok, NewTimeout::non_neg_integer()} | {error, term()}.
ping_task(TaskId) ->
case ets:lookup(temp_tasks, TaskId) of
[] -> {error, not_found};
[{TaskId, GraphPid}] -> df_graph:ping(GraphPid)
end.
get_stats(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:get_stats(Graph);
false -> {error, task_not_running}
end;
#task{} -> {ok, []}
end.
-spec start_trace(non_neg_integer()|binary(), non_neg_integer()|undefined) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
start_trace(TaskId, DrationMs) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:start_trace(Graph, trace_duration(DrationMs)),
{ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
trace_duration(undefined) ->
faxe_config:get(debug_time, 60000);
trace_duration(DurationMs) when is_integer(DurationMs) ->
DurationMs.
-spec stop_trace(non_neg_integer()|binary()) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
stop_trace(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:stop_trace(Graph), {ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
-spec start_metrics_trace(non_neg_integer()|binary(), undefined|non_neg_integer()) ->
{ok, pid()} | {error, not_found} | {error_task_not_running}.
start_metrics_trace(TaskId, DurationMs) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true ->
df_graph:start_metrics_trace(Graph, trace_duration(DurationMs)),
{ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
-spec stop_metrics_trace(non_neg_integer()|binary()) -> {ok, pid()} | {error, not_found} | {error_task_not_running}.
stop_metrics_trace(TaskId) ->
T = faxe_db:get_task(TaskId),
case T of
{error, not_found} -> {error, not_found};
#task{pid = Graph} when is_pid(Graph) ->
case is_process_alive(Graph) of
true -> df_graph:stop_metrics_trace(Graph), {ok, Graph};
false -> {error, task_not_running}
end;
#task{} -> {error, task_not_running}
end.
-spec template_to_task(#template{}, binary(), map()) -> ok | {error, term()}.
template_to_task(Template = #template{dfs = DFS}, TaskName, Vars) ->
{DFSString, Def} = faxe_dfs:data(DFS, Vars),
case Def of
_ when is_map(Def) ->
Task = #task{
date = faxe_time:now_date(),
definition = Def,
dfs = DFSString,
name = TaskName,
template = Template#template.name,
template_vars = Vars
},
Res = faxe_db:save_task(Task),
flow_changed({flow , TaskName , register } ) ,
Res;
{error, What} -> {error, What}
end.
flow_changed({Type, Affected, Method}) ->
Msg = #data_point{ts = faxe_time:now(),
fields = #{<<"type">> => Type, <<"affected">> => Affected, <<"method">> => Method}},
gen_event:notify(flow_changed, Msg). |
926dcd828142024f166c2d8ce972a9b88e13a1a954c00093a8b58255159322a4 | LuKC1024/stacker | io.rkt | #lang plait
(define-type-alias Id Symbol)
(define-type Constant
(c-void)
(c-str [it : String])
(c-num [it : Number])
(c-bool [it : Boolean])
(c-char [it : Char])
(c-vec [it : (Listof Constant)])
(c-list [it : (Listof Constant)]))
(define-type-alias Program ((Listof Def) * (Listof Expr)))
(define (program d* e*) (pair d* e*))
(define-type Def
[d-fun [fun : Id] [arg* : (Listof Id)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr]]
[d-var [var : Id] [val : Expr]])
(define-type Expr
(e-con [c : Constant])
(e-var [x : Id])
(e-fun [arg* : (Listof Id)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-app [fun : Expr] [arg* : (Listof Expr)])
(e-let [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-let* [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-letrec [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-set! [var : Id] [val : Expr])
(e-begin [prelude* : (Listof Expr)] [result : Expr])
(e-if [cnd : Expr] [thn : Expr] [els : Expr])
(e-cond [cnd-thn* : (Listof (Expr * Expr))] [els : (Optionof Expr)]))
(define (bind x e) (values x e))
(define-type-alias Bind (Id * Expr))
(define (var-of-bind bind) (fst bind))
(define (val-of-bind bind) (snd bind))
(define-type Obs
(o-void)
(o-con [it : Constant])
(o-vec [it : (Vectorof Obs)])
(o-list [it : (Listof Obs)])
(o-fun [it : (Optionof String)])
(o-rec [id : Number] [content : Obs])
(o-var [id : Number])
(o-exn [it : String]))
| null | https://raw.githubusercontent.com/LuKC1024/stacker/46ccb39d3326c13fc7b0e65f4bb4253b9b71edd8/io.rkt | racket | #lang plait
(define-type-alias Id Symbol)
(define-type Constant
(c-void)
(c-str [it : String])
(c-num [it : Number])
(c-bool [it : Boolean])
(c-char [it : Char])
(c-vec [it : (Listof Constant)])
(c-list [it : (Listof Constant)]))
(define-type-alias Program ((Listof Def) * (Listof Expr)))
(define (program d* e*) (pair d* e*))
(define-type Def
[d-fun [fun : Id] [arg* : (Listof Id)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr]]
[d-var [var : Id] [val : Expr]])
(define-type Expr
(e-con [c : Constant])
(e-var [x : Id])
(e-fun [arg* : (Listof Id)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-app [fun : Expr] [arg* : (Listof Expr)])
(e-let [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-let* [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-letrec [bind* : (Listof Bind)]
[def* : (Listof Def)]
[prelude* : (Listof Expr)]
[result : Expr])
(e-set! [var : Id] [val : Expr])
(e-begin [prelude* : (Listof Expr)] [result : Expr])
(e-if [cnd : Expr] [thn : Expr] [els : Expr])
(e-cond [cnd-thn* : (Listof (Expr * Expr))] [els : (Optionof Expr)]))
(define (bind x e) (values x e))
(define-type-alias Bind (Id * Expr))
(define (var-of-bind bind) (fst bind))
(define (val-of-bind bind) (snd bind))
(define-type Obs
(o-void)
(o-con [it : Constant])
(o-vec [it : (Vectorof Obs)])
(o-list [it : (Listof Obs)])
(o-fun [it : (Optionof String)])
(o-rec [id : Number] [content : Obs])
(o-var [id : Number])
(o-exn [it : String]))
| |
0d35824b4ba8c62aee673508405631db8da51676d7af640b0c346b2168ea5f1d | JustusAdam/language-haskell | Role.hs | SYNTAX TEST " source.haskell " " Role annotations "
data A n r p where
type role A nominal representational phantom
^^^^ keyword.other.type.haskell
-- ^^^^ keyword.other.role.haskell
^ storage.type.haskell
-- ^^^^^^^ keyword.other.role.nominal.haskell
-- ^^^^^^^^^^^^^^^^ keyword.other.role.representational.haskell
-- ^^^^^^^ keyword.other.role.phantom.haskell
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.role-annotation.haskell
type role A
^^^^ keyword.other.type.haskell
-- ^^^^ keyword.other.role.haskell
^ storage.type.haskell
nominal
-- ^^^^^^^ keyword.other.role.nominal.haskell
representational
phantom
-- ^^^^^^^ keyword.other.role.phantom.haskell
type role
^^^^ keyword.other.type.haskell
-- ^^^^ keyword.other.role.haskell
(:&)
^^ storage.type.operator.haskell
nominal
-- ^^^^^^^ keyword.other.role.nominal.haskell
representational
-- ^^^^^^^^^^^^^^^^ keyword.other.role.representational.haskell
phantom
-- ^^^^^^^ keyword.other.role.phantom.haskell
| null | https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tests/Role.hs | haskell | ^^^^ keyword.other.role.haskell
^^^^^^^ keyword.other.role.nominal.haskell
^^^^^^^^^^^^^^^^ keyword.other.role.representational.haskell
^^^^^^^ keyword.other.role.phantom.haskell
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.role-annotation.haskell
^^^^ keyword.other.role.haskell
^^^^^^^ keyword.other.role.nominal.haskell
^^^^^^^ keyword.other.role.phantom.haskell
^^^^ keyword.other.role.haskell
^^^^^^^ keyword.other.role.nominal.haskell
^^^^^^^^^^^^^^^^ keyword.other.role.representational.haskell
^^^^^^^ keyword.other.role.phantom.haskell | SYNTAX TEST " source.haskell " " Role annotations "
data A n r p where
type role A nominal representational phantom
^^^^ keyword.other.type.haskell
^ storage.type.haskell
type role A
^^^^ keyword.other.type.haskell
^ storage.type.haskell
nominal
representational
phantom
type role
^^^^ keyword.other.type.haskell
(:&)
^^ storage.type.operator.haskell
nominal
representational
phantom
|
c389bdee5323b5cca27a0d09c0a7bf861ba23749c73f8da55a193830081a50c3 | jacekschae/learn-pedestal-course-files | user.clj | (ns user
(:require [io.pedestal.http :as http]))
(defonce system-ref (atom nil))
(defn start-dev []
(reset! system-ref
(-> {::http/routes #{}
::http/type :jetty
::http/join? false
::http/port 3000}
(http/create-server)
(http/start)))
:started)
(defn stop-dev []
(http/stop @system-ref)
:stopped)
(defn restart-dev []
(stop-dev)
(start-dev)
:restarted)
(comment
(start-dev)
(restart-dev)
(stop-dev)
) | null | https://raw.githubusercontent.com/jacekschae/learn-pedestal-course-files/fa60a8f208e80658a4c55f0c094b66f68a2d3c6a/increments/08-routes/src/dev/user.clj | clojure | (ns user
(:require [io.pedestal.http :as http]))
(defonce system-ref (atom nil))
(defn start-dev []
(reset! system-ref
(-> {::http/routes #{}
::http/type :jetty
::http/join? false
::http/port 3000}
(http/create-server)
(http/start)))
:started)
(defn stop-dev []
(http/stop @system-ref)
:stopped)
(defn restart-dev []
(stop-dev)
(start-dev)
:restarted)
(comment
(start-dev)
(restart-dev)
(stop-dev)
) | |
1a840ed1da29b382379f1113b7b0d9193719fd772f718626811110f4a418772b | tari3x/csec-modex | piauth.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* and *
* *
* Copyright ( C ) INRIA , LIENS , 2000 - 2009 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet and Xavier Allamigeon *
* *
* Copyright (C) INRIA, LIENS, MPII 2000-2009 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val solve_auth : Types.reduction list -> Pitypes.query list -> unit
| null | https://raw.githubusercontent.com/tari3x/csec-modex/5ab2aa18ef308b4d18ac479e5ab14476328a6a50/deps/proverif1.84/src/piauth.mli | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* and *
* *
* Copyright ( C ) INRIA , LIENS , 2000 - 2009 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet and Xavier Allamigeon *
* *
* Copyright (C) INRIA, LIENS, MPII 2000-2009 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val solve_auth : Types.reduction list -> Pitypes.query list -> unit
| |
8cc15ba42a114e2fb815783cd805f86250a73690492cdc6758a901c884106c8a | quil-lang/quilc | suite.lisp | ;;;; tests/suite.lisp
;;;;
Author :
(in-package #:libquilc-tests)
(defun clean-up ()
(uiop:with-current-directory ("lib/")
(uiop:run-program '("make" "clean")))
(uiop:with-current-directory ("lib/tests/c/")
(uiop:run-program '("make" "clean"))))
(defun run-libquilc-tests (&key (verbose nil) (headless nil))
"Run all libquilc tests. If VERBOSE is T, print out lots of test info. If HEADLESS is T, disable interactive debugging and quit on completion."
(setf fiasco::*test-run-standard-output* (make-broadcast-stream *standard-output*))
(cond
((null headless)
(run-package-tests :package ':libquilc-tests
:verbose verbose
:describe-failures t
:interactive t)
(clean-up))
(t
(let ((successp (run-package-tests :package ':libquilc-tests
:verbose t
:describe-failures t
:interactive nil)))
(clean-up)
(uiop:quit (if successp 0 1))))))
| null | https://raw.githubusercontent.com/quil-lang/quilc/5f70950681008fd0dc345d574b8d293c5a638d5d/lib/tests/suite.lisp | lisp | tests/suite.lisp
| Author :
(in-package #:libquilc-tests)
(defun clean-up ()
(uiop:with-current-directory ("lib/")
(uiop:run-program '("make" "clean")))
(uiop:with-current-directory ("lib/tests/c/")
(uiop:run-program '("make" "clean"))))
(defun run-libquilc-tests (&key (verbose nil) (headless nil))
"Run all libquilc tests. If VERBOSE is T, print out lots of test info. If HEADLESS is T, disable interactive debugging and quit on completion."
(setf fiasco::*test-run-standard-output* (make-broadcast-stream *standard-output*))
(cond
((null headless)
(run-package-tests :package ':libquilc-tests
:verbose verbose
:describe-failures t
:interactive t)
(clean-up))
(t
(let ((successp (run-package-tests :package ':libquilc-tests
:verbose t
:describe-failures t
:interactive nil)))
(clean-up)
(uiop:quit (if successp 0 1))))))
|
39d521b311838c7479ff0c57fb428e26192d4e5c16a2e46989efbc67e288c777 | GU-CLASP/TypedFlow | Layers.hs |
module TypedFlow.Layers
(module TypedFlow.Layers.Core
,module TypedFlow.Layers.RNN
) where
import TypedFlow.Layers.Core
import TypedFlow.Layers.RNN
| null | https://raw.githubusercontent.com/GU-CLASP/TypedFlow/a8591151ddfa94b4ef9ea7d1d3e24f1339c1e764/TypedFlow/Layers.hs | haskell |
module TypedFlow.Layers
(module TypedFlow.Layers.Core
,module TypedFlow.Layers.RNN
) where
import TypedFlow.Layers.Core
import TypedFlow.Layers.RNN
| |
83d2d06d7fed2c4fe6919bd7cc7641b5556f701b48c4a8e792693a4306b1a010 | spechub/Hets | incmpl.hs |
data Boolx = Minx | Plusx
data Natx a = Zx | Sx a | SSx (Natx a) Boolx
map1 :: Natx Int -> (Int -> Int) -> Natx Int
map1 x = \ f -> case x of
Zx -> Sx (f 0)
Sx n -> Sx (f n)
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/Haskell/test/HOLCF/incmpl.hs | haskell |
data Boolx = Minx | Plusx
data Natx a = Zx | Sx a | SSx (Natx a) Boolx
map1 :: Natx Int -> (Int -> Int) -> Natx Int
map1 x = \ f -> case x of
Zx -> Sx (f 0)
Sx n -> Sx (f n)
| |
cf772952273654e883827edf1721ee95d103cfcc910adf3caf5242656e921335 | mransan/ocaml-protoc | example04.ml | open Example04_types
open Example04_pp
let ( @+ ) value next = Cons { value; next }
let () =
let l = 1 @+ 2 @+ 3 @+ 4 @+ 5 @+ Nil in
Format.(fprintf std_formatter "l = %a\n" pp_int_list l)
| null | https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/examples/example04.ml | ocaml | open Example04_types
open Example04_pp
let ( @+ ) value next = Cons { value; next }
let () =
let l = 1 @+ 2 @+ 3 @+ 4 @+ 5 @+ Nil in
Format.(fprintf std_formatter "l = %a\n" pp_int_list l)
| |
777e99f1d05368d5db599fe95bc707d050f4e93b1634d30843c5853a4bb341c1 | matijapretnar/eff | desugarer.ml | (** Desugaring of syntax into the core language. *)
open Utils
open Language
module Sugared = SugaredSyntax
module Untyped = UntypedSyntax
module T = Type
type constructor_kind = Variant of bool | Effect of bool
This is so OCaml does n't complain about :
Error ( warning 37 ): constructor Effect is never used to build values .
Error (warning 37): constructor Effect is never used to build values. *)
let _ = Effect true
module StringMap = Map.Make (String)
let add_unique ~loc kind str symb string_map =
StringMap.update str
(function
| None -> Some symb
| Some _ -> Error.syntax ~loc "%s %s defined multiple times." kind str)
string_map
type state = {
context : Term.Variable.t StringMap.t;
effect_symbols : Effect.t StringMap.t;
field_symbols : Type.Field.t StringMap.t;
tyname_symbols : (TyName.t * (Type.TyParam.t * variance) list) StringMap.t;
constructors : (Type.Label.t * constructor_kind) StringMap.t;
local_type_annotations : (Type.TyParam.t * Type.ty) StringMap.t;
inlined_types : Type.ty StringMap.t;
}
let initial_state =
let constructors =
StringMap.empty
|> StringMap.add Type.cons_annot (Type.cons, Variant true)
|> StringMap.add Type.nil_annot (Type.nil, Variant false)
and tyname_symbols =
StringMap.empty
|> StringMap.add "bool" (Type.bool_tyname, [])
|> StringMap.add "int" (Type.int_tyname, [])
|> StringMap.add "unit" (Type.unit_tyname, [])
|> StringMap.add "string" (Type.string_tyname, [])
|> StringMap.add "float" (Type.float_tyname, [])
|> StringMap.add "list"
(Type.list_tyname, [ (Type.list_ty_param, Covariant) ])
|> StringMap.add "empty" (Type.empty_tyname, [])
and inlined_types =
StringMap.empty
|> StringMap.add "bool" Type.bool_ty
|> StringMap.add "int" Type.int_ty
|> StringMap.add "unit" Type.unit_ty
|> StringMap.add "string" Type.string_ty
|> StringMap.add "float" Type.float_ty
in
{
context = StringMap.empty;
effect_symbols = StringMap.empty;
field_symbols = StringMap.empty;
tyname_symbols;
constructors;
local_type_annotations = StringMap.empty;
inlined_types;
}
let add_variables vars state =
let context' = StringMap.fold StringMap.add vars state.context in
{ state with context = context' }
let add_unique_variables ~loc vars context =
StringMap.fold (add_unique ~loc "Variable") vars context
let add_loc t loc = { it = t; at = loc }
let effect_to_symbol ~loc state name =
match StringMap.find_opt name state.effect_symbols with
| Some sym -> (state, sym)
| None -> Error.syntax ~loc "Unknown effect %s" name
let field_to_symbol ~loc state name =
match StringMap.find_opt name state.field_symbols with
| Some sym -> (state, sym)
| None -> Error.syntax ~loc "Unknown field %s" name
let tyname_to_symbol ~loc state name =
match StringMap.find_opt name state.tyname_symbols with
| Some sym -> sym
| None -> Error.syntax ~loc "Unknown type %s" name
let force_param ty =
match ty.term with Type.TyParam t -> t | _ -> failwith "Cant get param"
(* ***** Desugaring of types. ***** *)
a type , where only the given type , dirt and region parameters may appear .
If a type application with missing dirt and region parameters is encountered ,
it uses [ ds ] and [ rs ] instead . This is used in desugaring of recursive type definitions
where we need to figure out which type and dirt parameters are missing in a type defnition .
Also , it relies on the optional region parameter in [ T.Apply ] to figure out whether
an application applies to an effect type . So , it is prudent to call [ fill_args ] before
calling [ ty ] .
If a type application with missing dirt and region parameters is encountered,
it uses [ds] and [rs] instead. This is used in desugaring of recursive type definitions
where we need to figure out which type and dirt parameters are missing in a type defnition.
Also, it relies on the optional region parameter in [T.Apply] to figure out whether
an application applies to an effect type. So, it is prudent to call [fill_args] before
calling [ty].
*)
let desugar_type type_sbst state =
let rec desugar_type state { it = t; at = loc } =
match t with
| Sugared.TyApply (t, tys) -> (
let t', lst = tyname_to_symbol ~loc state t in
let n = List.length lst in
if List.length tys <> n then
Error.syntax ~loc "Type %t expects %d arguments" (TyName.print t') n;
match StringMap.find_opt t state.inlined_types with
| Some ty -> (state, ty)
| None ->
let t', lst = tyname_to_symbol ~loc state t in
let n = List.length lst in
if List.length tys <> n then
Error.syntax ~loc "Type %t expects %d arguments" (TyName.print t')
n
else
let state', tys' = List.fold_map desugar_type state tys in
let type_info =
lst
|> List.map2
(fun ty (param, variance) -> (param, (ty, variance)))
tys'
in
(state', T.apply (t', Type.TyParam.Map.of_bindings type_info)))
| Sugared.TyParam t -> (
match StringMap.find_opt t type_sbst with
| None -> Error.syntax ~loc "Unbound type parameter '%s" t
| Some (_, ty, _) -> (state, ty))
| Sugared.TyArrow (t1, t2) ->
let state', t1' = desugar_type state t1 in
let state'', t2' = desugar_dirty_type state' t2 in
(state'', T.arrow (t1', t2'))
| Sugared.TyTuple lst ->
let state', lst' = List.fold_map desugar_type state lst in
(state', T.tuple lst')
| Sugared.TyHandler (t1, t2) ->
let state', t1' = desugar_dirty_type state t1 in
let state'', t2' = desugar_dirty_type state' t2 in
(state'', T.handler (t1', t2'))
and desugar_dirty_type state ty =
let state', ty' = desugar_type state ty in
(state', T.make_dirty ty')
in
desugar_type state
(** [free_type_params t] returns all free type params in [t]. *)
let free_type_params t =
let rec ty_params { it = t; at = _loc } =
match t with
| Sugared.TyApply (_, tys) -> List.map ty_params tys |> List.flatten
| Sugared.TyParam s -> [ s ]
| Sugared.TyArrow (t1, t2) -> ty_params t1 @ ty_params t2
| Sugared.TyTuple lst -> List.map ty_params lst |> List.flatten
| Sugared.TyHandler (t1, t2) -> ty_params t1 @ ty_params t2
in
List.unique_elements (ty_params t)
let fresh_ty_param () =
let ty = Type.fresh_ty_with_fresh_skel () in
let param = force_param ty in
(param, ty)
let syntax_to_core_params ts =
let core_params =
ts
|> List.map (fun (p, variance) ->
let param, ty = fresh_ty_param () in
(p, (param, ty, variance)))
in
core_params |> List.to_seq |> StringMap.of_seq
* [ desugar_tydef state params def ] desugars the type definition with parameters
[ params ] and definition [ def ] .
[params] and definition [def]. *)
let desugar_tydef ~loc state
(ty_sbst : (T.TyParam.t * T.ty * variance) StringMap.t) ty_name def =
let state', def' =
match def with
| Sugared.TyRecord flds ->
let field_desugar st (f, t) =
let f' = Type.Field.fresh f in
let st', t' = desugar_type ty_sbst st t in
let st'' =
{
st' with
field_symbols = add_unique ~loc "Field" f f' st'.field_symbols;
}
in
(st'', (f', t'))
in
let state', flds' = Assoc.kfold_map field_desugar state flds in
let flds' = Type.Field.Map.of_bindings (Assoc.to_list flds') in
(state', Type.Record flds')
| Sugared.TySum assoc ->
let aux (st, sum_def) (lbl, ty) =
let lbl' = Type.Label.fresh lbl in
let st', ty', kind =
match ty with
| None -> (st, None, Variant false)
| Some ty ->
let st, ty = desugar_type ty_sbst st ty in
(st, Some ty, Variant true)
in
let st'' =
{
st' with
constructors =
add_unique ~loc "Constructor" lbl (lbl', kind) st'.constructors;
}
in
let sum_def' = Type.Field.Map.add lbl' ty' sum_def in
(st'', sum_def')
in
let state', sum_def' =
Assoc.fold_left aux (state, Type.Field.Map.empty) assoc
in
(state', Type.Sum sum_def')
| Sugared.TyInline t ->
let state', t' = desugar_type ty_sbst state t in
let state'' =
{
state' with
inlined_types = StringMap.add ty_name t' state'.inlined_types;
}
in
(state'', Type.Inline t')
in
let ty_params =
ty_sbst |> StringMap.bindings
|> List.map (fun (_, (param, ty, variance)) -> (param, (ty.ty, variance)))
|> Type.TyParam.Map.of_bindings
in
let ty_params =
{
Type.type_params = ty_params;
dirt_params = Dirt.Param.Set.empty;
skel_params =
Type.TyParam.Map.fold
(fun _ (skeleton, _) skels ->
Skeleton.Param.Set.union
(skeleton |> Type.free_params_skeleton).skel_params skels)
ty_params Skeleton.Param.Set.empty;
}
in
(state', { Type.params = ty_params; type_def = def' })
* [ ] desugars the simultaneous type definitions [ defs ] .
let desugar_tydefs ~loc (state : state) sugared_defs =
let add_ty_names
(tyname_symbols :
(TyName.t * (Type.TyParam.t * variance) list) StringMap.t)
(name, (params, tydef)) =
let sym = TyName.fresh name in
let ty_sbst = syntax_to_core_params params in
let ty_param_subs =
params
|> List.map (fun (pname, _) ->
ty_sbst |> StringMap.find pname |> fun (_, ty, variance) ->
(force_param ty, variance))
in
( add_unique ~loc "Type" name (sym, ty_param_subs) tyname_symbols,
(name, (ty_sbst, tydef)) )
in
let tyname_symbols, sugared_defs =
Assoc.kfold_map add_ty_names state.tyname_symbols sugared_defs
in
let state' = { state with tyname_symbols } in
let desugar_fold st (name, (params, def)) =
First desugar the type names
let sym, _ = StringMap.find name st.tyname_symbols in
(* Then the types themselves *)
let st', tydef = desugar_tydef ~loc st params name def in
(st', (sym, tydef))
in
Assoc.kfold_map desugar_fold state' sugared_defs
(* ***** Desugaring of expressions and computations. ***** *)
(** [fresh_var opt] creates a fresh variable on each call *)
let fresh_var = function
| None -> Term.Variable.fresh "$anon"
| Some x -> Term.Variable.fresh x
let id_abstraction loc =
let x = fresh_var (Some "$id_par") in
( add_loc (Untyped.PVar x) loc,
add_loc (Untyped.Value (add_loc (Untyped.Var x) loc)) loc )
let desugar_pattern state p =
let vars = ref StringMap.empty in
let rec desugar_pattern state { it = p; at = loc } =
let state', p' =
match p with
| Sugared.PVar x ->
let x' = fresh_var (Some x) in
let state' =
{ state with context = StringMap.add x x' state.context }
in
vars := add_unique ~loc "Variable" x x' !vars;
(state', Untyped.PVar x')
| Sugared.PAnnotated (p, t) ->
let bind bound_ps p =
match StringMap.find_opt p bound_ps with
| Some _ty_param -> bound_ps
| None -> StringMap.add p (fresh_ty_param ()) bound_ps
in
let free_params = free_type_params t in
let bound_params = state.local_type_annotations in
let bound_params' = List.fold_left bind bound_params free_params in
let state' = { state with local_type_annotations = bound_params' } in
let state'', p' = desugar_pattern state' p in
let state''', t' =
desugar_type
(bound_params' |> StringMap.map (fun (p, t) -> (p, t, Invariant)))
state'' t
in
(state''', Untyped.PAnnotated (p', t'))
| Sugared.PAs (p, x) ->
let x' = fresh_var (Some x) in
let state' =
{ state with context = StringMap.add x x' state.context }
in
vars := add_unique ~loc "Variable" x x' !vars;
let state'', p' = desugar_pattern state' p in
(state'', Untyped.PAs (p', x'))
| Sugared.PTuple ps ->
let state', ps' = List.fold_map desugar_pattern state ps in
(state', Untyped.PTuple ps')
| Sugared.PRecord flds ->
let field_desugar st (f, p) =
let st', f' = field_to_symbol ~loc st f in
let st'', p' = desugar_pattern st' p in
(st'', (f', p'))
in
let state', flds' = Assoc.kfold_map field_desugar state flds in
let flds' = flds' |> Assoc.to_list |> Type.Field.Map.of_bindings in
(state', Untyped.PRecord flds')
| Sugared.PVariant (lbl, p) -> (
match StringMap.find_opt lbl state.constructors with
| None -> Error.typing ~loc "Unbound constructor %s" lbl
| Some (cons_lbl, Variant var) -> (
match (var, p) with
| true, Some p ->
let state', p' = desugar_pattern state p in
(state', Untyped.PVariant (cons_lbl, Some p'))
| false, None -> (state, Untyped.PVariant (cons_lbl, None))
| true, None ->
Error.typing ~loc
"Constructor %s should be applied to an argument." lbl
| false, Some _ ->
Error.typing ~loc
"Constructor %s cannot be applied to an argument." lbl)
| Some (_cons_lbl, Effect _eff) ->
Error.typing ~loc
"Constructor %s should not be an effect constructor." lbl)
| Sugared.PConst c -> (state, Untyped.PConst c)
| Sugared.PNonbinding -> (state, Untyped.PNonbinding)
in
(state', add_loc p' loc)
in
let state', p' = desugar_pattern state p in
(state', !vars, p')
Desugaring functions below return a list of bindings and the desugared form .
let rec desugar_expression state { it = t; at = loc } =
let state', w, e =
match t with
| Sugared.Var x -> (
match StringMap.find_opt x state.context with
| Some n -> (state, [], Untyped.Var n)
| None -> Error.typing ~loc "Unknown variable %s" x)
| Sugared.Const k -> (state, [], Untyped.Const k)
| Sugared.Annotated (t, ty) ->
let bind bound_ps p =
match StringMap.find_opt p bound_ps with
| Some _ty_param -> bound_ps
| None -> StringMap.add p (fresh_ty_param ()) bound_ps
in
let free_params = free_type_params ty in
let bound_params = state.local_type_annotations in
let bound_params' = List.fold_left bind bound_params free_params in
let state' = { state with local_type_annotations = bound_params' } in
let state'', w, e = desugar_expression state' t in
let state''', ty' =
desugar_type
(bound_params' |> StringMap.map (fun (p, t) -> (p, t, Invariant)))
state'' ty
in
(state''', w, Untyped.Annotated (e, ty'))
| Sugared.Lambda a ->
let state', a' = desugar_abstraction state a in
(state', [], Untyped.Lambda a')
| Sugared.Function cs ->
let x = fresh_var (Some "$function") in
let state', cs' = List.fold_map desugar_abstraction state cs in
( state',
[],
Untyped.Lambda
( add_loc (Untyped.PVar x) loc,
add_loc (Untyped.Match (add_loc (Untyped.Var x) loc, cs')) loc )
)
| Sugared.Handler cs ->
let state', h' = desugar_handler loc state cs in
(state', [], Untyped.Handler h')
| Sugared.Tuple ts ->
let state', w, es = desugar_expressions state ts in
(state', w, Untyped.Tuple es)
| Sugared.Record ts ->
if not (List.no_duplicates (Assoc.keys_of ts)) then
Error.syntax ~loc "Fields in a record must be distinct";
let state', w, es = desugar_record_fields ~loc state ts in
(state', w, Untyped.Record es)
| Sugared.Variant (lbl, t) -> (
match StringMap.find_opt lbl state.constructors with
| None -> Error.typing ~loc "Unbound constructor %s" lbl
| Some (cons_lbl, Variant var) -> (
match (var, t) with
| true, Some t ->
let state', w, e = desugar_expression state t in
(state', w, Untyped.Variant (cons_lbl, Some e))
| false, None -> (state, [], Untyped.Variant (cons_lbl, None))
| true, None ->
Error.typing ~loc
"Constructor %s should be applied to an argument." lbl
| false, Some _ ->
Error.typing ~loc
"Constructor %s cannot be applied to an argument." lbl)
| Some (_cons_lbl, Effect _eff) ->
Error.typing ~loc
"Constructor %s should not be an effect constructor." lbl)
(* Terms that are desugared into computations. We list them explicitly in
order to catch any future constructs. *)
| Sugared.Apply _ | Sugared.Match _ | Sugared.Let _ | Sugared.LetRec _
| Sugared.Handle _ | Sugared.Conditional _ | Sugared.Check _
| Sugared.Effect _ ->
let x = fresh_var (Some "$bind") in
let state', c = desugar_computation state { it = t; at = loc } in
let w = [ (add_loc (Untyped.PVar x) loc, c) ] in
(state', w, Untyped.Var x)
in
(state', w, add_loc e loc)
and desugar_computation state { it = t; at = loc } =
let if_then_else e c1 c2 =
let true_p = add_loc (Untyped.PConst Const.of_true) c1.at in
let false_p = add_loc (Untyped.PConst Const.of_false) c2.at in
Untyped.Match (e, [ (true_p, c1); (false_p, c2) ])
in
let state', w, c =
match t with
| Sugared.Apply
( {
it = Sugared.Apply ({ it = Sugared.Var "&&"; at = _loc1 }, t1);
at = loc2;
},
t2 ) ->
let state', w1, e1 = desugar_expression state t1 in
let untyped_false loc = add_loc (Untyped.Const Const.of_false) loc in
let state'', c1 = desugar_computation state' t2 in
let c2 = add_loc (Untyped.Value (untyped_false loc2)) loc2 in
(state'', w1, if_then_else e1 c1 c2)
| Sugared.Apply
( {
it = Sugared.Apply ({ it = Sugared.Var "||"; at = _loc1 }, t1);
at = loc2;
},
t2 ) ->
let state', w1, e1 = desugar_expression state t1 in
let untyped_true loc = add_loc (Untyped.Const Const.of_true) loc in
let c1 = add_loc (Untyped.Value (untyped_true loc2)) loc2 in
let state'', c2 = desugar_computation state' t2 in
(state'', w1, if_then_else e1 c1 c2)
| Sugared.Apply (t1, t2) ->
let state', w1, e1 = desugar_expression state t1 in
let state'', w2, e2 = desugar_expression state' t2 in
(state'', w1 @ w2, Untyped.Apply (e1, e2))
| Sugared.Effect (eff, t) -> (
match StringMap.find_opt eff state.effect_symbols with
| Some eff' ->
let state', w, e = desugar_expression state t in
let loc_eff = add_loc (Untyped.Effect eff') loc in
(state', w, Untyped.Apply (loc_eff, e))
| None -> Error.typing ~loc "Unknown operation %s" eff)
| Sugared.Match (t, cs) -> match_constructor state loc t cs
| Sugared.Handle (t1, t2) ->
let state', w1, e1 = desugar_expression state t1 in
let state'', c2 = desugar_computation state' t2 in
(state'', w1, Untyped.Handle (e1, c2))
| Sugared.Conditional (t, t1, t2) ->
let state', w, e = desugar_expression state t in
let state'', c1 = desugar_computation state' t1 in
let state''', c2 = desugar_computation state'' t2 in
(state''', w, if_then_else e c1 c2)
| Sugared.Check t ->
let state', c = desugar_computation state t in
(state', [], Untyped.Check c)
| Sugared.Let (defs, t) ->
let aux_desugar (p, c) (new_vars, defs) =
let state', p_vars, p' = desugar_pattern state p in
let _, c' =
desugar_computation { state' with context = state.context } c
in
(add_unique_variables ~loc p_vars new_vars, (p', c') :: defs)
in
let new_vars, defs' =
List.fold_right aux_desugar defs (StringMap.empty, [])
in
let _, c = desugar_computation (add_variables new_vars state) t in
(state, [], Untyped.Let (defs', c))
| Sugared.LetRec (defs, t) ->
let aux_desugar (x, _) (fold_state, ns) =
let n = fresh_var (Some x) in
( { state with context = StringMap.add x n fold_state.context },
n :: ns )
in
let state', ns = List.fold_right aux_desugar defs (state, []) in
let desugar_defs (p, (_, c)) defs =
let _, c = desugar_let_rec state' c in
(p, c) :: defs
in
let defs' = List.fold_right desugar_defs (List.combine ns defs) [] in
let _, c = desugar_computation state' t in
(state, [], Untyped.LetRec (defs', c))
(* The remaining cases are expressions, which we list explicitly to catch any
future changes. *)
| Sugared.Var _ | Sugared.Const _ | Sugared.Annotated _ | Sugared.Tuple _
| Sugared.Record _ | Sugared.Variant _ | Sugared.Lambda _
| Sugared.Function _ | Sugared.Handler _ ->
let state', w, e = desugar_expression state { it = t; at = loc } in
(state', w, Untyped.Value e)
in
match w with
| [] -> (state', add_loc c loc)
| _ :: _ -> (state', add_loc (Untyped.Let (w, add_loc c loc)) loc)
and desugar_abstraction state (p, t) =
let old_context = state.context in
let state', p_vars, p' = desugar_pattern state p in
let state'' = add_variables p_vars state' in
let state''', c = desugar_computation state'' t in
({ state''' with context = old_context }, (p', c))
and desugar_abstraction2 state (p1, p2, t) =
let old_context = state.context in
let state', p_vars1, p1' = desugar_pattern state p1 in
let state'', p_vars2, p2' = desugar_pattern state' p2 in
let state''' = state'' |> add_variables p_vars1 |> add_variables p_vars2 in
let state'''', t' = desugar_computation state''' t in
({ state'''' with context = old_context }, (p1', p2', t'))
and desugar_let_rec state { it = exp; at = loc } =
match exp with
| Sugared.Lambda a -> desugar_abstraction state a
| Sugared.Function cs ->
let x = fresh_var (Some "$let_rec_function") in
let state', cs = List.fold_map desugar_abstraction state cs in
let new_match = Untyped.Match (add_loc (Untyped.Var x) loc, cs) in
(state', (add_loc (Untyped.PVar x) loc, add_loc new_match loc))
| _ ->
Error.syntax ~loc
"This kind of expression is not allowed in a recursive definition"
and desugar_expressions state = function
| [] -> (state, [], [])
| t :: ts ->
let state', w, e = desugar_expression state t in
let state'', ws, es = desugar_expressions state' ts in
(state'', w @ ws, e :: es)
and desugar_record_fields ~loc state flds =
Assoc.fold_right
(fun (fld, t) (st, ws, mp) ->
let state', fld' = field_to_symbol ~loc st fld in
let state'', w, e = desugar_expression state' t in
(state'', w @ ws, Type.Field.Map.add fld' e mp))
flds
(state, [], Type.Field.Map.empty)
and desugar_handler loc state
{
Sugared.effect_clauses = eff_cs;
Sugared.value_clause = val_cs;
Sugared.finally_clause = fin_cs;
} =
Construct a desugared handler with match statements .
let group_eff_cs (eff, a2) assoc =
match Assoc.lookup eff assoc with
| None -> Assoc.update eff [ a2 ] assoc
| Some a2s -> Assoc.replace eff (a2 :: a2s) assoc
in
let construct_eff_clause state (eff, eff_cs_lst) =
transform string name to Effect.t
let state', eff' = effect_to_symbol ~loc state eff in
match eff_cs_lst with
| [] -> assert false
| [ a2 ] ->
let state'', a2' = desugar_abstraction2 state' a2 in
(state'', (eff', a2'))
| a2s ->
let x = fresh_var (Some "$eff_param") in
let k = fresh_var (Some "$continuation") in
let x_k_vars =
Untyped.Tuple
[ add_loc (Untyped.Var x) loc; add_loc (Untyped.Var k) loc ]
in
let match_term_fun state =
let aux st a2 =
let st', (p1', p2', t') = desugar_abstraction2 st a2 in
(st', (add_loc (Untyped.PTuple [ p1'; p2' ]) loc, t'))
in
let state', a2s' = List.fold_map aux state a2s in
(state', add_loc (Untyped.Match (add_loc x_k_vars loc, a2s')) loc)
in
let p1, p2 = (Untyped.PVar x, Untyped.PVar k) in
let state'', match_term = match_term_fun state' in
let new_eff_cs = (eff', (add_loc p1 loc, add_loc p2 loc, match_term)) in
(state'', new_eff_cs)
in
group eff cases by effects into lumps to transform into matches
let collected_eff_cs = Assoc.fold_right group_eff_cs eff_cs Assoc.empty in
construct match cases for effects with more than one pattern
let state', untyped_eff_cs =
Assoc.kfold_map construct_eff_clause state collected_eff_cs
in
(* construct match case for value *)
let state'', untyped_val_a =
match val_cs with
| [] -> (state', id_abstraction loc)
| cs ->
let v = fresh_var (Some "$val_param") in
let v_var = add_loc (Untyped.Var v) loc in
let state'', cs = List.fold_map desugar_abstraction state' cs in
( state'',
(add_loc (Untyped.PVar v) loc, add_loc (Untyped.Match (v_var, cs)) loc)
)
in
(* construct match case for finally clause *)
let state''', untyped_fin_a =
match fin_cs with
| [] -> (state'', id_abstraction loc)
| cs ->
let fin = fresh_var (Some "$fin_param") in
let fin_var = add_loc (Untyped.Var fin) loc in
let state''', cs' = List.fold_map desugar_abstraction state cs in
( state''',
( add_loc (Untyped.PVar fin) loc,
add_loc (Untyped.Match (fin_var, cs')) loc ) )
in
( state''',
{
Untyped.effect_clauses = untyped_eff_cs;
Untyped.value_clause = untyped_val_a;
Untyped.finally_clause = untyped_fin_a;
} )
and match_constructor state loc t cs =
(* Separate value and effect cases. *)
let val_cs, eff_cs = separate_match_cases cs in
match eff_cs with
| [] ->
let state', w, e = desugar_expression state t in
let state'', val_cs' = List.fold_map desugar_abstraction state' val_cs in
(state'', w, Untyped.Match (e, val_cs'))
| _ ->
let val_cs = List.map (fun cs -> Sugared.Val_match cs) val_cs in
let x = "$id_par" in
let value_match =
add_loc (Sugared.Match (add_loc (Sugared.Var x) loc, val_cs)) loc
in
let h_value_clause = (add_loc (Sugared.PVar x) loc, value_match) in
let sugared_h =
{
Sugared.effect_clauses = Assoc.of_list eff_cs;
Sugared.value_clause = [ h_value_clause ];
Sugared.finally_clause = [];
}
in
let state', c = desugar_computation state t in
let state'', h = desugar_handler loc state' sugared_h in
let loc_h = { it = Untyped.Handler h; at = loc } in
(state'', [], Untyped.Handle (loc_h, c))
and separate_match_cases cs =
let separator case (val_cs, eff_cs) =
match case with
| Sugared.Val_match v_cs -> (v_cs :: val_cs, eff_cs)
| Sugared.Eff_match e_cs -> (val_cs, e_cs :: eff_cs)
in
List.fold_right separator cs ([], [])
let desugar_top_let ~loc state defs =
let aux_desugar (p, c) (new_vars, defs) =
let state', p_vars, p' = desugar_pattern state p in
let _, c' = desugar_computation { state' with context = state.context } c in
(add_unique_variables ~loc p_vars new_vars, (p', c') :: defs)
in
let new_vars, defs' =
List.fold_right aux_desugar defs (StringMap.empty, [])
in
(add_variables new_vars state, defs')
let desugar_top_let_rec state defs =
let aux_desugar (x, t) (vars, ns) =
let n = fresh_var (Some x) in
(add_unique ~loc:t.at "Variable" x n vars, n :: ns)
in
let vars, ns = List.fold_right aux_desugar defs (StringMap.empty, []) in
let state' = add_variables vars state in
let desugar_defs (p, (_, c)) defs =
let _, c = desugar_let_rec state' c in
(p, c) :: defs
in
let defs' = List.fold_right desugar_defs (List.combine ns defs) [] in
(state', defs')
let load_primitive_value state x prim =
{
state with
context =
StringMap.add (Primitives.primitive_value_name prim) x state.context;
}
let load_primitive_effect state eff prim =
{
state with
effect_symbols =
StringMap.add
(Primitives.primitive_effect_name prim)
eff state.effect_symbols;
}
let desugar_def_effect ~loc state (eff, (ty1, ty2)) =
let eff' = Effect.fresh eff in
let state' =
{
state with
effect_symbols = add_unique ~loc "Effect" eff eff' state.effect_symbols;
}
in
let state'', ty1' = desugar_type StringMap.empty state' ty1 in
let state''', ty2' = desugar_type StringMap.empty state'' ty2 in
(state''', (eff', (ty1', ty2')))
| null | https://raw.githubusercontent.com/matijapretnar/eff/1be07f0c7fbaadf5c28437bf11fe818aa76640e7/src/02-parser/desugarer.ml | ocaml | * Desugaring of syntax into the core language.
***** Desugaring of types. *****
* [free_type_params t] returns all free type params in [t].
Then the types themselves
***** Desugaring of expressions and computations. *****
* [fresh_var opt] creates a fresh variable on each call
Terms that are desugared into computations. We list them explicitly in
order to catch any future constructs.
The remaining cases are expressions, which we list explicitly to catch any
future changes.
construct match case for value
construct match case for finally clause
Separate value and effect cases. |
open Utils
open Language
module Sugared = SugaredSyntax
module Untyped = UntypedSyntax
module T = Type
type constructor_kind = Variant of bool | Effect of bool
This is so OCaml does n't complain about :
Error ( warning 37 ): constructor Effect is never used to build values .
Error (warning 37): constructor Effect is never used to build values. *)
let _ = Effect true
module StringMap = Map.Make (String)
let add_unique ~loc kind str symb string_map =
StringMap.update str
(function
| None -> Some symb
| Some _ -> Error.syntax ~loc "%s %s defined multiple times." kind str)
string_map
type state = {
context : Term.Variable.t StringMap.t;
effect_symbols : Effect.t StringMap.t;
field_symbols : Type.Field.t StringMap.t;
tyname_symbols : (TyName.t * (Type.TyParam.t * variance) list) StringMap.t;
constructors : (Type.Label.t * constructor_kind) StringMap.t;
local_type_annotations : (Type.TyParam.t * Type.ty) StringMap.t;
inlined_types : Type.ty StringMap.t;
}
let initial_state =
let constructors =
StringMap.empty
|> StringMap.add Type.cons_annot (Type.cons, Variant true)
|> StringMap.add Type.nil_annot (Type.nil, Variant false)
and tyname_symbols =
StringMap.empty
|> StringMap.add "bool" (Type.bool_tyname, [])
|> StringMap.add "int" (Type.int_tyname, [])
|> StringMap.add "unit" (Type.unit_tyname, [])
|> StringMap.add "string" (Type.string_tyname, [])
|> StringMap.add "float" (Type.float_tyname, [])
|> StringMap.add "list"
(Type.list_tyname, [ (Type.list_ty_param, Covariant) ])
|> StringMap.add "empty" (Type.empty_tyname, [])
and inlined_types =
StringMap.empty
|> StringMap.add "bool" Type.bool_ty
|> StringMap.add "int" Type.int_ty
|> StringMap.add "unit" Type.unit_ty
|> StringMap.add "string" Type.string_ty
|> StringMap.add "float" Type.float_ty
in
{
context = StringMap.empty;
effect_symbols = StringMap.empty;
field_symbols = StringMap.empty;
tyname_symbols;
constructors;
local_type_annotations = StringMap.empty;
inlined_types;
}
let add_variables vars state =
let context' = StringMap.fold StringMap.add vars state.context in
{ state with context = context' }
let add_unique_variables ~loc vars context =
StringMap.fold (add_unique ~loc "Variable") vars context
let add_loc t loc = { it = t; at = loc }
let effect_to_symbol ~loc state name =
match StringMap.find_opt name state.effect_symbols with
| Some sym -> (state, sym)
| None -> Error.syntax ~loc "Unknown effect %s" name
let field_to_symbol ~loc state name =
match StringMap.find_opt name state.field_symbols with
| Some sym -> (state, sym)
| None -> Error.syntax ~loc "Unknown field %s" name
let tyname_to_symbol ~loc state name =
match StringMap.find_opt name state.tyname_symbols with
| Some sym -> sym
| None -> Error.syntax ~loc "Unknown type %s" name
let force_param ty =
match ty.term with Type.TyParam t -> t | _ -> failwith "Cant get param"
a type , where only the given type , dirt and region parameters may appear .
If a type application with missing dirt and region parameters is encountered ,
it uses [ ds ] and [ rs ] instead . This is used in desugaring of recursive type definitions
where we need to figure out which type and dirt parameters are missing in a type defnition .
Also , it relies on the optional region parameter in [ T.Apply ] to figure out whether
an application applies to an effect type . So , it is prudent to call [ fill_args ] before
calling [ ty ] .
If a type application with missing dirt and region parameters is encountered,
it uses [ds] and [rs] instead. This is used in desugaring of recursive type definitions
where we need to figure out which type and dirt parameters are missing in a type defnition.
Also, it relies on the optional region parameter in [T.Apply] to figure out whether
an application applies to an effect type. So, it is prudent to call [fill_args] before
calling [ty].
*)
let desugar_type type_sbst state =
let rec desugar_type state { it = t; at = loc } =
match t with
| Sugared.TyApply (t, tys) -> (
let t', lst = tyname_to_symbol ~loc state t in
let n = List.length lst in
if List.length tys <> n then
Error.syntax ~loc "Type %t expects %d arguments" (TyName.print t') n;
match StringMap.find_opt t state.inlined_types with
| Some ty -> (state, ty)
| None ->
let t', lst = tyname_to_symbol ~loc state t in
let n = List.length lst in
if List.length tys <> n then
Error.syntax ~loc "Type %t expects %d arguments" (TyName.print t')
n
else
let state', tys' = List.fold_map desugar_type state tys in
let type_info =
lst
|> List.map2
(fun ty (param, variance) -> (param, (ty, variance)))
tys'
in
(state', T.apply (t', Type.TyParam.Map.of_bindings type_info)))
| Sugared.TyParam t -> (
match StringMap.find_opt t type_sbst with
| None -> Error.syntax ~loc "Unbound type parameter '%s" t
| Some (_, ty, _) -> (state, ty))
| Sugared.TyArrow (t1, t2) ->
let state', t1' = desugar_type state t1 in
let state'', t2' = desugar_dirty_type state' t2 in
(state'', T.arrow (t1', t2'))
| Sugared.TyTuple lst ->
let state', lst' = List.fold_map desugar_type state lst in
(state', T.tuple lst')
| Sugared.TyHandler (t1, t2) ->
let state', t1' = desugar_dirty_type state t1 in
let state'', t2' = desugar_dirty_type state' t2 in
(state'', T.handler (t1', t2'))
and desugar_dirty_type state ty =
let state', ty' = desugar_type state ty in
(state', T.make_dirty ty')
in
desugar_type state
let free_type_params t =
let rec ty_params { it = t; at = _loc } =
match t with
| Sugared.TyApply (_, tys) -> List.map ty_params tys |> List.flatten
| Sugared.TyParam s -> [ s ]
| Sugared.TyArrow (t1, t2) -> ty_params t1 @ ty_params t2
| Sugared.TyTuple lst -> List.map ty_params lst |> List.flatten
| Sugared.TyHandler (t1, t2) -> ty_params t1 @ ty_params t2
in
List.unique_elements (ty_params t)
let fresh_ty_param () =
let ty = Type.fresh_ty_with_fresh_skel () in
let param = force_param ty in
(param, ty)
let syntax_to_core_params ts =
let core_params =
ts
|> List.map (fun (p, variance) ->
let param, ty = fresh_ty_param () in
(p, (param, ty, variance)))
in
core_params |> List.to_seq |> StringMap.of_seq
* [ desugar_tydef state params def ] desugars the type definition with parameters
[ params ] and definition [ def ] .
[params] and definition [def]. *)
let desugar_tydef ~loc state
(ty_sbst : (T.TyParam.t * T.ty * variance) StringMap.t) ty_name def =
let state', def' =
match def with
| Sugared.TyRecord flds ->
let field_desugar st (f, t) =
let f' = Type.Field.fresh f in
let st', t' = desugar_type ty_sbst st t in
let st'' =
{
st' with
field_symbols = add_unique ~loc "Field" f f' st'.field_symbols;
}
in
(st'', (f', t'))
in
let state', flds' = Assoc.kfold_map field_desugar state flds in
let flds' = Type.Field.Map.of_bindings (Assoc.to_list flds') in
(state', Type.Record flds')
| Sugared.TySum assoc ->
let aux (st, sum_def) (lbl, ty) =
let lbl' = Type.Label.fresh lbl in
let st', ty', kind =
match ty with
| None -> (st, None, Variant false)
| Some ty ->
let st, ty = desugar_type ty_sbst st ty in
(st, Some ty, Variant true)
in
let st'' =
{
st' with
constructors =
add_unique ~loc "Constructor" lbl (lbl', kind) st'.constructors;
}
in
let sum_def' = Type.Field.Map.add lbl' ty' sum_def in
(st'', sum_def')
in
let state', sum_def' =
Assoc.fold_left aux (state, Type.Field.Map.empty) assoc
in
(state', Type.Sum sum_def')
| Sugared.TyInline t ->
let state', t' = desugar_type ty_sbst state t in
let state'' =
{
state' with
inlined_types = StringMap.add ty_name t' state'.inlined_types;
}
in
(state'', Type.Inline t')
in
let ty_params =
ty_sbst |> StringMap.bindings
|> List.map (fun (_, (param, ty, variance)) -> (param, (ty.ty, variance)))
|> Type.TyParam.Map.of_bindings
in
let ty_params =
{
Type.type_params = ty_params;
dirt_params = Dirt.Param.Set.empty;
skel_params =
Type.TyParam.Map.fold
(fun _ (skeleton, _) skels ->
Skeleton.Param.Set.union
(skeleton |> Type.free_params_skeleton).skel_params skels)
ty_params Skeleton.Param.Set.empty;
}
in
(state', { Type.params = ty_params; type_def = def' })
* [ ] desugars the simultaneous type definitions [ defs ] .
let desugar_tydefs ~loc (state : state) sugared_defs =
let add_ty_names
(tyname_symbols :
(TyName.t * (Type.TyParam.t * variance) list) StringMap.t)
(name, (params, tydef)) =
let sym = TyName.fresh name in
let ty_sbst = syntax_to_core_params params in
let ty_param_subs =
params
|> List.map (fun (pname, _) ->
ty_sbst |> StringMap.find pname |> fun (_, ty, variance) ->
(force_param ty, variance))
in
( add_unique ~loc "Type" name (sym, ty_param_subs) tyname_symbols,
(name, (ty_sbst, tydef)) )
in
let tyname_symbols, sugared_defs =
Assoc.kfold_map add_ty_names state.tyname_symbols sugared_defs
in
let state' = { state with tyname_symbols } in
let desugar_fold st (name, (params, def)) =
First desugar the type names
let sym, _ = StringMap.find name st.tyname_symbols in
let st', tydef = desugar_tydef ~loc st params name def in
(st', (sym, tydef))
in
Assoc.kfold_map desugar_fold state' sugared_defs
let fresh_var = function
| None -> Term.Variable.fresh "$anon"
| Some x -> Term.Variable.fresh x
let id_abstraction loc =
let x = fresh_var (Some "$id_par") in
( add_loc (Untyped.PVar x) loc,
add_loc (Untyped.Value (add_loc (Untyped.Var x) loc)) loc )
let desugar_pattern state p =
let vars = ref StringMap.empty in
let rec desugar_pattern state { it = p; at = loc } =
let state', p' =
match p with
| Sugared.PVar x ->
let x' = fresh_var (Some x) in
let state' =
{ state with context = StringMap.add x x' state.context }
in
vars := add_unique ~loc "Variable" x x' !vars;
(state', Untyped.PVar x')
| Sugared.PAnnotated (p, t) ->
let bind bound_ps p =
match StringMap.find_opt p bound_ps with
| Some _ty_param -> bound_ps
| None -> StringMap.add p (fresh_ty_param ()) bound_ps
in
let free_params = free_type_params t in
let bound_params = state.local_type_annotations in
let bound_params' = List.fold_left bind bound_params free_params in
let state' = { state with local_type_annotations = bound_params' } in
let state'', p' = desugar_pattern state' p in
let state''', t' =
desugar_type
(bound_params' |> StringMap.map (fun (p, t) -> (p, t, Invariant)))
state'' t
in
(state''', Untyped.PAnnotated (p', t'))
| Sugared.PAs (p, x) ->
let x' = fresh_var (Some x) in
let state' =
{ state with context = StringMap.add x x' state.context }
in
vars := add_unique ~loc "Variable" x x' !vars;
let state'', p' = desugar_pattern state' p in
(state'', Untyped.PAs (p', x'))
| Sugared.PTuple ps ->
let state', ps' = List.fold_map desugar_pattern state ps in
(state', Untyped.PTuple ps')
| Sugared.PRecord flds ->
let field_desugar st (f, p) =
let st', f' = field_to_symbol ~loc st f in
let st'', p' = desugar_pattern st' p in
(st'', (f', p'))
in
let state', flds' = Assoc.kfold_map field_desugar state flds in
let flds' = flds' |> Assoc.to_list |> Type.Field.Map.of_bindings in
(state', Untyped.PRecord flds')
| Sugared.PVariant (lbl, p) -> (
match StringMap.find_opt lbl state.constructors with
| None -> Error.typing ~loc "Unbound constructor %s" lbl
| Some (cons_lbl, Variant var) -> (
match (var, p) with
| true, Some p ->
let state', p' = desugar_pattern state p in
(state', Untyped.PVariant (cons_lbl, Some p'))
| false, None -> (state, Untyped.PVariant (cons_lbl, None))
| true, None ->
Error.typing ~loc
"Constructor %s should be applied to an argument." lbl
| false, Some _ ->
Error.typing ~loc
"Constructor %s cannot be applied to an argument." lbl)
| Some (_cons_lbl, Effect _eff) ->
Error.typing ~loc
"Constructor %s should not be an effect constructor." lbl)
| Sugared.PConst c -> (state, Untyped.PConst c)
| Sugared.PNonbinding -> (state, Untyped.PNonbinding)
in
(state', add_loc p' loc)
in
let state', p' = desugar_pattern state p in
(state', !vars, p')
Desugaring functions below return a list of bindings and the desugared form .
let rec desugar_expression state { it = t; at = loc } =
let state', w, e =
match t with
| Sugared.Var x -> (
match StringMap.find_opt x state.context with
| Some n -> (state, [], Untyped.Var n)
| None -> Error.typing ~loc "Unknown variable %s" x)
| Sugared.Const k -> (state, [], Untyped.Const k)
| Sugared.Annotated (t, ty) ->
let bind bound_ps p =
match StringMap.find_opt p bound_ps with
| Some _ty_param -> bound_ps
| None -> StringMap.add p (fresh_ty_param ()) bound_ps
in
let free_params = free_type_params ty in
let bound_params = state.local_type_annotations in
let bound_params' = List.fold_left bind bound_params free_params in
let state' = { state with local_type_annotations = bound_params' } in
let state'', w, e = desugar_expression state' t in
let state''', ty' =
desugar_type
(bound_params' |> StringMap.map (fun (p, t) -> (p, t, Invariant)))
state'' ty
in
(state''', w, Untyped.Annotated (e, ty'))
| Sugared.Lambda a ->
let state', a' = desugar_abstraction state a in
(state', [], Untyped.Lambda a')
| Sugared.Function cs ->
let x = fresh_var (Some "$function") in
let state', cs' = List.fold_map desugar_abstraction state cs in
( state',
[],
Untyped.Lambda
( add_loc (Untyped.PVar x) loc,
add_loc (Untyped.Match (add_loc (Untyped.Var x) loc, cs')) loc )
)
| Sugared.Handler cs ->
let state', h' = desugar_handler loc state cs in
(state', [], Untyped.Handler h')
| Sugared.Tuple ts ->
let state', w, es = desugar_expressions state ts in
(state', w, Untyped.Tuple es)
| Sugared.Record ts ->
if not (List.no_duplicates (Assoc.keys_of ts)) then
Error.syntax ~loc "Fields in a record must be distinct";
let state', w, es = desugar_record_fields ~loc state ts in
(state', w, Untyped.Record es)
| Sugared.Variant (lbl, t) -> (
match StringMap.find_opt lbl state.constructors with
| None -> Error.typing ~loc "Unbound constructor %s" lbl
| Some (cons_lbl, Variant var) -> (
match (var, t) with
| true, Some t ->
let state', w, e = desugar_expression state t in
(state', w, Untyped.Variant (cons_lbl, Some e))
| false, None -> (state, [], Untyped.Variant (cons_lbl, None))
| true, None ->
Error.typing ~loc
"Constructor %s should be applied to an argument." lbl
| false, Some _ ->
Error.typing ~loc
"Constructor %s cannot be applied to an argument." lbl)
| Some (_cons_lbl, Effect _eff) ->
Error.typing ~loc
"Constructor %s should not be an effect constructor." lbl)
| Sugared.Apply _ | Sugared.Match _ | Sugared.Let _ | Sugared.LetRec _
| Sugared.Handle _ | Sugared.Conditional _ | Sugared.Check _
| Sugared.Effect _ ->
let x = fresh_var (Some "$bind") in
let state', c = desugar_computation state { it = t; at = loc } in
let w = [ (add_loc (Untyped.PVar x) loc, c) ] in
(state', w, Untyped.Var x)
in
(state', w, add_loc e loc)
and desugar_computation state { it = t; at = loc } =
let if_then_else e c1 c2 =
let true_p = add_loc (Untyped.PConst Const.of_true) c1.at in
let false_p = add_loc (Untyped.PConst Const.of_false) c2.at in
Untyped.Match (e, [ (true_p, c1); (false_p, c2) ])
in
let state', w, c =
match t with
| Sugared.Apply
( {
it = Sugared.Apply ({ it = Sugared.Var "&&"; at = _loc1 }, t1);
at = loc2;
},
t2 ) ->
let state', w1, e1 = desugar_expression state t1 in
let untyped_false loc = add_loc (Untyped.Const Const.of_false) loc in
let state'', c1 = desugar_computation state' t2 in
let c2 = add_loc (Untyped.Value (untyped_false loc2)) loc2 in
(state'', w1, if_then_else e1 c1 c2)
| Sugared.Apply
( {
it = Sugared.Apply ({ it = Sugared.Var "||"; at = _loc1 }, t1);
at = loc2;
},
t2 ) ->
let state', w1, e1 = desugar_expression state t1 in
let untyped_true loc = add_loc (Untyped.Const Const.of_true) loc in
let c1 = add_loc (Untyped.Value (untyped_true loc2)) loc2 in
let state'', c2 = desugar_computation state' t2 in
(state'', w1, if_then_else e1 c1 c2)
| Sugared.Apply (t1, t2) ->
let state', w1, e1 = desugar_expression state t1 in
let state'', w2, e2 = desugar_expression state' t2 in
(state'', w1 @ w2, Untyped.Apply (e1, e2))
| Sugared.Effect (eff, t) -> (
match StringMap.find_opt eff state.effect_symbols with
| Some eff' ->
let state', w, e = desugar_expression state t in
let loc_eff = add_loc (Untyped.Effect eff') loc in
(state', w, Untyped.Apply (loc_eff, e))
| None -> Error.typing ~loc "Unknown operation %s" eff)
| Sugared.Match (t, cs) -> match_constructor state loc t cs
| Sugared.Handle (t1, t2) ->
let state', w1, e1 = desugar_expression state t1 in
let state'', c2 = desugar_computation state' t2 in
(state'', w1, Untyped.Handle (e1, c2))
| Sugared.Conditional (t, t1, t2) ->
let state', w, e = desugar_expression state t in
let state'', c1 = desugar_computation state' t1 in
let state''', c2 = desugar_computation state'' t2 in
(state''', w, if_then_else e c1 c2)
| Sugared.Check t ->
let state', c = desugar_computation state t in
(state', [], Untyped.Check c)
| Sugared.Let (defs, t) ->
let aux_desugar (p, c) (new_vars, defs) =
let state', p_vars, p' = desugar_pattern state p in
let _, c' =
desugar_computation { state' with context = state.context } c
in
(add_unique_variables ~loc p_vars new_vars, (p', c') :: defs)
in
let new_vars, defs' =
List.fold_right aux_desugar defs (StringMap.empty, [])
in
let _, c = desugar_computation (add_variables new_vars state) t in
(state, [], Untyped.Let (defs', c))
| Sugared.LetRec (defs, t) ->
let aux_desugar (x, _) (fold_state, ns) =
let n = fresh_var (Some x) in
( { state with context = StringMap.add x n fold_state.context },
n :: ns )
in
let state', ns = List.fold_right aux_desugar defs (state, []) in
let desugar_defs (p, (_, c)) defs =
let _, c = desugar_let_rec state' c in
(p, c) :: defs
in
let defs' = List.fold_right desugar_defs (List.combine ns defs) [] in
let _, c = desugar_computation state' t in
(state, [], Untyped.LetRec (defs', c))
| Sugared.Var _ | Sugared.Const _ | Sugared.Annotated _ | Sugared.Tuple _
| Sugared.Record _ | Sugared.Variant _ | Sugared.Lambda _
| Sugared.Function _ | Sugared.Handler _ ->
let state', w, e = desugar_expression state { it = t; at = loc } in
(state', w, Untyped.Value e)
in
match w with
| [] -> (state', add_loc c loc)
| _ :: _ -> (state', add_loc (Untyped.Let (w, add_loc c loc)) loc)
and desugar_abstraction state (p, t) =
let old_context = state.context in
let state', p_vars, p' = desugar_pattern state p in
let state'' = add_variables p_vars state' in
let state''', c = desugar_computation state'' t in
({ state''' with context = old_context }, (p', c))
and desugar_abstraction2 state (p1, p2, t) =
let old_context = state.context in
let state', p_vars1, p1' = desugar_pattern state p1 in
let state'', p_vars2, p2' = desugar_pattern state' p2 in
let state''' = state'' |> add_variables p_vars1 |> add_variables p_vars2 in
let state'''', t' = desugar_computation state''' t in
({ state'''' with context = old_context }, (p1', p2', t'))
and desugar_let_rec state { it = exp; at = loc } =
match exp with
| Sugared.Lambda a -> desugar_abstraction state a
| Sugared.Function cs ->
let x = fresh_var (Some "$let_rec_function") in
let state', cs = List.fold_map desugar_abstraction state cs in
let new_match = Untyped.Match (add_loc (Untyped.Var x) loc, cs) in
(state', (add_loc (Untyped.PVar x) loc, add_loc new_match loc))
| _ ->
Error.syntax ~loc
"This kind of expression is not allowed in a recursive definition"
and desugar_expressions state = function
| [] -> (state, [], [])
| t :: ts ->
let state', w, e = desugar_expression state t in
let state'', ws, es = desugar_expressions state' ts in
(state'', w @ ws, e :: es)
and desugar_record_fields ~loc state flds =
Assoc.fold_right
(fun (fld, t) (st, ws, mp) ->
let state', fld' = field_to_symbol ~loc st fld in
let state'', w, e = desugar_expression state' t in
(state'', w @ ws, Type.Field.Map.add fld' e mp))
flds
(state, [], Type.Field.Map.empty)
and desugar_handler loc state
{
Sugared.effect_clauses = eff_cs;
Sugared.value_clause = val_cs;
Sugared.finally_clause = fin_cs;
} =
Construct a desugared handler with match statements .
let group_eff_cs (eff, a2) assoc =
match Assoc.lookup eff assoc with
| None -> Assoc.update eff [ a2 ] assoc
| Some a2s -> Assoc.replace eff (a2 :: a2s) assoc
in
let construct_eff_clause state (eff, eff_cs_lst) =
transform string name to Effect.t
let state', eff' = effect_to_symbol ~loc state eff in
match eff_cs_lst with
| [] -> assert false
| [ a2 ] ->
let state'', a2' = desugar_abstraction2 state' a2 in
(state'', (eff', a2'))
| a2s ->
let x = fresh_var (Some "$eff_param") in
let k = fresh_var (Some "$continuation") in
let x_k_vars =
Untyped.Tuple
[ add_loc (Untyped.Var x) loc; add_loc (Untyped.Var k) loc ]
in
let match_term_fun state =
let aux st a2 =
let st', (p1', p2', t') = desugar_abstraction2 st a2 in
(st', (add_loc (Untyped.PTuple [ p1'; p2' ]) loc, t'))
in
let state', a2s' = List.fold_map aux state a2s in
(state', add_loc (Untyped.Match (add_loc x_k_vars loc, a2s')) loc)
in
let p1, p2 = (Untyped.PVar x, Untyped.PVar k) in
let state'', match_term = match_term_fun state' in
let new_eff_cs = (eff', (add_loc p1 loc, add_loc p2 loc, match_term)) in
(state'', new_eff_cs)
in
group eff cases by effects into lumps to transform into matches
let collected_eff_cs = Assoc.fold_right group_eff_cs eff_cs Assoc.empty in
construct match cases for effects with more than one pattern
let state', untyped_eff_cs =
Assoc.kfold_map construct_eff_clause state collected_eff_cs
in
let state'', untyped_val_a =
match val_cs with
| [] -> (state', id_abstraction loc)
| cs ->
let v = fresh_var (Some "$val_param") in
let v_var = add_loc (Untyped.Var v) loc in
let state'', cs = List.fold_map desugar_abstraction state' cs in
( state'',
(add_loc (Untyped.PVar v) loc, add_loc (Untyped.Match (v_var, cs)) loc)
)
in
let state''', untyped_fin_a =
match fin_cs with
| [] -> (state'', id_abstraction loc)
| cs ->
let fin = fresh_var (Some "$fin_param") in
let fin_var = add_loc (Untyped.Var fin) loc in
let state''', cs' = List.fold_map desugar_abstraction state cs in
( state''',
( add_loc (Untyped.PVar fin) loc,
add_loc (Untyped.Match (fin_var, cs')) loc ) )
in
( state''',
{
Untyped.effect_clauses = untyped_eff_cs;
Untyped.value_clause = untyped_val_a;
Untyped.finally_clause = untyped_fin_a;
} )
and match_constructor state loc t cs =
let val_cs, eff_cs = separate_match_cases cs in
match eff_cs with
| [] ->
let state', w, e = desugar_expression state t in
let state'', val_cs' = List.fold_map desugar_abstraction state' val_cs in
(state'', w, Untyped.Match (e, val_cs'))
| _ ->
let val_cs = List.map (fun cs -> Sugared.Val_match cs) val_cs in
let x = "$id_par" in
let value_match =
add_loc (Sugared.Match (add_loc (Sugared.Var x) loc, val_cs)) loc
in
let h_value_clause = (add_loc (Sugared.PVar x) loc, value_match) in
let sugared_h =
{
Sugared.effect_clauses = Assoc.of_list eff_cs;
Sugared.value_clause = [ h_value_clause ];
Sugared.finally_clause = [];
}
in
let state', c = desugar_computation state t in
let state'', h = desugar_handler loc state' sugared_h in
let loc_h = { it = Untyped.Handler h; at = loc } in
(state'', [], Untyped.Handle (loc_h, c))
and separate_match_cases cs =
let separator case (val_cs, eff_cs) =
match case with
| Sugared.Val_match v_cs -> (v_cs :: val_cs, eff_cs)
| Sugared.Eff_match e_cs -> (val_cs, e_cs :: eff_cs)
in
List.fold_right separator cs ([], [])
let desugar_top_let ~loc state defs =
let aux_desugar (p, c) (new_vars, defs) =
let state', p_vars, p' = desugar_pattern state p in
let _, c' = desugar_computation { state' with context = state.context } c in
(add_unique_variables ~loc p_vars new_vars, (p', c') :: defs)
in
let new_vars, defs' =
List.fold_right aux_desugar defs (StringMap.empty, [])
in
(add_variables new_vars state, defs')
let desugar_top_let_rec state defs =
let aux_desugar (x, t) (vars, ns) =
let n = fresh_var (Some x) in
(add_unique ~loc:t.at "Variable" x n vars, n :: ns)
in
let vars, ns = List.fold_right aux_desugar defs (StringMap.empty, []) in
let state' = add_variables vars state in
let desugar_defs (p, (_, c)) defs =
let _, c = desugar_let_rec state' c in
(p, c) :: defs
in
let defs' = List.fold_right desugar_defs (List.combine ns defs) [] in
(state', defs')
let load_primitive_value state x prim =
{
state with
context =
StringMap.add (Primitives.primitive_value_name prim) x state.context;
}
let load_primitive_effect state eff prim =
{
state with
effect_symbols =
StringMap.add
(Primitives.primitive_effect_name prim)
eff state.effect_symbols;
}
let desugar_def_effect ~loc state (eff, (ty1, ty2)) =
let eff' = Effect.fresh eff in
let state' =
{
state with
effect_symbols = add_unique ~loc "Effect" eff eff' state.effect_symbols;
}
in
let state'', ty1' = desugar_type StringMap.empty state' ty1 in
let state''', ty2' = desugar_type StringMap.empty state'' ty2 in
(state''', (eff', (ty1', ty2')))
|
aa18bc434d070a019028a35f8c85a95a8b3db28c7144f758237c77ac24e20bae | Andromedans/andromeda | matching.mli |
* Match a value against a pattern . Matches are returned in order of increasing de Bruijn index :
if we match the pattern [ ( x , y , z ) ] against the value [ ( " foo " , " bar " , " baz " ) ] , the list returned
will be [ [ " baz " , " bar " , " foo " ] ] .
if we match the pattern [(x,y,z)] against the value [("foo", "bar", "baz")], the list returned
will be [["baz", "bar", "foo"]]. *)
val match_pattern : Syntax.pattern -> Runtime.value -> Runtime.value list option Runtime.comp
* Match a value against a pattern . Matches are returned in the order of increasing de Bruijn index .
val top_match_pattern : Syntax.pattern -> Runtime.value -> Runtime.value list option Runtime.toplevel
(** [match_op_pattern ps p_out vs t_out] matches patterns [ps] against values [vs] and
the optional pattern [p_out] against the optional type [t_out]. *)
val match_op_pattern :
Syntax.pattern list -> Syntax.pattern option ->
Runtime.value list -> Nucleus.boundary_abstraction option ->
Runtime.value list option Runtime.comp
| null | https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/src/runtime/matching.mli | ocaml | * [match_op_pattern ps p_out vs t_out] matches patterns [ps] against values [vs] and
the optional pattern [p_out] against the optional type [t_out]. |
* Match a value against a pattern . Matches are returned in order of increasing de Bruijn index :
if we match the pattern [ ( x , y , z ) ] against the value [ ( " foo " , " bar " , " baz " ) ] , the list returned
will be [ [ " baz " , " bar " , " foo " ] ] .
if we match the pattern [(x,y,z)] against the value [("foo", "bar", "baz")], the list returned
will be [["baz", "bar", "foo"]]. *)
val match_pattern : Syntax.pattern -> Runtime.value -> Runtime.value list option Runtime.comp
* Match a value against a pattern . Matches are returned in the order of increasing de Bruijn index .
val top_match_pattern : Syntax.pattern -> Runtime.value -> Runtime.value list option Runtime.toplevel
val match_op_pattern :
Syntax.pattern list -> Syntax.pattern option ->
Runtime.value list -> Nucleus.boundary_abstraction option ->
Runtime.value list option Runtime.comp
|
32d66a6d3695ed7eb51696bf1fbc7df4f5903d83bd1eba5991a1a2a5bea77921 | reborg/clojure-essential-reference | 7.clj | (import '[java.util.concurrent LinkedBlockingQueue])
< 1 >
< 2 >
(let [out *out*]
(future
(binding [*out* out]
(dotimes [n 50]
(Thread/sleep 1000)
(println "buffer" (.size q)))))))
(defn lazy-scan [] ; <3>
(->> (java.io.File. "/")
file-seq
(map (memfn getPath))
(filter (by-type ".txt"))
(seque q)))
< 4 >
# object[clojure.core$future_call$reify__8454 0x4b672daa { : status : pending , : nil } ]
buffer 0
buffer 0
buffer 0
(go)
( " /usr / local / Homebrew / docs / robots.txt " ; < 5 >
" /usr / local / Homebrew / LICENSE.txt "
;; "/usr/local/var/homebrew/linked/z3/todo.txt"
" /usr / local / var / homebrew / linked / z3 / LICENSE.txt "
;; "/usr/local/var/homebrew/linked/z3/share/z3/examples/c++/CMakeLists.txt")
;; more?
buffer 544 ; < 6 >
buffer 745
buffer 745
buffer 749
buffer 749
;; ...
buffer 2000
buffer 2000
;; ... | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/SequentialCollections/seque/7.clj | clojure | <3>
< 5 >
"/usr/local/var/homebrew/linked/z3/todo.txt"
"/usr/local/var/homebrew/linked/z3/share/z3/examples/c++/CMakeLists.txt")
more?
< 6 >
...
... | (import '[java.util.concurrent LinkedBlockingQueue])
< 1 >
< 2 >
(let [out *out*]
(future
(binding [*out* out]
(dotimes [n 50]
(Thread/sleep 1000)
(println "buffer" (.size q)))))))
(->> (java.io.File. "/")
file-seq
(map (memfn getPath))
(filter (by-type ".txt"))
(seque q)))
< 4 >
# object[clojure.core$future_call$reify__8454 0x4b672daa { : status : pending , : nil } ]
buffer 0
buffer 0
buffer 0
(go)
" /usr / local / Homebrew / LICENSE.txt "
" /usr / local / var / homebrew / linked / z3 / LICENSE.txt "
buffer 745
buffer 745
buffer 749
buffer 749
buffer 2000
buffer 2000 |
e0937c555bbbb3537aaf2c7e7f4cab0dfa74d965f3af8dbf9f670b5d3a489ff9 | rbuchmann/samak | nodes.cljc | (ns samak.nodes
(:require [samak.protocols :as p]
[samak.api :as api]
[samak.pipes :as pipes]
[samak.tools :refer [fail log]]
[samak.trace :refer [*db-id*]]
[samak.code-db :as db]))
(def ^:dynamic *manager* nil)
(def ^:dynamic *builtins* {})
(defn compile-error
[& args]
(fail ["[" *db-id* "]"] args))
(defmulti eval-node ::type)
(defn eval-reordered [nodes]
(->> nodes
(sort-by :order)
(mapv (comp eval-node ::node))))
(def eval-vals (partial map (fn [[k v]] [(::value k) (eval-node v)])))
(defn ref? [m]
(and (map? m) (= (keys m) [:db/id])))
(defn unresolved-name? [value]
(and (vector? value)
(= 2 (count value))
(= ::name (first value))))
(defmethod eval-node nil [value]
(cond
(unresolved-name? value) (compile-error "Tried to eval unresolved name:"
(str "'" (second value) "'"))
(ref? value) (let [id (:db/id value)]
(or ((:resolve *manager*) id)
(compile-error "Referenced id " id " was undefined")))
:default (compile-error "unknown token during evaluation: " (str value))))
(defmethod eval-node ::module [{:keys [::definition] :as module}]
;; (println "evaling module: " module)
FIXME : also needs to make this stuff available for resolve ?
(fn []
FIXME
;; needs to prep resolve magic when instanciating pipes, to select same runtime
;; maybe simply do so explicitly
(println (str "about to eval module: " module))
(let [evaled (eval-node definition)]
(println (str "used module: " module "->" evaled))
evaled)))
(defmethod eval-node ::map [{:keys [::mapkv-pairs]}]
(reduce (fn [a {:keys [::mapkey ::mapvalue]}]
(assoc a (::value mapkey) (eval-node mapvalue)))
{}
mapkv-pairs))
(defmethod eval-node ::vector [{:keys [::children]}]
(-> children eval-reordered vec))
(defmethod eval-node ::integer [{:keys [::value]}] value)
(defmethod eval-node ::keyword [{:keys [::value]}] value)
(defmethod eval-node ::key-fn [{:keys [::value]}] (fn [x] (value x)))
(defmethod eval-node ::string [{:keys [::value]}] value)
(defmethod eval-node ::float [{:keys [::value]}] value)
(defmethod eval-node ::builtin [{:keys [::value]}] (get *builtins* value))
(defmethod eval-node ::def [{:keys [::rhs]}] (eval-node rhs))
(defmethod eval-node ::pipe [{:keys [::from ::to ::xf] :as p}]
(let [a (eval-node from)
b (when xf
(let [db-id (:db/id xf)]
(binding [*db-id* db-id]
(-> xf
eval-node
((partial pipes/instrument db-id (:cancel? *manager*)))
pipes/transduction-pipe))))
c (eval-node to)]
((:link *manager*) a c b)))
(defmethod eval-node ::fn-ref [{:keys [::fn] :as f}]
(or (when (api/is-def? fn) (eval-node fn))
((:resolve *manager*) (:db/id fn))
(compile-error "Undefined reference " fn " in " *manager*)))
(defmethod eval-node ::fn-call [{:keys [::fn-expression ::arguments]}]
(let [func (eval-node fn-expression)]
(try (apply (p/eval-as-fn func) (eval-reordered arguments))
(catch clojure.lang.ArityException ex
(compile-error "wrong args: " (eval-reordered arguments) " for fn " func " -> " ex)))))
(defmethod eval-node ::link [{:keys [::from ::to]}]
(pipes/link! (eval-node from) (eval-node to)))
(defn eval-env [manager builtins ast db-id]
(binding [*manager* manager
*builtins* builtins
*db-id* db-id]
(eval-node ast)))
| null | https://raw.githubusercontent.com/rbuchmann/samak/ab98d1a180ee02c6cd784962b3c03e473a6d481b/src/samak/nodes.cljc | clojure | (println "evaling module: " module)
needs to prep resolve magic when instanciating pipes, to select same runtime
maybe simply do so explicitly | (ns samak.nodes
(:require [samak.protocols :as p]
[samak.api :as api]
[samak.pipes :as pipes]
[samak.tools :refer [fail log]]
[samak.trace :refer [*db-id*]]
[samak.code-db :as db]))
(def ^:dynamic *manager* nil)
(def ^:dynamic *builtins* {})
(defn compile-error
[& args]
(fail ["[" *db-id* "]"] args))
(defmulti eval-node ::type)
(defn eval-reordered [nodes]
(->> nodes
(sort-by :order)
(mapv (comp eval-node ::node))))
(def eval-vals (partial map (fn [[k v]] [(::value k) (eval-node v)])))
(defn ref? [m]
(and (map? m) (= (keys m) [:db/id])))
(defn unresolved-name? [value]
(and (vector? value)
(= 2 (count value))
(= ::name (first value))))
(defmethod eval-node nil [value]
(cond
(unresolved-name? value) (compile-error "Tried to eval unresolved name:"
(str "'" (second value) "'"))
(ref? value) (let [id (:db/id value)]
(or ((:resolve *manager*) id)
(compile-error "Referenced id " id " was undefined")))
:default (compile-error "unknown token during evaluation: " (str value))))
(defmethod eval-node ::module [{:keys [::definition] :as module}]
FIXME : also needs to make this stuff available for resolve ?
(fn []
FIXME
(println (str "about to eval module: " module))
(let [evaled (eval-node definition)]
(println (str "used module: " module "->" evaled))
evaled)))
(defmethod eval-node ::map [{:keys [::mapkv-pairs]}]
(reduce (fn [a {:keys [::mapkey ::mapvalue]}]
(assoc a (::value mapkey) (eval-node mapvalue)))
{}
mapkv-pairs))
(defmethod eval-node ::vector [{:keys [::children]}]
(-> children eval-reordered vec))
(defmethod eval-node ::integer [{:keys [::value]}] value)
(defmethod eval-node ::keyword [{:keys [::value]}] value)
(defmethod eval-node ::key-fn [{:keys [::value]}] (fn [x] (value x)))
(defmethod eval-node ::string [{:keys [::value]}] value)
(defmethod eval-node ::float [{:keys [::value]}] value)
(defmethod eval-node ::builtin [{:keys [::value]}] (get *builtins* value))
(defmethod eval-node ::def [{:keys [::rhs]}] (eval-node rhs))
(defmethod eval-node ::pipe [{:keys [::from ::to ::xf] :as p}]
(let [a (eval-node from)
b (when xf
(let [db-id (:db/id xf)]
(binding [*db-id* db-id]
(-> xf
eval-node
((partial pipes/instrument db-id (:cancel? *manager*)))
pipes/transduction-pipe))))
c (eval-node to)]
((:link *manager*) a c b)))
(defmethod eval-node ::fn-ref [{:keys [::fn] :as f}]
(or (when (api/is-def? fn) (eval-node fn))
((:resolve *manager*) (:db/id fn))
(compile-error "Undefined reference " fn " in " *manager*)))
(defmethod eval-node ::fn-call [{:keys [::fn-expression ::arguments]}]
(let [func (eval-node fn-expression)]
(try (apply (p/eval-as-fn func) (eval-reordered arguments))
(catch clojure.lang.ArityException ex
(compile-error "wrong args: " (eval-reordered arguments) " for fn " func " -> " ex)))))
(defmethod eval-node ::link [{:keys [::from ::to]}]
(pipes/link! (eval-node from) (eval-node to)))
(defn eval-env [manager builtins ast db-id]
(binding [*manager* manager
*builtins* builtins
*db-id* db-id]
(eval-node ast)))
|
305ab90cc550909255239099d5312d1d17675c321fbd0cecdc842ec9b3cb7621 | ROCKTAKEY/roquix | tailscale.scm | (define-module
(roquix packages tailscale)
#:use-module (guix packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (gnu packages linux)
#:use-module (nonguix build-system binary))
(define-public tailscale
(package
(name "tailscale")
(version "1.24.2")
(source (origin
(method url-fetch)
(uri (string-append ""
version "_amd64.tgz"))
(sha256
(base32
"1b697g694vigzmv5q48l1d3pjc9l5gwzazggnfi7z9prb9cvlnx2"))))
(build-system binary-build-system)
(arguments '(#:install-plan
'(("tailscale" "bin/")
("tailscaled" "bin/"))))
(home-page "/")
(synopsis "Tailscale")
(propagated-inputs
(list iptables))
(description
"A secure network that just works
Zero config VPN. Installs on any device in minutes, manages firewall rules for you, and works from anywhere.")
(license license:bsd-3)))
| null | https://raw.githubusercontent.com/ROCKTAKEY/roquix/03fd20cbef8de72a2d52dec8593f242d1a752d09/roquix/packages/tailscale.scm | scheme | (define-module
(roquix packages tailscale)
#:use-module (guix packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (gnu packages linux)
#:use-module (nonguix build-system binary))
(define-public tailscale
(package
(name "tailscale")
(version "1.24.2")
(source (origin
(method url-fetch)
(uri (string-append ""
version "_amd64.tgz"))
(sha256
(base32
"1b697g694vigzmv5q48l1d3pjc9l5gwzazggnfi7z9prb9cvlnx2"))))
(build-system binary-build-system)
(arguments '(#:install-plan
'(("tailscale" "bin/")
("tailscaled" "bin/"))))
(home-page "/")
(synopsis "Tailscale")
(propagated-inputs
(list iptables))
(description
"A secure network that just works
Zero config VPN. Installs on any device in minutes, manages firewall rules for you, and works from anywhere.")
(license license:bsd-3)))
| |
f0036e0e1a9888d7744eb4006cb8b2240b14223538f0c5a7d384a1ad51b31a34 | levex/wacc | Emit.hs | module WACC.CodeGen.ARM.Emit where
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad.Writer
import WACC.CodeGen.Types
import WACC.Parser.Types hiding (Add, Sub, Mul, Div)
import WACC.Semantics.Types
conditions :: [(Condition, String)]
conditions = [ (CAl, "")
, (CEq, "eq")
, (CNe, "ne")
, (CCs, "cs")
, (CCc, "cc")
, (CMi, "mi")
, (CPl, "pl")
, (CVs, "vs")
, (CVc, "vc")
, (CHi, "hi")
, (CLs, "ls")
, (CGe, "ge")
, (CLt, "lt")
, (CGt, "gt")
, (CLe, "le") ]
sizes :: [(MemAccessType, String)]
sizes = [ (Byte, "b")
, (HalfWord, "h")
, (Word, "") ]
opTable :: [(Operation, String)]
opTable = [ (AddOp, "add")
, (SubOp, "sub")
, (RSubOp, "rsb")
, (MulOp, "mul")
, (OrOp, "orr")
, (XorOp, "eor")
, (AndOp, "and")]
genModifier :: Eq a => [(a, String)] -> a -> String -> String
genModifier t = flip (++) . fromJust . flip lookup t
genCond :: Condition -> String -> String
genCond = genModifier conditions
genSize :: MemAccessType -> String -> String
genSize = genModifier sizes
instance Emit Instruction where
emit (Special (FunctionStart label usedRegs stackSpace))
= [".globl ", label, "\n"]
++ concatMap emit
[ Special (LabelDecl label)
, Push CAl (usedRegs ++ [LR])
, Push CAl [(R 12)]
, if stackSpace > 0 then
sub sp , sp , stackSpace
else
Special Empty
, Move CAl (R 12) (Reg (R 13)) -- mov fp, sp
]
emit (Special (LabelDecl l))
= [l, ":\n"]
emit (Special (SectionStart str))
= [".section ", str, "\n"]
emit (Special _)
= []
emit (Load c m rt op1 plus op2)
= [genCond c (genSize m "ldr"), " "] ++
case op1 of
Imm i -> [show rt, ", =", show i, "\n"]
Label l -> [show rt, ", =", l, "\n"]
Reg rn -> case op2 of
Reg rm -> [show rt, ", [", show rn, ", ",
if plus then "" else "-", show rm, "]\n"]
Imm 0 -> [show rt, ", [", show rn, "]\n"]
Imm i2 -> [show rt, ", [", show rn, ", ",
"#", show i2, "]\n"]
emit (Move c rt op1)
= [genCond c "mov", " "] ++
case op1 of
Imm i -> [show rt, ", #", show i, "\n"]
Reg rn -> [show rt, ", ", show rn, "\n"]
emit (MoveN c rt rn)
= [genCond c "mvn", " ", show rt, ", ", show rn, "\n"]
emit (Shift c rt rn st op)
= [genCond c (map toLower (show st)), " ", show rt, ", ", show rn, ", "] ++
case op of
Imm i -> ["#", show i, "\n"]
Reg rs -> [show rs, "\n"]
emit (Push c rs)
= [genCond c "push", " {",
intercalate ", " $ map show (sort rs), "}\n"]
emit (Pop c rs)
= [genCond c "pop", " {",
intercalate ", " $ map show (sort rs), "}\n"]
emit (Branch c op1)
= case op1 of
Label lab -> [genCond c "b", " ", lab, "\n"]
Reg rt -> [genCond c "bx", " ", show rt, "\n"]
emit (BranchLink c op1)
= case op1 of
Label lab -> [genCond c "bl", " ", lab, "\n"]
Reg rt -> [genCond c "blx", " ", show rt, "\n"]
emit (Compare c rt op1) = do
[genCond c "cmp", " "] ++
case op1 of
Reg rn -> [show rt, ", ", show rn, "\n"]
Imm i -> [show rt, ", #", show i, "\n"]
emit (Store c m rt rn plus op2) = do
[genCond c (genSize m "str"), " "] ++
case op2 of
Reg rm -> [show rt, ", [", show rn, ", ",
if plus then "" else "- ", show rm, "]\n"]
Imm 0 -> [show rt, ", [", show rn, "]\n"]
Imm i -> [show rt, ", [", show rn, ", #", show i, "]\n"]
emit (Op c (ModOp True) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
FIXME : see and unify these
, Move c r1 op1
, BranchLink c (Label "__aeabi_idivmod")
, Move c rt (Reg r1)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (ModOp False) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
FIXME : see and unify these
, Move c r1 op1
, BranchLink c (Label "__aeabi_uidivmod")
, Move c rt (Reg r1)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (DivOp True) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
, Move c r0 (Reg rn) -- FIXME: proper regsave and div-by-zero check
, Move c r1 op1
, BranchLink c (Label "__aeabi_idiv")
, Move c rt (Reg r0)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (DivOp False) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
, Move c r0 (Reg rn) -- FIXME: proper regsave and div-by-zero check
, Move c r1 op1
, BranchLink c (Label "__aeabi_uidiv")
, Move c rt (Reg r0)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c op rt rn op1)
= [genCond c (fromJust $ lookup op opTable), " "] ++
case op1 of
Reg rm -> [intercalate ", " $ map show [rt, rn, rm],"\n"]
Imm i -> [show rt, ", ", show rn, ", #", show i,"\n"]
emit (SWI i)
= ["swi #", show i, "\n"]
emit (Ret (Just op) usedRegs stackSpace) = concatMap emit
[ Move CAl r0 op
, if stackSpace > 0 then
add sp , sp , stackSpace
else
Special Empty
, Pop CAl [(R 12)]
, Pop CAl (usedRegs ++ [PC])
]
emit (Ret Nothing usedRegs stackSpace) = concatMap emit
[ if stackSpace > 0 then
add sp , sp , stackSpace
else
Special Empty
, Pop CAl [(R 12)]
, Pop CAl (usedRegs ++ [PC])
]
emit (PureAsm ss)
= ss
| null | https://raw.githubusercontent.com/levex/wacc/c77164f0c9aeb53d3d13a0370fdedc448b6009a3/src/WACC/CodeGen/ARM/Emit.hs | haskell | mov fp, sp
FIXME: proper regsave and div-by-zero check
FIXME: proper regsave and div-by-zero check | module WACC.CodeGen.ARM.Emit where
import Data.Char
import Data.List
import Data.Maybe
import Control.Monad.Writer
import WACC.CodeGen.Types
import WACC.Parser.Types hiding (Add, Sub, Mul, Div)
import WACC.Semantics.Types
conditions :: [(Condition, String)]
conditions = [ (CAl, "")
, (CEq, "eq")
, (CNe, "ne")
, (CCs, "cs")
, (CCc, "cc")
, (CMi, "mi")
, (CPl, "pl")
, (CVs, "vs")
, (CVc, "vc")
, (CHi, "hi")
, (CLs, "ls")
, (CGe, "ge")
, (CLt, "lt")
, (CGt, "gt")
, (CLe, "le") ]
sizes :: [(MemAccessType, String)]
sizes = [ (Byte, "b")
, (HalfWord, "h")
, (Word, "") ]
opTable :: [(Operation, String)]
opTable = [ (AddOp, "add")
, (SubOp, "sub")
, (RSubOp, "rsb")
, (MulOp, "mul")
, (OrOp, "orr")
, (XorOp, "eor")
, (AndOp, "and")]
genModifier :: Eq a => [(a, String)] -> a -> String -> String
genModifier t = flip (++) . fromJust . flip lookup t
genCond :: Condition -> String -> String
genCond = genModifier conditions
genSize :: MemAccessType -> String -> String
genSize = genModifier sizes
instance Emit Instruction where
emit (Special (FunctionStart label usedRegs stackSpace))
= [".globl ", label, "\n"]
++ concatMap emit
[ Special (LabelDecl label)
, Push CAl (usedRegs ++ [LR])
, Push CAl [(R 12)]
, if stackSpace > 0 then
sub sp , sp , stackSpace
else
Special Empty
]
emit (Special (LabelDecl l))
= [l, ":\n"]
emit (Special (SectionStart str))
= [".section ", str, "\n"]
emit (Special _)
= []
emit (Load c m rt op1 plus op2)
= [genCond c (genSize m "ldr"), " "] ++
case op1 of
Imm i -> [show rt, ", =", show i, "\n"]
Label l -> [show rt, ", =", l, "\n"]
Reg rn -> case op2 of
Reg rm -> [show rt, ", [", show rn, ", ",
if plus then "" else "-", show rm, "]\n"]
Imm 0 -> [show rt, ", [", show rn, "]\n"]
Imm i2 -> [show rt, ", [", show rn, ", ",
"#", show i2, "]\n"]
emit (Move c rt op1)
= [genCond c "mov", " "] ++
case op1 of
Imm i -> [show rt, ", #", show i, "\n"]
Reg rn -> [show rt, ", ", show rn, "\n"]
emit (MoveN c rt rn)
= [genCond c "mvn", " ", show rt, ", ", show rn, "\n"]
emit (Shift c rt rn st op)
= [genCond c (map toLower (show st)), " ", show rt, ", ", show rn, ", "] ++
case op of
Imm i -> ["#", show i, "\n"]
Reg rs -> [show rs, "\n"]
emit (Push c rs)
= [genCond c "push", " {",
intercalate ", " $ map show (sort rs), "}\n"]
emit (Pop c rs)
= [genCond c "pop", " {",
intercalate ", " $ map show (sort rs), "}\n"]
emit (Branch c op1)
= case op1 of
Label lab -> [genCond c "b", " ", lab, "\n"]
Reg rt -> [genCond c "bx", " ", show rt, "\n"]
emit (BranchLink c op1)
= case op1 of
Label lab -> [genCond c "bl", " ", lab, "\n"]
Reg rt -> [genCond c "blx", " ", show rt, "\n"]
emit (Compare c rt op1) = do
[genCond c "cmp", " "] ++
case op1 of
Reg rn -> [show rt, ", ", show rn, "\n"]
Imm i -> [show rt, ", #", show i, "\n"]
emit (Store c m rt rn plus op2) = do
[genCond c (genSize m "str"), " "] ++
case op2 of
Reg rm -> [show rt, ", [", show rn, ", ",
if plus then "" else "- ", show rm, "]\n"]
Imm 0 -> [show rt, ", [", show rn, "]\n"]
Imm i -> [show rt, ", [", show rn, ", #", show i, "]\n"]
emit (Op c (ModOp True) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
FIXME : see and unify these
, Move c r1 op1
, BranchLink c (Label "__aeabi_idivmod")
, Move c rt (Reg r1)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (ModOp False) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
FIXME : see and unify these
, Move c r1 op1
, BranchLink c (Label "__aeabi_uidivmod")
, Move c rt (Reg r1)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (DivOp True) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
, Move c r1 op1
, BranchLink c (Label "__aeabi_idiv")
, Move c rt (Reg r0)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c (DivOp False) rt rn op1) = concatMap emit
[ Push c [r0, r1, r2, r3, R 12]
, Move c r1 op1
, BranchLink c (Label "__aeabi_uidiv")
, Move c rt (Reg r0)
, Pop c [r0, r1, r2, r3, R 12]]
emit (Op c op rt rn op1)
= [genCond c (fromJust $ lookup op opTable), " "] ++
case op1 of
Reg rm -> [intercalate ", " $ map show [rt, rn, rm],"\n"]
Imm i -> [show rt, ", ", show rn, ", #", show i,"\n"]
emit (SWI i)
= ["swi #", show i, "\n"]
emit (Ret (Just op) usedRegs stackSpace) = concatMap emit
[ Move CAl r0 op
, if stackSpace > 0 then
add sp , sp , stackSpace
else
Special Empty
, Pop CAl [(R 12)]
, Pop CAl (usedRegs ++ [PC])
]
emit (Ret Nothing usedRegs stackSpace) = concatMap emit
[ if stackSpace > 0 then
add sp , sp , stackSpace
else
Special Empty
, Pop CAl [(R 12)]
, Pop CAl (usedRegs ++ [PC])
]
emit (PureAsm ss)
= ss
|
c8c130b0077257cbec7a6fc9a9ba2fda0941754112e849a4c399bb5b3f3d9a9a | ejgallego/coq-serapi | ser_genintern.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * INRIA , CNRS and contributors - Copyright 1999 - 2018
(* <O___,, * (see CREDITS file for the list of authors) *)
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 - 2018 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 +
(************************************************************************)
(* Status: Very Experimental *)
(************************************************************************)
open Sexplib.Conv
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Stdlib = Ser_stdlib
module Names = Ser_names
module Environ = Ser_environ
module Glob_term = Ser_glob_term
module Constrexpr = Ser_constrexpr
module Pattern = Ser_pattern
module Notation_term = Ser_notation_term
module Store = struct
module StoreOpaque = struct type t = Genintern.Store.t let name = "Genintern.Store.t" end
include SerType.Opaque(StoreOpaque)
end
type intern_variable_status =
[%import: Genintern.intern_variable_status]
[@@deriving sexp,yojson,hash,compare]
type glob_sign =
[%import: Genintern.glob_sign]
[@@deriving sexp]
type glob_constr_and_expr =
[%import: Genintern.glob_constr_and_expr]
[@@deriving sexp,yojson,hash,compare]
type glob_constr_pattern_and_expr =
[%import: Genintern.glob_constr_pattern_and_expr]
[@@deriving sexp,yojson,hash,compare]
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/61d2a5c092c1918312b8a92f43a374639d1786f9/serlib/ser_genintern.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
<O___,, * (see CREDITS file for the list of authors)
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Very Experimental
********************************************************************** | v * INRIA , CNRS and contributors - Copyright 1999 - 2018
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
Copyright 2016 - 2018 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 +
open Sexplib.Conv
open Ppx_hash_lib.Std.Hash.Builtin
open Ppx_compare_lib.Builtin
module Stdlib = Ser_stdlib
module Names = Ser_names
module Environ = Ser_environ
module Glob_term = Ser_glob_term
module Constrexpr = Ser_constrexpr
module Pattern = Ser_pattern
module Notation_term = Ser_notation_term
module Store = struct
module StoreOpaque = struct type t = Genintern.Store.t let name = "Genintern.Store.t" end
include SerType.Opaque(StoreOpaque)
end
type intern_variable_status =
[%import: Genintern.intern_variable_status]
[@@deriving sexp,yojson,hash,compare]
type glob_sign =
[%import: Genintern.glob_sign]
[@@deriving sexp]
type glob_constr_and_expr =
[%import: Genintern.glob_constr_and_expr]
[@@deriving sexp,yojson,hash,compare]
type glob_constr_pattern_and_expr =
[%import: Genintern.glob_constr_pattern_and_expr]
[@@deriving sexp,yojson,hash,compare]
|
58ee67a2c646fe18af7492bc15fc987cf91ac781613e0e95dc9c9cedabd176e7 | byorgey/diagrams-play | ToothpickTrees.hs | {- -player.org/2013/joshua-trees-and-toothpicks -}
import Control.Arrow (second)
import Control.Lens ((&), _1, _2, (%~))
import Data.List (group, sort)
import qualified Data.Set as S
import Diagrams.Prelude hiding ((&), End)
data Dir = H | V
deriving (Eq, Show, Ord)
flipDir H = V
flipDir V = H
type Loc = (Int, Int)
data End = End { endLoc :: Loc, endDir :: Dir }
deriving (Eq, Show, Ord)
data Toothpick = Toothpick Loc Dir (Colour Double)
deriving (Show)
instance Eq Toothpick where
(Toothpick l1 d1 _) == (Toothpick l2 d2 _) = l1 == l2 && d1 == d2
instance Ord Toothpick where
compare (Toothpick l1 d1 _) (Toothpick l2 d2 _) = compare l1 l2 `mappend` compare d1 d2
data ToothpickTree = TT { ttGen :: Int
, ttToothpicks :: S.Set Toothpick
, ttLocs :: S.Set Loc
, ttEnds :: [End]
}
deriving (Show)
toothpickEnds (Toothpick l dir _)
= [End (l & x %~ pred) dir, End (l & x %~ succ) dir]
where
x = case dir of
H -> _1
V -> _2
grow :: Colour Double -> End -> (Toothpick, [End])
grow c (End l dir) = ( t, toothpickEnds t )
where
dir' = flipDir dir
t = Toothpick l dir' c
colors = [red, blue, green]
growTree (TT gen toothpicks locs tips)
= (TT (gen + 1)
(toothpicks `S.union` S.fromList newTPs)
(locs `S.union` (S.fromList $ map endLoc newEnds))
newTips
)
where
c = colors !! (gen `mod` length colors)
(newTPs, newEnds) = second concat . unzip . map (grow c) $ tips
newEnds' = map head . filter (null . drop 1) . group . sort $ newEnds
newTips = filter ((`S.notMember` locs) . endLoc) newEnds'
initToothpick = Toothpick (0,0) V (colors !! 0)
initTree = TT 0
(S.singleton initToothpick)
(S.fromList $ (0,0) : map endLoc es)
es
where es = toothpickEnds initToothpick
tt n = iterate growTree initTree !! n
--------------------------------------------------
locToP2 (x,y) = p2 (fromIntegral x, fromIntegral y)
drawToothpick (Toothpick loc dir c)
= (case dir of {H -> hrule; V -> vrule}) 2 # moveTo (locToP2 loc) # lc c
drawToothpicks = sized (Width 4) . mconcat . map drawToothpick . S.toList
drawTT = drawToothpicks . ttToothpicks . tt | null | https://raw.githubusercontent.com/byorgey/diagrams-play/5362c715db394be6848ff5de1bbe71178e5f173f/ToothpickTrees.hs | haskell | -player.org/2013/joshua-trees-and-toothpicks
------------------------------------------------ |
import Control.Arrow (second)
import Control.Lens ((&), _1, _2, (%~))
import Data.List (group, sort)
import qualified Data.Set as S
import Diagrams.Prelude hiding ((&), End)
data Dir = H | V
deriving (Eq, Show, Ord)
flipDir H = V
flipDir V = H
type Loc = (Int, Int)
data End = End { endLoc :: Loc, endDir :: Dir }
deriving (Eq, Show, Ord)
data Toothpick = Toothpick Loc Dir (Colour Double)
deriving (Show)
instance Eq Toothpick where
(Toothpick l1 d1 _) == (Toothpick l2 d2 _) = l1 == l2 && d1 == d2
instance Ord Toothpick where
compare (Toothpick l1 d1 _) (Toothpick l2 d2 _) = compare l1 l2 `mappend` compare d1 d2
data ToothpickTree = TT { ttGen :: Int
, ttToothpicks :: S.Set Toothpick
, ttLocs :: S.Set Loc
, ttEnds :: [End]
}
deriving (Show)
toothpickEnds (Toothpick l dir _)
= [End (l & x %~ pred) dir, End (l & x %~ succ) dir]
where
x = case dir of
H -> _1
V -> _2
grow :: Colour Double -> End -> (Toothpick, [End])
grow c (End l dir) = ( t, toothpickEnds t )
where
dir' = flipDir dir
t = Toothpick l dir' c
colors = [red, blue, green]
growTree (TT gen toothpicks locs tips)
= (TT (gen + 1)
(toothpicks `S.union` S.fromList newTPs)
(locs `S.union` (S.fromList $ map endLoc newEnds))
newTips
)
where
c = colors !! (gen `mod` length colors)
(newTPs, newEnds) = second concat . unzip . map (grow c) $ tips
newEnds' = map head . filter (null . drop 1) . group . sort $ newEnds
newTips = filter ((`S.notMember` locs) . endLoc) newEnds'
initToothpick = Toothpick (0,0) V (colors !! 0)
initTree = TT 0
(S.singleton initToothpick)
(S.fromList $ (0,0) : map endLoc es)
es
where es = toothpickEnds initToothpick
tt n = iterate growTree initTree !! n
locToP2 (x,y) = p2 (fromIntegral x, fromIntegral y)
drawToothpick (Toothpick loc dir c)
= (case dir of {H -> hrule; V -> vrule}) 2 # moveTo (locToP2 loc) # lc c
drawToothpicks = sized (Width 4) . mconcat . map drawToothpick . S.toList
drawTT = drawToothpicks . ttToothpicks . tt |
7df4bdad63897f166fe68613ee63c66faff8a4421ab5448a0a6ad6f39cd3f1f6 | nikita-volkov/hasql-transaction | SQL.hs | module Hasql.Transaction.Private.SQL where
import qualified ByteString.TreeBuilder as D
import Hasql.Transaction.Config
import Hasql.Transaction.Private.Prelude
beginTransaction :: IsolationLevel -> Mode -> ByteString
beginTransaction isolation mode =
D.toByteString builder
where
builder =
"BEGIN " <> isolationBuilder <> " " <> modeBuilder
where
isolationBuilder =
case isolation of
ReadCommitted -> "ISOLATION LEVEL READ COMMITTED"
RepeatableRead -> "ISOLATION LEVEL REPEATABLE READ"
Serializable -> "ISOLATION LEVEL SERIALIZABLE"
modeBuilder =
case mode of
Write -> "READ WRITE"
Read -> "READ ONLY"
declareCursor :: ByteString -> ByteString -> ByteString
declareCursor name sql =
D.toByteString $
"DECLARE " <> D.byteString name <> " NO SCROLL CURSOR FOR " <> D.byteString sql
| null | https://raw.githubusercontent.com/nikita-volkov/hasql-transaction/d4bcbb5bdb361b828717962bab085f95b5feb60d/library/Hasql/Transaction/Private/SQL.hs | haskell | module Hasql.Transaction.Private.SQL where
import qualified ByteString.TreeBuilder as D
import Hasql.Transaction.Config
import Hasql.Transaction.Private.Prelude
beginTransaction :: IsolationLevel -> Mode -> ByteString
beginTransaction isolation mode =
D.toByteString builder
where
builder =
"BEGIN " <> isolationBuilder <> " " <> modeBuilder
where
isolationBuilder =
case isolation of
ReadCommitted -> "ISOLATION LEVEL READ COMMITTED"
RepeatableRead -> "ISOLATION LEVEL REPEATABLE READ"
Serializable -> "ISOLATION LEVEL SERIALIZABLE"
modeBuilder =
case mode of
Write -> "READ WRITE"
Read -> "READ ONLY"
declareCursor :: ByteString -> ByteString -> ByteString
declareCursor name sql =
D.toByteString $
"DECLARE " <> D.byteString name <> " NO SCROLL CURSOR FOR " <> D.byteString sql
| |
1eee5fbf5746aff5eadc58748c80a7901fe5db2aa67b1971f37cf0bae7ce0e80 | matt-noonan/justified-containers | Tutorial.hs | # LANGUAGE RankNTypes , DeriveTraversable #
-- |
-- Module : Data.Map.Justified.Tutorial
Copyright : ( c ) 2017
-- License : BSD-style
-- Maintainer :
-- Portability : portable
--
-- = Description
--
-- The examples below demonstrate how to use the types and functions in "Data.Map.Justified".
--
-- You should be able to simply load this module in @ghci@ to play along.
-- The import list is:
--
-- @
import Prelude hiding ( lookup )
--
import Data . Map . Justified
--
-- import qualified Data.Map as M
--
import Data . ( for )
import Data . ( toUpper )
import Control . ( forM _ )
-- @
module Data.Map.Justified.Tutorial where
import Prelude hiding (lookup)
import Data.Map.Justified
import qualified Data.Map as M
import Data.Char (toUpper)
import Control.Monad (forM_)
import Data.Type.Coercion
-- | A simple "Data.Map" value used in several examples below.
--
-- @
test_table = M.fromList [ ( 1 , " hello " ) , ( 2 , " world " ) ]
-- @
test_table :: M.Map Int String
test_table = M.fromList [ (1, "hello"), (2, "world") ]
| This example shows how the @'Data . Map .
-- function can be used to obtain a key whose type has been
-- augmented by a proof that the key is present in maps of a
-- certain type.
--
-- Where "Data.Map" may use a @'Maybe'@ type to ensure that
-- the user handles missing keys when performing a lookup,
-- here we use the @'Maybe'@ type to either tell the user
-- that a key is missing (by returning @'Nothing'@), or
-- actually give back evidence of the key's presence
( by returning @Just known_key@ )
--
The @'Data . Map . Justified.withMap'@ function is used to
plumb a " Data . Map " @'Data . Map . Map'@ into a function that
expects a " Data . Map . Justified " @'Data . Map . Justified . Map'@.
In the code below , you can think of @table@ as @test_table@ ,
-- enhanced with the ability to use verified keys.
--
You can get from @table@ back to @test_table@ using the
function @'Data . Map . Justified.theMap'@.
--
-- @
-- example1 = withMap test_table $ \\table -> do
--
putStrLn " Is 1 a valid key ? "
case member 1 table of
-- Nothing -> putStrLn " No, it was not found."
-- Just key -> putStrLn $ " Yes, found key: " ++ show key
--
a valid key ? "
case member 5 table of
-- Nothing -> putStrLn " No, it was not found."
-- Just key -> putStrLn $ " Yes, found key: " ++ show key
-- @
-- Output:
--
-- @
Is 1 a valid key ?
Yes , found key : Key 1
Is 5 a valid key ?
-- No, it was not found.
-- @
example1 :: IO ()
example1 = withMap test_table $ \table -> do
putStrLn "Is 1 a valid key?"
case member 1 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
putStrLn "Is 5 a valid key?"
case member 5 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
-- | Once you have obtained a verified key, how do you use it?
--
-- "Data.Map.Justified" has several functions that are similar
-- to ones found in "Data.Map" that operate over verified keys.
-- In this example, notice that we can extract values directly
from the map using @'Data . Map . Justified.lookup'@ ; since we already
-- proved that the key is present when we obtained a @Key ph k@
value , @'Data . Map . Justified.lookup'@ does not need to return a
-- @'Maybe'@ value.
--
-- @
-- example2 = withMap test_table $ \\table -> do
--
case member 1 table of
-- Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
-- Just key -> do
-- In this do - block , \'key\ ' represents the key 1 , but carries type - level
-- -- evidence that the key is present. Lookups and updates can now proceed
-- -- without the possibility of error.
putStrLn ( " Found key : " + + show key )
--
-- -- Note that lookup returns a value directly, not a \'Maybe\'!
-- putStrLn ("Value for key: " ++ lookup key table)
--
-- -- If you update an already-mapped value, the set of valid keys does
-- -- not change. So the evidence that \'key\' could be found in \'table\'
-- -- is still sufficient to ensure that \'key\' can be found in the updated
-- -- table as well.
-- let table' = reinsert key "howdy" table
-- putStrLn ("Value for key in updated map: " ++ lookup key table')
-- @
-- Output:
--
-- @
-- Found key: Key 1
-- Value for key: hello
-- Value for key in updated map: howdy
-- @
example2 :: IO ()
example2 = withMap test_table $ \table -> do
case member 1 table of
Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
Just key -> do
In this do - block , ' key ' represents the key 1 , but carries type - level
-- evidence that the key is present. Lookups and updates can now proceed
-- without the possibility of error.
putStrLn ("Found key " ++ show key)
-- Note that lookup returns a value directly, not a 'Maybe'!
putStrLn ("Value for key: " ++ lookup key table)
-- If you update an already-mapped value, the set of valid keys does
-- not change. So the evidence that 'key' could be found in 'table'
-- is still sufficient to ensure that 'key' can be found in the updated
-- table as well.
let table' = reinsert key "howdy" table
putStrLn ("Value for key in updated map: " ++ lookup key table')
-- | It is a bit surprising to realize that a key of type @Key ph k@ can
be used to safely look up values in /any/ map of type @Map ph k v@ ,
-- not only the map that they key was originally found in!
--
-- This example makes use of that property to look up corresponding
elements of two /different/ ( but related ) tables , using the same
-- key evidence.
--
-- @
-- example3 = withMap test_table $ \\table -> do
--
-- let uppercase = map toUpper
-- updated_table = fmap (reverse . uppercase) table
--
-- for (keys table) $ \\key -> do
-- -- Although we are iterating over keys from the original table, they
-- -- can also be used to safely lookup values in the fmapped table.
-- -- Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
-- putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
-- putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
--
-- return ()
-- @
-- Output:
--
-- @
-- In original table, Key 1 maps to hello
In updated table , Key 1 maps to OLLEH
In original table , Key 2 maps to world
In updated table , Key 2 maps to DLROW
-- @
example3 :: IO ()
example3 = withMap test_table $ \table -> do
let uppercase = map toUpper
updated_table = fmap (reverse . uppercase) table
forM_ (keys table) $ \key -> do
-- Although we are iterating over keys from the original table, they
-- can also be used to safely lookup values in the fmapped table.
-- Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
return ()
-- | What if your set of keys can change over time?
--
-- If you were to insert a new key into a map, evidence that a key
-- exists is in the old map is no longer equivalent to evidence that
-- a key exists in the new map.
--
On the other hand , we know that if some @key@ exists in the old map ,
then @key@ must still exist in the new map . So there should be a
-- way of "upgrading" evidence from the old map to the new. Furthermore,
-- we know that the key we just added must be in the new map.
--
The @'Data . Map . Justified.inserting'@ function inserts a value into a map
-- and feeds the new map into a continuation, along with the "upgrade" and
-- "new key" data.
--
-- @
= withMap test_table $ \\table - > do
inserting 3 " NEW " table $ \\(newKey , upgrade , table ' ) - > do
-- forM_ (keys table) $ \\key -> do
-- putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
-- putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
-- putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
-- @
-- Output:
--
-- @
-- Key 1 maps to hello in the old table.
-- Key 1 maps to hello in the new table.
-- Key 2 maps to world in the old table.
-- Key 2 maps to world in the new table.
-- Also, the new table maps Key 3 to NEW
-- @
example4 :: IO ()
example4 = withMap test_table $ \table -> do
inserting 3 "NEW" table $ \(newKey, upgrade, table') -> do
forM_ (keys table) $ \key -> do
putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
-- | The next example uses a directed graph, defined by this adjacency list.
--
-- @
adjacencies = M.fromList [ ( 1 , [ 2,3 ] ) , ( 2 , [ 1,5,3 ] ) , ( 3 , [ 4 ] ) , ( 4 , [ 3 , 1 ] ) , ( 5 , [ ] ) ]
-- @
adjacencies :: M.Map Int [Int]
adjacencies = M.fromList [ (1, [2,3]), (2, [1,5,3]), (3, [4]), (4, [3, 1]), (5, []) ]
-- | Sometimes, the values in a map may include references back to keys
-- in the map. A canonical example of this is the adjacency map representation of
-- a directed graph, where each node maps to its list of immediate successors.
-- The type would look something like
--
-- @
-- type Digraphy node = M.Map node [node]
-- @
--
If you want to do a computation with a @Digraphy node@ , you probably want each
of the neighbor nodes to have keys in the @Digraphy node@ map . That is , you
-- may really want
--
-- @
type Digraph ph node = Map ph node [ Key ph node ]
-- \/\\ \/\\
-- | |
-- +-----+------+
-- |
-- (each neighbor should carry a proof that they are also in the map)
-- @
You can do this via @'Data . Map . Justified.withRecMap'@ , which converts each
-- key reference of type @k@ in your map to a verified key of type @'Key' ph k@.
--
But what if a referenced key really is missing from the map ? . Map . Justified.withRecMap'@
-- returns an @'Either'@ value to represent failure; if a key is missing, then the
-- result will be a value of the form @'Left' problems@, where @problems@ is an explanation
-- of where the missing keys are.
--
-- @
-- example5 = do
-- -- Print out the nodes in a graph
-- putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
-- trial adjacencies
--
-- Now add the ( non - present ) node 6 as a target of an edge from node 4 and try again :
let adjacencies ' = M.adjust ( 6 :) 4 adjacencies
-- putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
-- trial adjacencies'
--
-- where
-- trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
--
-- showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
--
-- showComplaint problems = do
-- putStrLn " The following edges are missing targets:"
let badPairs = concatMap ( \\(src , tgts ) - > [ ( src , tgt ) | ( tgt , Missing ) < - tgts ] ) problems
-- forM_ badPairs $ \\(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
-- @
-- Output:
--
-- @
-- Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[3,1]),(5,[])]
Nodes : [ 1,2,3,4,5 ]
-- Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[6,3,1]),(5,[])]
-- The following edges are missing targets:
4 - > 6
-- @
example5 :: IO ()
example5 = do
-- Print out the nodes in a graph
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
trial adjacencies
Now add the ( non - present ) node 6 as a target of an edge from node 4 and try again :
let adjacencies' = M.adjust (6:) 4 adjacencies
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
trial adjacencies'
where
trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
showComplaint problems = do
putStrLn " The following edges are missing targets:"
let badPairs = concatMap (\(src, tgts) -> [ (src,tgt) | (tgt, Missing) <- tgts ]) problems
forM_ badPairs $ \(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
| null | https://raw.githubusercontent.com/matt-noonan/justified-containers/38233a7faf0e953654ea380ea762b998765148e9/src/Data/Map/Justified/Tutorial.hs | haskell | |
Module : Data.Map.Justified.Tutorial
License : BSD-style
Maintainer :
Portability : portable
= Description
The examples below demonstrate how to use the types and functions in "Data.Map.Justified".
You should be able to simply load this module in @ghci@ to play along.
The import list is:
@
import qualified Data.Map as M
@
| A simple "Data.Map" value used in several examples below.
@
@
function can be used to obtain a key whose type has been
augmented by a proof that the key is present in maps of a
certain type.
Where "Data.Map" may use a @'Maybe'@ type to ensure that
the user handles missing keys when performing a lookup,
here we use the @'Maybe'@ type to either tell the user
that a key is missing (by returning @'Nothing'@), or
actually give back evidence of the key's presence
enhanced with the ability to use verified keys.
@
example1 = withMap test_table $ \\table -> do
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
@
Output:
@
No, it was not found.
@
| Once you have obtained a verified key, how do you use it?
"Data.Map.Justified" has several functions that are similar
to ones found in "Data.Map" that operate over verified keys.
In this example, notice that we can extract values directly
proved that the key is present when we obtained a @Key ph k@
@'Maybe'@ value.
@
example2 = withMap test_table $ \\table -> do
Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
Just key -> do
In this do - block , \'key\ ' represents the key 1 , but carries type - level
-- evidence that the key is present. Lookups and updates can now proceed
-- without the possibility of error.
-- Note that lookup returns a value directly, not a \'Maybe\'!
putStrLn ("Value for key: " ++ lookup key table)
-- If you update an already-mapped value, the set of valid keys does
-- not change. So the evidence that \'key\' could be found in \'table\'
-- is still sufficient to ensure that \'key\' can be found in the updated
-- table as well.
let table' = reinsert key "howdy" table
putStrLn ("Value for key in updated map: " ++ lookup key table')
@
Output:
@
Found key: Key 1
Value for key: hello
Value for key in updated map: howdy
@
evidence that the key is present. Lookups and updates can now proceed
without the possibility of error.
Note that lookup returns a value directly, not a 'Maybe'!
If you update an already-mapped value, the set of valid keys does
not change. So the evidence that 'key' could be found in 'table'
is still sufficient to ensure that 'key' can be found in the updated
table as well.
| It is a bit surprising to realize that a key of type @Key ph k@ can
not only the map that they key was originally found in!
This example makes use of that property to look up corresponding
key evidence.
@
example3 = withMap test_table $ \\table -> do
let uppercase = map toUpper
updated_table = fmap (reverse . uppercase) table
for (keys table) $ \\key -> do
-- Although we are iterating over keys from the original table, they
-- can also be used to safely lookup values in the fmapped table.
-- Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
return ()
@
Output:
@
In original table, Key 1 maps to hello
@
Although we are iterating over keys from the original table, they
can also be used to safely lookup values in the fmapped table.
Unlike (!) from Data.Map, Data.Map.Justified's (!) can not fail at runtime.
| What if your set of keys can change over time?
If you were to insert a new key into a map, evidence that a key
exists is in the old map is no longer equivalent to evidence that
a key exists in the new map.
way of "upgrading" evidence from the old map to the new. Furthermore,
we know that the key we just added must be in the new map.
and feeds the new map into a continuation, along with the "upgrade" and
"new key" data.
@
forM_ (keys table) $ \\key -> do
putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
@
Output:
@
Key 1 maps to hello in the old table.
Key 1 maps to hello in the new table.
Key 2 maps to world in the old table.
Key 2 maps to world in the new table.
Also, the new table maps Key 3 to NEW
@
| The next example uses a directed graph, defined by this adjacency list.
@
@
| Sometimes, the values in a map may include references back to keys
in the map. A canonical example of this is the adjacency map representation of
a directed graph, where each node maps to its list of immediate successors.
The type would look something like
@
type Digraphy node = M.Map node [node]
@
may really want
@
\/\\ \/\\
| |
+-----+------+
|
(each neighbor should carry a proof that they are also in the map)
@
key reference of type @k@ in your map to a verified key of type @'Key' ph k@.
returns an @'Either'@ value to represent failure; if a key is missing, then the
result will be a value of the form @'Left' problems@, where @problems@ is an explanation
of where the missing keys are.
@
example5 = do
-- Print out the nodes in a graph
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
trial adjacencies
Now add the ( non - present ) node 6 as a target of an edge from node 4 and try again :
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
trial adjacencies'
where
trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
showComplaint problems = do
putStrLn " The following edges are missing targets:"
forM_ badPairs $ \\(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
@
Output:
@
Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[3,1]),(5,[])]
Finding nodes in the directed graph fromList [(1,[2,3]),(2,[1,5,3]),(3,[4]),(4,[6,3,1]),(5,[])]
The following edges are missing targets:
@
Print out the nodes in a graph | # LANGUAGE RankNTypes , DeriveTraversable #
Copyright : ( c ) 2017
import Prelude hiding ( lookup )
import Data . Map . Justified
import Data . ( for )
import Data . ( toUpper )
import Control . ( forM _ )
module Data.Map.Justified.Tutorial where
import Prelude hiding (lookup)
import Data.Map.Justified
import qualified Data.Map as M
import Data.Char (toUpper)
import Control.Monad (forM_)
import Data.Type.Coercion
test_table = M.fromList [ ( 1 , " hello " ) , ( 2 , " world " ) ]
test_table :: M.Map Int String
test_table = M.fromList [ (1, "hello"), (2, "world") ]
| This example shows how the @'Data . Map .
( by returning @Just known_key@ )
The @'Data . Map . Justified.withMap'@ function is used to
plumb a " Data . Map " @'Data . Map . Map'@ into a function that
expects a " Data . Map . Justified " @'Data . Map . Justified . Map'@.
In the code below , you can think of @table@ as @test_table@ ,
You can get from @table@ back to @test_table@ using the
function @'Data . Map . Justified.theMap'@.
putStrLn " Is 1 a valid key ? "
case member 1 table of
a valid key ? "
case member 5 table of
Is 1 a valid key ?
Yes , found key : Key 1
Is 5 a valid key ?
example1 :: IO ()
example1 = withMap test_table $ \table -> do
putStrLn "Is 1 a valid key?"
case member 1 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
putStrLn "Is 5 a valid key?"
case member 5 table of
Nothing -> putStrLn " No, it was not found."
Just key -> putStrLn $ " Yes, found key: " ++ show key
from the map using @'Data . Map . Justified.lookup'@ ; since we already
value , @'Data . Map . Justified.lookup'@ does not need to return a
case member 1 table of
putStrLn ( " Found key : " + + show key )
example2 :: IO ()
example2 = withMap test_table $ \table -> do
case member 1 table of
Nothing -> putStrLn "Sorry, I couldn't prove that the key is present."
Just key -> do
In this do - block , ' key ' represents the key 1 , but carries type - level
putStrLn ("Found key " ++ show key)
putStrLn ("Value for key: " ++ lookup key table)
let table' = reinsert key "howdy" table
putStrLn ("Value for key in updated map: " ++ lookup key table')
be used to safely look up values in /any/ map of type @Map ph k v@ ,
elements of two /different/ ( but related ) tables , using the same
In updated table , Key 1 maps to OLLEH
In original table , Key 2 maps to world
In updated table , Key 2 maps to DLROW
example3 :: IO ()
example3 = withMap test_table $ \table -> do
let uppercase = map toUpper
updated_table = fmap (reverse . uppercase) table
forM_ (keys table) $ \key -> do
putStrLn ("In original table, " ++ show key ++ " maps to " ++ table ! key)
putStrLn ("In updated table, " ++ show key ++ " maps to " ++ updated_table ! key)
return ()
On the other hand , we know that if some @key@ exists in the old map ,
then @key@ must still exist in the new map . So there should be a
The @'Data . Map . Justified.inserting'@ function inserts a value into a map
= withMap test_table $ \\table - > do
inserting 3 " NEW " table $ \\(newKey , upgrade , table ' ) - > do
example4 :: IO ()
example4 = withMap test_table $ \table -> do
inserting 3 "NEW" table $ \(newKey, upgrade, table') -> do
forM_ (keys table) $ \key -> do
putStrLn (show key ++ " maps to " ++ table ! key ++ " in the old table.")
putStrLn (show key ++ " maps to " ++ table' ! (upgrade key) ++ " in the new table.")
putStrLn ("Also, the new table maps " ++ show newKey ++ " to " ++ table' ! newKey)
adjacencies = M.fromList [ ( 1 , [ 2,3 ] ) , ( 2 , [ 1,5,3 ] ) , ( 3 , [ 4 ] ) , ( 4 , [ 3 , 1 ] ) , ( 5 , [ ] ) ]
adjacencies :: M.Map Int [Int]
adjacencies = M.fromList [ (1, [2,3]), (2, [1,5,3]), (3, [4]), (4, [3, 1]), (5, []) ]
If you want to do a computation with a @Digraphy node@ , you probably want each
of the neighbor nodes to have keys in the @Digraphy node@ map . That is , you
type Digraph ph node = Map ph node [ Key ph node ]
You can do this via @'Data . Map . Justified.withRecMap'@ , which converts each
But what if a referenced key really is missing from the map ? . Map . Justified.withRecMap'@
let adjacencies ' = M.adjust ( 6 :) 4 adjacencies
let badPairs = concatMap ( \\(src , tgts ) - > [ ( src , tgt ) | ( tgt , Missing ) < - tgts ] ) problems
Nodes : [ 1,2,3,4,5 ]
4 - > 6
example5 :: IO ()
example5 = do
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies)
trial adjacencies
Now add the ( non - present ) node 6 as a target of an edge from node 4 and try again :
let adjacencies' = M.adjust (6:) 4 adjacencies
putStrLn ("Finding nodes in the directed graph " ++ show adjacencies')
trial adjacencies'
where
trial adj = either showComplaint showNodes (withRecMap adj (map theKey . keys))
showNodes nodes = putStrLn (" Nodes: " ++ show nodes)
showComplaint problems = do
putStrLn " The following edges are missing targets:"
let badPairs = concatMap (\(src, tgts) -> [ (src,tgt) | (tgt, Missing) <- tgts ]) problems
forM_ badPairs $ \(src,tgt) -> putStrLn (" " ++ show src ++ " -> " ++ show tgt)
|
fb74c148149c7bbb957d983cd3b5561e37487a515fcf85db6ef97490f9af1626 | jeromesimeon/Galax | top_parse.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2009 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ Id$
Module : Top_parse
Description :
This module implements a simple front - end for Galax XML
parser / validator and serialization .
Description:
This module implements a simple front-end for Galax XML
parser/validator and serialization.
*)
open Format
open Error
open Xquery_ast
open Processing_context
open Monitoring_context
open Top_util
open Top_options
open Top_config
(*****************)
(* Schema import *)
(*****************)
(* Imports an XML Schema *)
let get_schema () =
match !schemafile with
| None ->
failwith "Could not load the schema for validation"
| Some uri ->
(* Create a fresh processing context for the schema resource *)
let proc_ctxt = Processing_context.default_processing_context() in
SAX parsing
let (_, xml_schema_stream) = Streaming_parse.open_xml_stream_from_io (Galax_io.Http_Input uri) in
(* Followed by namespace resolution *)
let resolved_schema_stream = Streaming_ops.resolve_xml_stream xml_schema_stream in
(* Now schema import *)
let imported_schema = Schema_import.import_schema_document proc_ctxt None resolved_schema_stream in
(* Finally, schema normalization *)
let normalized_schema = Schema_norm.normalize Namespace_context.default_xml_nsenv imported_schema in
normalized_schema
(******************)
(* Parsing phases *)
(******************)
exception DONE of int
let consume_xml_stream xml_stream =
let i = ref 0 in
try
while (ignore(Cursor.cursor_next xml_stream);true) do incr i
done;
raise (DONE !i)
with
| Stream.Failure ->
raise (DONE !i)
let consume_resolved_xml_stream = consume_xml_stream
(* Serialization *)
let serialize proc_ctxt stream =
if !Conf.print_xml
then
begin
Serialization.serialize_xml_stream proc_ctxt stream;
raise (DONE 0)
end
else
consume_xml_stream stream
(* Prefix *)
let prefix proc_ctxt resolved_stream =
if !prefix
then
let stream = Streaming_ops.prefix_xml_stream resolved_stream in
serialize proc_ctxt stream
else
consume_xml_stream resolved_stream
(* Erase *)
let erase proc_ctxt typed_stream =
if !erase
then
let resolved_stream = Streaming_ops.erase_xml_stream typed_stream in
prefix proc_ctxt resolved_stream
else
consume_xml_stream typed_stream
(* Parsing *)
let parse_pxp proc_ctxt uri_string =
let gio = Galax_io.Http_Input uri_string in
let (pxp_stream,s) = Streaming_parse.open_pxp_stream_from_io gio Galax_io.Document_entity in
pxp_stream
let consume_pxp pp =
let e = ref None in
let i = ref 0 in
while (e := (fst pp) ()); (!e != None) do incr i
done;
raise (DONE !i)
let parse_galax proc_ctxt uri_string =
(* Parsing, followed by namespace resolution *)
let gio = Galax_io.Http_Input uri_string in
let (dtdopt, xml_stream) = Streaming_parse.open_xml_stream_from_io gio in
let sopt =
match dtdopt with
| None -> None
| Some dtd -> Some (Schema_dtd_import.import_dtd dtd)
in
(sopt, xml_stream)
let parse proc_ctxt uri_string =
if (!pxp)
then
if (!stream)
then
parse_galax proc_ctxt uri_string
else
consume_pxp (parse_pxp proc_ctxt uri_string)
else
raise (DONE 0)
let resolve proc_ctxt xml_stream =
if (!resolve)
then
Streaming_ops.resolve_xml_stream xml_stream
else
serialize proc_ctxt xml_stream
(* Validation *)
let validate proc_ctxt opt_cxschema resolved_xml_stream =
if (!annotate)
then
if (!validation)
then
begin
match opt_cxschema with
| None ->
failwith "Cannot validate without a schema"
| Some cxschema ->
Schema_validation.validate cxschema resolved_xml_stream
end
else
Streaming_ops.typed_of_resolved_xml_stream resolved_xml_stream
else
prefix proc_ctxt resolved_xml_stream
(* Export *)
let export proc_ctxt dm =
if !export
then
let typed_stream = Physical_export.typed_xml_stream_of_datamodel dm in
erase proc_ctxt typed_stream
else
raise (DONE 0)
(* Data model loading *)
let load proc_ctxt uri typed_xml_stream =
if (!load)
then
begin
let apply_load_document () =
let nodeid_context = Nodeid_context.default_nodeid_context () in
Physical_load.load_xml_document_from_typed_stream nodeid_context typed_xml_stream
in
begin
let res =
Monitor.wrap_monitor proc_ctxt (Document_ParsingLoading_Phase (AnyURI._string_of_uri uri)) apply_load_document ()
in
export proc_ctxt (Cursor.cursor_of_list res)
end
end
else
erase proc_ctxt typed_xml_stream
(*************************)
(* Process a single file *)
(*************************)
let process_file_aux proc_ctxt uri_string =
let uri = AnyURI._actual_uri_of_string uri_string in
(* Parsing -- check for well-formedness *)
let (dtdopt, xml_stream) = parse proc_ctxt uri_string in
let resolved_xml_stream = resolve proc_ctxt xml_stream in
(* Validation -- if requested *)
let opt_cxschema =
if (!validation)
then
if (!dtd) then
match dtdopt with
| Some xschema -> Some (Schema_norm.normalize Namespace_context.default_xml_nsenv xschema)
| None -> raise (Query(Error("No DTD found in "^uri_string)))
else Some (get_schema ())
else
None
in
let typed_xml_stream = validate proc_ctxt opt_cxschema resolved_xml_stream in
(* Data model loading and serialization -- if requested *)
let _ = load proc_ctxt uri typed_xml_stream in
()
let process_file proc_ctxt uri_string =
try
process_file_aux proc_ctxt uri_string
with
| DONE i -> Printf.printf "Processed %i events!\n" i
(**************************)
(* Command line arguments *)
(**************************)
let process_args proc_ctxt gargs =
let args =
make_options_argv
proc_ctxt
(usage_galax_parse ())
[ GalaxParse_Options;Misc_Options;Monitoring_Options;Encoding_Options;DataModel_Options;Serialization_Options;PrintParse_Options ]
gargs
in
match args with
| [] -> failwith "Input file(s) not specified"
| fnames ->
List.rev fnames
(********)
(* Main *)
(********)
let main proc_ctxt input_files =
List.iter (process_file proc_ctxt) input_files
(*************)
(* Let's go! *)
(*************)
let parse_typed_xml_stream_from_io pc gio =
1 . Open a SAX cursor on the input document
let (diff_opt, xml_stream) = Streaming_parse.open_xml_stream_from_io gio in
2 . Resolve namespaces
let resolved_xml_stream = Streaming_ops.resolve_xml_stream xml_stream in
3 . Apply type annotations
let typed_xml_stream = Streaming_ops.typed_of_resolved_xml_stream resolved_xml_stream in
typed_xml_stream
let go gargs =
let proc_ctxt = Processing_context.default_processing_context() in
let input_files = process_args proc_ctxt gargs in
(* Test if -diff is passed *)
if (!Top_config.diff) then
let output_file = List.hd input_files in
let expected_file = List.hd (List.tl input_files) in
let t1 = parse_typed_xml_stream_from_io proc_ctxt (Galax_io.File_Input output_file) in
let t2 = parse_typed_xml_stream_from_io proc_ctxt (Galax_io.File_Input expected_file) in
let b = Streaming_diff.stream_boolean_diff t1 t2 in
if (not b) then print_string (output_file^" and "^expected_file^" differ\n")
else ()
else
exec main proc_ctxt input_files
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/toplevel/top_parse.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
***************
Schema import
***************
Imports an XML Schema
Create a fresh processing context for the schema resource
Followed by namespace resolution
Now schema import
Finally, schema normalization
****************
Parsing phases
****************
Serialization
Prefix
Erase
Parsing
Parsing, followed by namespace resolution
Validation
Export
Data model loading
***********************
Process a single file
***********************
Parsing -- check for well-formedness
Validation -- if requested
Data model loading and serialization -- if requested
************************
Command line arguments
************************
******
Main
******
***********
Let's go!
***********
Test if -diff is passed | Copyright 2001 - 2009 .
$ Id$
Module : Top_parse
Description :
This module implements a simple front - end for Galax XML
parser / validator and serialization .
Description:
This module implements a simple front-end for Galax XML
parser/validator and serialization.
*)
open Format
open Error
open Xquery_ast
open Processing_context
open Monitoring_context
open Top_util
open Top_options
open Top_config
let get_schema () =
match !schemafile with
| None ->
failwith "Could not load the schema for validation"
| Some uri ->
let proc_ctxt = Processing_context.default_processing_context() in
SAX parsing
let (_, xml_schema_stream) = Streaming_parse.open_xml_stream_from_io (Galax_io.Http_Input uri) in
let resolved_schema_stream = Streaming_ops.resolve_xml_stream xml_schema_stream in
let imported_schema = Schema_import.import_schema_document proc_ctxt None resolved_schema_stream in
let normalized_schema = Schema_norm.normalize Namespace_context.default_xml_nsenv imported_schema in
normalized_schema
exception DONE of int
let consume_xml_stream xml_stream =
let i = ref 0 in
try
while (ignore(Cursor.cursor_next xml_stream);true) do incr i
done;
raise (DONE !i)
with
| Stream.Failure ->
raise (DONE !i)
let consume_resolved_xml_stream = consume_xml_stream
let serialize proc_ctxt stream =
if !Conf.print_xml
then
begin
Serialization.serialize_xml_stream proc_ctxt stream;
raise (DONE 0)
end
else
consume_xml_stream stream
let prefix proc_ctxt resolved_stream =
if !prefix
then
let stream = Streaming_ops.prefix_xml_stream resolved_stream in
serialize proc_ctxt stream
else
consume_xml_stream resolved_stream
let erase proc_ctxt typed_stream =
if !erase
then
let resolved_stream = Streaming_ops.erase_xml_stream typed_stream in
prefix proc_ctxt resolved_stream
else
consume_xml_stream typed_stream
let parse_pxp proc_ctxt uri_string =
let gio = Galax_io.Http_Input uri_string in
let (pxp_stream,s) = Streaming_parse.open_pxp_stream_from_io gio Galax_io.Document_entity in
pxp_stream
let consume_pxp pp =
let e = ref None in
let i = ref 0 in
while (e := (fst pp) ()); (!e != None) do incr i
done;
raise (DONE !i)
let parse_galax proc_ctxt uri_string =
let gio = Galax_io.Http_Input uri_string in
let (dtdopt, xml_stream) = Streaming_parse.open_xml_stream_from_io gio in
let sopt =
match dtdopt with
| None -> None
| Some dtd -> Some (Schema_dtd_import.import_dtd dtd)
in
(sopt, xml_stream)
let parse proc_ctxt uri_string =
if (!pxp)
then
if (!stream)
then
parse_galax proc_ctxt uri_string
else
consume_pxp (parse_pxp proc_ctxt uri_string)
else
raise (DONE 0)
let resolve proc_ctxt xml_stream =
if (!resolve)
then
Streaming_ops.resolve_xml_stream xml_stream
else
serialize proc_ctxt xml_stream
let validate proc_ctxt opt_cxschema resolved_xml_stream =
if (!annotate)
then
if (!validation)
then
begin
match opt_cxschema with
| None ->
failwith "Cannot validate without a schema"
| Some cxschema ->
Schema_validation.validate cxschema resolved_xml_stream
end
else
Streaming_ops.typed_of_resolved_xml_stream resolved_xml_stream
else
prefix proc_ctxt resolved_xml_stream
let export proc_ctxt dm =
if !export
then
let typed_stream = Physical_export.typed_xml_stream_of_datamodel dm in
erase proc_ctxt typed_stream
else
raise (DONE 0)
let load proc_ctxt uri typed_xml_stream =
if (!load)
then
begin
let apply_load_document () =
let nodeid_context = Nodeid_context.default_nodeid_context () in
Physical_load.load_xml_document_from_typed_stream nodeid_context typed_xml_stream
in
begin
let res =
Monitor.wrap_monitor proc_ctxt (Document_ParsingLoading_Phase (AnyURI._string_of_uri uri)) apply_load_document ()
in
export proc_ctxt (Cursor.cursor_of_list res)
end
end
else
erase proc_ctxt typed_xml_stream
let process_file_aux proc_ctxt uri_string =
let uri = AnyURI._actual_uri_of_string uri_string in
let (dtdopt, xml_stream) = parse proc_ctxt uri_string in
let resolved_xml_stream = resolve proc_ctxt xml_stream in
let opt_cxschema =
if (!validation)
then
if (!dtd) then
match dtdopt with
| Some xschema -> Some (Schema_norm.normalize Namespace_context.default_xml_nsenv xschema)
| None -> raise (Query(Error("No DTD found in "^uri_string)))
else Some (get_schema ())
else
None
in
let typed_xml_stream = validate proc_ctxt opt_cxschema resolved_xml_stream in
let _ = load proc_ctxt uri typed_xml_stream in
()
let process_file proc_ctxt uri_string =
try
process_file_aux proc_ctxt uri_string
with
| DONE i -> Printf.printf "Processed %i events!\n" i
let process_args proc_ctxt gargs =
let args =
make_options_argv
proc_ctxt
(usage_galax_parse ())
[ GalaxParse_Options;Misc_Options;Monitoring_Options;Encoding_Options;DataModel_Options;Serialization_Options;PrintParse_Options ]
gargs
in
match args with
| [] -> failwith "Input file(s) not specified"
| fnames ->
List.rev fnames
let main proc_ctxt input_files =
List.iter (process_file proc_ctxt) input_files
let parse_typed_xml_stream_from_io pc gio =
1 . Open a SAX cursor on the input document
let (diff_opt, xml_stream) = Streaming_parse.open_xml_stream_from_io gio in
2 . Resolve namespaces
let resolved_xml_stream = Streaming_ops.resolve_xml_stream xml_stream in
3 . Apply type annotations
let typed_xml_stream = Streaming_ops.typed_of_resolved_xml_stream resolved_xml_stream in
typed_xml_stream
let go gargs =
let proc_ctxt = Processing_context.default_processing_context() in
let input_files = process_args proc_ctxt gargs in
if (!Top_config.diff) then
let output_file = List.hd input_files in
let expected_file = List.hd (List.tl input_files) in
let t1 = parse_typed_xml_stream_from_io proc_ctxt (Galax_io.File_Input output_file) in
let t2 = parse_typed_xml_stream_from_io proc_ctxt (Galax_io.File_Input expected_file) in
let b = Streaming_diff.stream_boolean_diff t1 t2 in
if (not b) then print_string (output_file^" and "^expected_file^" differ\n")
else ()
else
exec main proc_ctxt input_files
|
0392659129051ef172b9dec21541c575015915e9e337a4d4e3f57a72e1b5a00b | schemeorg-community/index.scheme.org | index.scm | (
(r5rs . "types/r5rs.scm")
;; r6rs
((rnrs base (6)) . "types/rnrs.base.6.scm")
((rnrs arithmetic bitwise (6)) . "types/rnrs.arithmetic.bitwise.6.scm")
((rnrs arithmetic fixnum (6)) . "types/rnrs.arithmetic.fixnum.6.scm")
((rnrs arithmetic flonum (6)) . "types/rnrs.arithmetic.flonum.6.scm")
((rnrs bytevectors (6)) . "types/rnrs.bytevectors.6.scm")
((rnrs conditions (6)) . "types/rnrs.conditions.6.scm")
((rnrs control (6)) . "types/rnrs.control.6.scm")
((rnrs enums (6)) . "types/rnrs.enums.6.scm")
((rnrs eval (6)) . "types/scheme.eval.scm")
((rnrs exceptions (6)) . "types/rnrs.exceptions.6.scm")
((rnrs files (6)) . "types/rnrs.files.6.scm")
((rnrs hashtables (6)) . "types/rnrs.hashtables.6.scm")
((rnrs io ports (6)) . "types/rnrs.io.ports.6.scm")
((rnrs io simple (6)) . "types/rnrs.io.simple.6.scm")
((rnrs lists (6)) . "types/rnrs.lists.6.scm")
((rnrs mutable-pairs (6)) . "types/rnrs.mutable-pairs.6.scm")
((rnrs mutable-strings (6)) . "types/rnrs.mutable-strings.6.scm")
((rnrs programs (6)) . "types/rnrs.programs.6.scm")
((rnrs r5rs (6)) . "types/rnrs.r5rs.6.scm")
((rnrs records inspection (6)) . "types/rnrs.records.inspection.6.scm")
((rnrs records procedural (6)) . "types/rnrs.records.procedural.6.scm")
((rnrs records syntactic (6)) . "types/rnrs.records.syntactic.6.scm")
((rnrs sorting (6)) . "types/rnrs.sorting.6.scm")
((rnrs unicode (6)) . "types/rnrs.unicode.6.scm")
;; r7rs small
((scheme base) . "types/scheme.base.scm")
((scheme base) . "types/srfi.0.scm")
((scheme base) . "types/srfi.6.scm")
((scheme base) . "types/srfi.9.scm")
((scheme base) . "types/srfi.11.scm")
((scheme base) . "types/srfi.23.scm")
((scheme base) . "types/srfi.34.scm")
((scheme base) . "types/srfi.39.scm")
((scheme case-lambda) . "types/srfi.16.scm")
((scheme complex) . "types/scheme.complex.scm")
((scheme char) . "types/scheme.char.scm")
((scheme cxr) . "types/scheme.cxr.scm")
((scheme eval) . "types/scheme.eval.scm")
((scheme file) . "types/scheme.file.scm")
((scheme inexact) . "types/scheme.inexact.scm")
((scheme lazy) . "types/scheme.lazy.scm")
((scheme load) . "types/scheme.load.scm")
((scheme process-context) . "types/scheme.process-context.scm")
((scheme read) . "types/scheme.read.scm")
((scheme repl) . "types/scheme.repl.scm")
((scheme time) . "types/scheme.time.scm")
((scheme write) . "types/scheme.write.scm")
((scheme r5rs) . ((file . "types/r5rs.scm") (exclude . (transcript-on transcript-off))))
; r7rs large red
((scheme box) . "types/srfi.111.scm")
((scheme comparator) . "types/srfi.128.scm")
((scheme charset) . "types/srfi.14.scm")
((scheme ephemeron) . "types/srfi.124.scm")
((scheme generator) . "types/srfi.158.scm")
((scheme hash-table) . "types/srfi.125.scm")
((scheme ideque) . "types/srfi.134.scm")
((scheme ilist) . "types/srfi.116.scm")
((scheme list) . "types/srfi.1.scm")
((scheme list-queue) . "types/srfi.117.scm")
((scheme lseq) . "types/srfi.127.scm")
((scheme rlist) . "types/srfi.101.scm")
((scheme set) . "types/srfi.113.scm")
((scheme stream) . "types/srfi.41.scm")
((scheme sort) . "types/srfi.132.scm")
((scheme text) . "types/srfi.135.scm")
((scheme vector) . "types/srfi.133.scm")
; r7rs large tangerine
((scheme bitwise) . "types/srfi.151.scm")
((scheme bytevector) . "types/rnrs.bytevectors.6.scm")
((scheme division) . "types/srfi.141.scm")
((scheme fixnum) . "types/srfi.143.scm")
((scheme flonum) . "types/srfi.144.scm")
((scheme mapping) . "types/srfi.146.scm")
((scheme mapping hash) . "types/srfi.146.hash.scm")
((scheme regex) . "types/srfi.115.scm")
((scheme show) . "types/srfi.159.scm")
((scheme vector base) . "types/srfi.160.base.scm")
((scheme vector u8) . "types/srfi.160.u8.scm")
((scheme vector s8) . "types/srfi.160.s8.scm")
((scheme vector u16) . "types/srfi.160.u16.scm")
((scheme vector s16) . "types/srfi.160.s16.scm")
((scheme vector u32) . "types/srfi.160.u32.scm")
((scheme vector s32) . "types/srfi.160.s32.scm")
((scheme vector u64) . "types/srfi.160.u64.scm")
((scheme vector s64) . "types/srfi.160.s64.scm")
((scheme vector f32) . "types/srfi.160.f32.scm")
((scheme vector f64) . "types/srfi.160.f64.scm")
((scheme vector c64) . "types/srfi.160.c64.scm")
((scheme vector c128) . "types/srfi.160.c128.scm")
((srfi 0) . "types/srfi.0.scm")
((srfi 1) . "types/srfi.1.scm")
((srfi 2) . "types/srfi.2.scm")
srfi 3 -- withdrawn
((srfi 4) . "types/srfi.4.u8.scm")
((srfi 4) . "types/srfi.4.s8.scm")
((srfi 4) . "types/srfi.4.u16.scm")
((srfi 4) . "types/srfi.4.s16.scm")
((srfi 4) . "types/srfi.4.u32.scm")
((srfi 4) . "types/srfi.4.s32.scm")
((srfi 4) . "types/srfi.4.u64.scm")
((srfi 4) . "types/srfi.4.s64.scm")
((srfi 4) . "types/srfi.4.f32.scm")
((srfi 4) . "types/srfi.4.f64.scm")
((srfi 5) . "types/srfi.5.scm")
((srfi 6) . "types/srfi.6.scm")
;; srfi 7 -- ??
((srfi 8) . "types/srfi.8.scm")
((srfi 9) . "types/srfi.9.scm")
srfi 10 -- syntax
((srfi 11) . "types/srfi.11.scm")
srfi 12 -- withdrawn
((srfi 13) . "types/srfi.13.scm")
((srfi 14) . "types/srfi.14.scm")
srfi 15 -- withdrawn
((srfi 16) . "types/srfi.16.scm")
((srfi 17) . "types/srfi.17.scm")
((srfi 18) . "types/srfi.18.scm")
((srfi 19) . "types/srfi.19.scm")
srfi 20 -- withdrawn
((srfi 21) . "types/srfi.21.scm")
srfi 22 -- non - sexpr syntax
((srfi 23) . "types/srfi.23.scm")
srfi 24 -- withdrawn
((srfi 25) . "types/srfi.25.scm")
((srfi 26) . "types/srfi.26.scm")
((srfi 27) . "types/srfi.27.scm")
((srfi 28) . "types/srfi.28.scm")
((srfi 29) . "types/srfi.29.scm")
srfi 30 -- non - sexpr syntax
((srfi 31) . "types/srfi.31.scm")
srfi 32 -- withdrawn
srfi 33 -- withdrawn
((srfi 34) . "types/srfi.34.scm")
((srfi 35) . "types/srfi.35.scm")
((srfi 36) . "types/srfi.36.scm")
((srfi 37) . "types/srfi.37.scm")
((srfi 38) . "types/srfi.38.scm")
((srfi 39) . "types/srfi.39.scm")
srfi 40 -- superceded
((srfi 41) . "types/srfi.41.scm")
((srfi 42) . "types/srfi.42.scm")
((srfi 43) . "types/srfi.43.scm")
srfi 44 -- " meta " srfi
((srfi 45) . "types/srfi.45.scm")
((srfi 46) . "types/srfi.46.scm")
((srfi 47) . "types/srfi.47.scm")
((srfi 48) . "types/srfi.48.scm")
srfi 49 -- non - sexpr syntax
srfi 50 -- withdrawn
( ( srfi 51 ) . " types / srfi.51.scm " )
srfi 52 -- withdrawn
srfi 53 -- withdrawn
((srfi 54) . "types/srfi.54.scm")
srfi 55 -- ? ?
srfi 56 -- withdrawn
( ( srfi 57 ) . " types / srfi.57.scm " ) TODO
srfi 58 -- non - sexpr syntax
((srfi 59) . "types/srfi.59.scm")
((srfi 60) . "types/srfi.60.scm")
((srfi 61) . "types/srfi.61.scm")
srfi 62 -- non - sexpr syntax
((srfi 63) . "types/srfi.63.scm")
((srfi 64) . "types/srfi.64.scm")
srfi 65 -- withdrawn
((srfi 66) . "types/srfi.66.scm")
((srfi 67) . "types/srfi.67.scm")
srfi 68 -- withdrawn
((srfi 69) . "types/srfi.69.scm")
( ( srfi 70 ) . " types / srfi.70.scm " ) TODO
((srfi 71) . "types/srfi.71.scm")
srfi 72 -- unpopular ( TODO ? )
srfi 73 -- withdrawn
((srfi 74) . "types/srfi.74.scm")
srfi 75 -- withdrawn
srfi 76 -- withdrawn
srfi 77 -- withdrawn
((srfi 78) . "types/srfi.78.scm")
srfi 79 -- withdrawn
srfi 80 -- withdrawn
srfi 81 -- withdrawn
srfi 82 -- withdrawn
srfi 83 -- withdrawn
srfi 84 -- withdrawn
srfi 85 -- withdrawn
( ( srfi 86 ) . " types / srfi.86.scm " ) TODO
((srfi 87) . "types/srfi.87.scm")
((srfi 88) . "types/srfi.88.scm")
( ( srfi 89 ) . " types / srfi.89.scm " ) TODO
( ( srfi 90 ) . " types / srfi.90.scm " ) TODO
srfi 91 -- withdrawn
srfi 92 -- withdrawn
srfi 93 -- withdrawn
( ( srfi 94 ) . " types / srfi.94.scm " ) TODO
((srfi 95) . "types/srfi.95.scm")
( ( srfi 96 ) . " types / srfi.96.scm " ) TODO
( ( srfi 97 ) . " types / srfi.97.scm " ) TODO
((srfi 98) . "types/srfi.98.scm")
((srfi 99) . "types/srfi.99.records.procedural.scm")
((srfi 99) . "types/srfi.99.records.inspection.scm")
((srfi 99) . "types/srfi.99.records.syntactic.scm")
((srfi 99 records procedural) . "types/srfi.99.records.procedural.scm")
((srfi 99 records inspection) . "types/srfi.99.records.inspection.scm")
((srfi 99 records syntactic) . "types/srfi.99.records.syntactic.scm")
( ( srfi 100 ) . " types / srfi.100.scm " ) TODO
((srfi 101) . "types/srfi.101.scm")
srfi 102 -- withdrawn
srfi 103 -- withdrawn
srfi 104 -- withdrawn
srfi 105 -- non - sexpr syntax
( ( srfi 106 ) . " types / srfi.106.scm " ) TODO
srfi 107 -- non - sexpr syntax
srfi 108 -- non - sexpr syntax
srfi 109 -- non - sexpr syntax
srfi 110 -- non - sexpr syntax
((srfi 111) . "types/srfi.111.scm")
((srfi 112) . "types/srfi.112.scm")
((srfi 113) . "types/srfi.113.scm")
srfi 114 -- superceded
((srfi 115) . "types/srfi.115.scm")
((srfi 116) . "types/srfi.116.scm")
((srfi 117) . "types/srfi.117.scm")
( ( srfi 118 ) . " types / srfi.118.scm " ) TODO
srfi 119 -- unpopular ( TODO ? )
( ( srfi 120 ) . " types / srfi.120.scm " ) TODO
srfi 121 -- superceded
srfi 122 -- superceded
( ( srfi 123 ) . " types / srfi.123.scm " ) TODO
((srfi 124) . "types/srfi.124.scm")
((srfi 125) . "types/srfi.125.scm")
( ( srfi 126 ) . " types / srfi.126.scm " ) TODO
((srfi 127) . "types/srfi.127.scm")
((srfi 128) . "types/srfi.128.scm")
((srfi 129) . "types/srfi.129.scm")
((srfi 130) . "types/srfi.130.scm")
((srfi 131) . "types/srfi.99.records.procedural.scm")
((srfi 131) . "types/srfi.99.records.inspection.scm")
((srfi 131) . "types/srfi.131.records.syntactic.scm")
((srfi 131 records procedural) . "types/srfi.99.records.procedural.scm")
((srfi 131 records inspection) . "types/srfi.99.records.inspection.scm")
((srfi 131 records syntactic) . "types/srfi.131.records.syntactic.scm")
((srfi 132) . "types/srfi.132.scm")
((srfi 133) . "types/srfi.133.scm")
((srfi 134) . "types/srfi.134.scm")
((srfi 135) . "types/srfi.135.scm")
( ( srfi 136 ) . " types / srfi.136.scm " ) TODO
( ( srfi 137 ) . " types / srfi.137.scm " ) TODO
( ( srfi 138 ) . " types / srfi.138.scm " ) TODO
( ( srfi 139 ) . " types / srfi.139.scm " ) TODO
( ( srfi 140 ) . " types / srfi.140.scm " ) TODO
((srfi 141) . "types/srfi.141.scm")
srfi 142 -- superceded
((srfi 143) . "types/srfi.143.scm")
((srfi 144) . "types/srfi.144.scm")
((srfi 145) . "types/srfi.145.scm")
((srfi 146) . "types/srfi.146.scm")
((srfi 146 hash) . "types/srfi.146.hash.scm")
( ( srfi 147 ) . " types / srfi.147.scm " ) TODO
srfi 148 -- unpopular ( TODO ? )
( ( srfi 149 ) . " types / srfi.149.scm " ) TODO
srfi 150 -- unpopular ( TODO ? )
((srfi 151) . "types/srfi.151.scm")
((srfi 152) . "types/srfi.152.scm")
srfi 153 -- withdrawn
((srfi 154) . "types/srfi.154.scm")
srfi 155 -- unpopular ( TODO ? )
((srfi 156) . "types/srfi.156.scm")
srfi 157 -- unpopular ( TODO ? )
((srfi 158) . "types/srfi.158.scm")
((srfi 159) . "types/srfi.159.scm")
((srfi 160 base) . "types/srfi.160.base.scm")
((srfi 160 u8) . "types/srfi.160.u8.scm")
((srfi 160 s8) . "types/srfi.160.s8.scm")
((srfi 160 u16) . "types/srfi.160.u16.scm")
((srfi 160 s16) . "types/srfi.160.s16.scm")
((srfi 160 u32) . "types/srfi.160.u32.scm")
((srfi 160 s32) . "types/srfi.160.s32.scm")
((srfi 160 u64) . "types/srfi.160.u64.scm")
((srfi 160 s64) . "types/srfi.160.s64.scm")
((srfi 160 f32) . "types/srfi.160.f32.scm")
((srfi 160 f64) . "types/srfi.160.f64.scm")
((srfi 160 c64) . "types/srfi.160.c64.scm")
((srfi 160 c128) . "types/srfi.160.c128.scm")
((srfi 193) . "types/srfi.193.scm")
((srfi 219) . "types/srfi.219.scm")
;; specific implementation handling
(bigloo . "types/r5rs.scm")
(bigloo . "types/srfi.0.scm")
(bigloo . "types/srfi.2.scm")
(bigloo . "types/srfi.6.scm")
(bigloo . "types/srfi.8.scm")
(bigloo . "types/srfi.9.scm")
(bigloo . "types/srfi.18.scm")
(bigloo . "types/srfi.28.scm")
(bigloo . "types/srfi.34.scm")
)
| null | https://raw.githubusercontent.com/schemeorg-community/index.scheme.org/f93e4454ec03885829fa449b7ec9edc9789afa61/types/index.scm | scheme | r6rs
r7rs small
r7rs large red
r7rs large tangerine
srfi 7 -- ??
specific implementation handling | (
(r5rs . "types/r5rs.scm")
((rnrs base (6)) . "types/rnrs.base.6.scm")
((rnrs arithmetic bitwise (6)) . "types/rnrs.arithmetic.bitwise.6.scm")
((rnrs arithmetic fixnum (6)) . "types/rnrs.arithmetic.fixnum.6.scm")
((rnrs arithmetic flonum (6)) . "types/rnrs.arithmetic.flonum.6.scm")
((rnrs bytevectors (6)) . "types/rnrs.bytevectors.6.scm")
((rnrs conditions (6)) . "types/rnrs.conditions.6.scm")
((rnrs control (6)) . "types/rnrs.control.6.scm")
((rnrs enums (6)) . "types/rnrs.enums.6.scm")
((rnrs eval (6)) . "types/scheme.eval.scm")
((rnrs exceptions (6)) . "types/rnrs.exceptions.6.scm")
((rnrs files (6)) . "types/rnrs.files.6.scm")
((rnrs hashtables (6)) . "types/rnrs.hashtables.6.scm")
((rnrs io ports (6)) . "types/rnrs.io.ports.6.scm")
((rnrs io simple (6)) . "types/rnrs.io.simple.6.scm")
((rnrs lists (6)) . "types/rnrs.lists.6.scm")
((rnrs mutable-pairs (6)) . "types/rnrs.mutable-pairs.6.scm")
((rnrs mutable-strings (6)) . "types/rnrs.mutable-strings.6.scm")
((rnrs programs (6)) . "types/rnrs.programs.6.scm")
((rnrs r5rs (6)) . "types/rnrs.r5rs.6.scm")
((rnrs records inspection (6)) . "types/rnrs.records.inspection.6.scm")
((rnrs records procedural (6)) . "types/rnrs.records.procedural.6.scm")
((rnrs records syntactic (6)) . "types/rnrs.records.syntactic.6.scm")
((rnrs sorting (6)) . "types/rnrs.sorting.6.scm")
((rnrs unicode (6)) . "types/rnrs.unicode.6.scm")
((scheme base) . "types/scheme.base.scm")
((scheme base) . "types/srfi.0.scm")
((scheme base) . "types/srfi.6.scm")
((scheme base) . "types/srfi.9.scm")
((scheme base) . "types/srfi.11.scm")
((scheme base) . "types/srfi.23.scm")
((scheme base) . "types/srfi.34.scm")
((scheme base) . "types/srfi.39.scm")
((scheme case-lambda) . "types/srfi.16.scm")
((scheme complex) . "types/scheme.complex.scm")
((scheme char) . "types/scheme.char.scm")
((scheme cxr) . "types/scheme.cxr.scm")
((scheme eval) . "types/scheme.eval.scm")
((scheme file) . "types/scheme.file.scm")
((scheme inexact) . "types/scheme.inexact.scm")
((scheme lazy) . "types/scheme.lazy.scm")
((scheme load) . "types/scheme.load.scm")
((scheme process-context) . "types/scheme.process-context.scm")
((scheme read) . "types/scheme.read.scm")
((scheme repl) . "types/scheme.repl.scm")
((scheme time) . "types/scheme.time.scm")
((scheme write) . "types/scheme.write.scm")
((scheme r5rs) . ((file . "types/r5rs.scm") (exclude . (transcript-on transcript-off))))
((scheme box) . "types/srfi.111.scm")
((scheme comparator) . "types/srfi.128.scm")
((scheme charset) . "types/srfi.14.scm")
((scheme ephemeron) . "types/srfi.124.scm")
((scheme generator) . "types/srfi.158.scm")
((scheme hash-table) . "types/srfi.125.scm")
((scheme ideque) . "types/srfi.134.scm")
((scheme ilist) . "types/srfi.116.scm")
((scheme list) . "types/srfi.1.scm")
((scheme list-queue) . "types/srfi.117.scm")
((scheme lseq) . "types/srfi.127.scm")
((scheme rlist) . "types/srfi.101.scm")
((scheme set) . "types/srfi.113.scm")
((scheme stream) . "types/srfi.41.scm")
((scheme sort) . "types/srfi.132.scm")
((scheme text) . "types/srfi.135.scm")
((scheme vector) . "types/srfi.133.scm")
((scheme bitwise) . "types/srfi.151.scm")
((scheme bytevector) . "types/rnrs.bytevectors.6.scm")
((scheme division) . "types/srfi.141.scm")
((scheme fixnum) . "types/srfi.143.scm")
((scheme flonum) . "types/srfi.144.scm")
((scheme mapping) . "types/srfi.146.scm")
((scheme mapping hash) . "types/srfi.146.hash.scm")
((scheme regex) . "types/srfi.115.scm")
((scheme show) . "types/srfi.159.scm")
((scheme vector base) . "types/srfi.160.base.scm")
((scheme vector u8) . "types/srfi.160.u8.scm")
((scheme vector s8) . "types/srfi.160.s8.scm")
((scheme vector u16) . "types/srfi.160.u16.scm")
((scheme vector s16) . "types/srfi.160.s16.scm")
((scheme vector u32) . "types/srfi.160.u32.scm")
((scheme vector s32) . "types/srfi.160.s32.scm")
((scheme vector u64) . "types/srfi.160.u64.scm")
((scheme vector s64) . "types/srfi.160.s64.scm")
((scheme vector f32) . "types/srfi.160.f32.scm")
((scheme vector f64) . "types/srfi.160.f64.scm")
((scheme vector c64) . "types/srfi.160.c64.scm")
((scheme vector c128) . "types/srfi.160.c128.scm")
((srfi 0) . "types/srfi.0.scm")
((srfi 1) . "types/srfi.1.scm")
((srfi 2) . "types/srfi.2.scm")
srfi 3 -- withdrawn
((srfi 4) . "types/srfi.4.u8.scm")
((srfi 4) . "types/srfi.4.s8.scm")
((srfi 4) . "types/srfi.4.u16.scm")
((srfi 4) . "types/srfi.4.s16.scm")
((srfi 4) . "types/srfi.4.u32.scm")
((srfi 4) . "types/srfi.4.s32.scm")
((srfi 4) . "types/srfi.4.u64.scm")
((srfi 4) . "types/srfi.4.s64.scm")
((srfi 4) . "types/srfi.4.f32.scm")
((srfi 4) . "types/srfi.4.f64.scm")
((srfi 5) . "types/srfi.5.scm")
((srfi 6) . "types/srfi.6.scm")
((srfi 8) . "types/srfi.8.scm")
((srfi 9) . "types/srfi.9.scm")
srfi 10 -- syntax
((srfi 11) . "types/srfi.11.scm")
srfi 12 -- withdrawn
((srfi 13) . "types/srfi.13.scm")
((srfi 14) . "types/srfi.14.scm")
srfi 15 -- withdrawn
((srfi 16) . "types/srfi.16.scm")
((srfi 17) . "types/srfi.17.scm")
((srfi 18) . "types/srfi.18.scm")
((srfi 19) . "types/srfi.19.scm")
srfi 20 -- withdrawn
((srfi 21) . "types/srfi.21.scm")
srfi 22 -- non - sexpr syntax
((srfi 23) . "types/srfi.23.scm")
srfi 24 -- withdrawn
((srfi 25) . "types/srfi.25.scm")
((srfi 26) . "types/srfi.26.scm")
((srfi 27) . "types/srfi.27.scm")
((srfi 28) . "types/srfi.28.scm")
((srfi 29) . "types/srfi.29.scm")
srfi 30 -- non - sexpr syntax
((srfi 31) . "types/srfi.31.scm")
srfi 32 -- withdrawn
srfi 33 -- withdrawn
((srfi 34) . "types/srfi.34.scm")
((srfi 35) . "types/srfi.35.scm")
((srfi 36) . "types/srfi.36.scm")
((srfi 37) . "types/srfi.37.scm")
((srfi 38) . "types/srfi.38.scm")
((srfi 39) . "types/srfi.39.scm")
srfi 40 -- superceded
((srfi 41) . "types/srfi.41.scm")
((srfi 42) . "types/srfi.42.scm")
((srfi 43) . "types/srfi.43.scm")
srfi 44 -- " meta " srfi
((srfi 45) . "types/srfi.45.scm")
((srfi 46) . "types/srfi.46.scm")
((srfi 47) . "types/srfi.47.scm")
((srfi 48) . "types/srfi.48.scm")
srfi 49 -- non - sexpr syntax
srfi 50 -- withdrawn
( ( srfi 51 ) . " types / srfi.51.scm " )
srfi 52 -- withdrawn
srfi 53 -- withdrawn
((srfi 54) . "types/srfi.54.scm")
srfi 55 -- ? ?
srfi 56 -- withdrawn
( ( srfi 57 ) . " types / srfi.57.scm " ) TODO
srfi 58 -- non - sexpr syntax
((srfi 59) . "types/srfi.59.scm")
((srfi 60) . "types/srfi.60.scm")
((srfi 61) . "types/srfi.61.scm")
srfi 62 -- non - sexpr syntax
((srfi 63) . "types/srfi.63.scm")
((srfi 64) . "types/srfi.64.scm")
srfi 65 -- withdrawn
((srfi 66) . "types/srfi.66.scm")
((srfi 67) . "types/srfi.67.scm")
srfi 68 -- withdrawn
((srfi 69) . "types/srfi.69.scm")
( ( srfi 70 ) . " types / srfi.70.scm " ) TODO
((srfi 71) . "types/srfi.71.scm")
srfi 72 -- unpopular ( TODO ? )
srfi 73 -- withdrawn
((srfi 74) . "types/srfi.74.scm")
srfi 75 -- withdrawn
srfi 76 -- withdrawn
srfi 77 -- withdrawn
((srfi 78) . "types/srfi.78.scm")
srfi 79 -- withdrawn
srfi 80 -- withdrawn
srfi 81 -- withdrawn
srfi 82 -- withdrawn
srfi 83 -- withdrawn
srfi 84 -- withdrawn
srfi 85 -- withdrawn
( ( srfi 86 ) . " types / srfi.86.scm " ) TODO
((srfi 87) . "types/srfi.87.scm")
((srfi 88) . "types/srfi.88.scm")
( ( srfi 89 ) . " types / srfi.89.scm " ) TODO
( ( srfi 90 ) . " types / srfi.90.scm " ) TODO
srfi 91 -- withdrawn
srfi 92 -- withdrawn
srfi 93 -- withdrawn
( ( srfi 94 ) . " types / srfi.94.scm " ) TODO
((srfi 95) . "types/srfi.95.scm")
( ( srfi 96 ) . " types / srfi.96.scm " ) TODO
( ( srfi 97 ) . " types / srfi.97.scm " ) TODO
((srfi 98) . "types/srfi.98.scm")
((srfi 99) . "types/srfi.99.records.procedural.scm")
((srfi 99) . "types/srfi.99.records.inspection.scm")
((srfi 99) . "types/srfi.99.records.syntactic.scm")
((srfi 99 records procedural) . "types/srfi.99.records.procedural.scm")
((srfi 99 records inspection) . "types/srfi.99.records.inspection.scm")
((srfi 99 records syntactic) . "types/srfi.99.records.syntactic.scm")
( ( srfi 100 ) . " types / srfi.100.scm " ) TODO
((srfi 101) . "types/srfi.101.scm")
srfi 102 -- withdrawn
srfi 103 -- withdrawn
srfi 104 -- withdrawn
srfi 105 -- non - sexpr syntax
( ( srfi 106 ) . " types / srfi.106.scm " ) TODO
srfi 107 -- non - sexpr syntax
srfi 108 -- non - sexpr syntax
srfi 109 -- non - sexpr syntax
srfi 110 -- non - sexpr syntax
((srfi 111) . "types/srfi.111.scm")
((srfi 112) . "types/srfi.112.scm")
((srfi 113) . "types/srfi.113.scm")
srfi 114 -- superceded
((srfi 115) . "types/srfi.115.scm")
((srfi 116) . "types/srfi.116.scm")
((srfi 117) . "types/srfi.117.scm")
( ( srfi 118 ) . " types / srfi.118.scm " ) TODO
srfi 119 -- unpopular ( TODO ? )
( ( srfi 120 ) . " types / srfi.120.scm " ) TODO
srfi 121 -- superceded
srfi 122 -- superceded
( ( srfi 123 ) . " types / srfi.123.scm " ) TODO
((srfi 124) . "types/srfi.124.scm")
((srfi 125) . "types/srfi.125.scm")
( ( srfi 126 ) . " types / srfi.126.scm " ) TODO
((srfi 127) . "types/srfi.127.scm")
((srfi 128) . "types/srfi.128.scm")
((srfi 129) . "types/srfi.129.scm")
((srfi 130) . "types/srfi.130.scm")
((srfi 131) . "types/srfi.99.records.procedural.scm")
((srfi 131) . "types/srfi.99.records.inspection.scm")
((srfi 131) . "types/srfi.131.records.syntactic.scm")
((srfi 131 records procedural) . "types/srfi.99.records.procedural.scm")
((srfi 131 records inspection) . "types/srfi.99.records.inspection.scm")
((srfi 131 records syntactic) . "types/srfi.131.records.syntactic.scm")
((srfi 132) . "types/srfi.132.scm")
((srfi 133) . "types/srfi.133.scm")
((srfi 134) . "types/srfi.134.scm")
((srfi 135) . "types/srfi.135.scm")
( ( srfi 136 ) . " types / srfi.136.scm " ) TODO
( ( srfi 137 ) . " types / srfi.137.scm " ) TODO
( ( srfi 138 ) . " types / srfi.138.scm " ) TODO
( ( srfi 139 ) . " types / srfi.139.scm " ) TODO
( ( srfi 140 ) . " types / srfi.140.scm " ) TODO
((srfi 141) . "types/srfi.141.scm")
srfi 142 -- superceded
((srfi 143) . "types/srfi.143.scm")
((srfi 144) . "types/srfi.144.scm")
((srfi 145) . "types/srfi.145.scm")
((srfi 146) . "types/srfi.146.scm")
((srfi 146 hash) . "types/srfi.146.hash.scm")
( ( srfi 147 ) . " types / srfi.147.scm " ) TODO
srfi 148 -- unpopular ( TODO ? )
( ( srfi 149 ) . " types / srfi.149.scm " ) TODO
srfi 150 -- unpopular ( TODO ? )
((srfi 151) . "types/srfi.151.scm")
((srfi 152) . "types/srfi.152.scm")
srfi 153 -- withdrawn
((srfi 154) . "types/srfi.154.scm")
srfi 155 -- unpopular ( TODO ? )
((srfi 156) . "types/srfi.156.scm")
srfi 157 -- unpopular ( TODO ? )
((srfi 158) . "types/srfi.158.scm")
((srfi 159) . "types/srfi.159.scm")
((srfi 160 base) . "types/srfi.160.base.scm")
((srfi 160 u8) . "types/srfi.160.u8.scm")
((srfi 160 s8) . "types/srfi.160.s8.scm")
((srfi 160 u16) . "types/srfi.160.u16.scm")
((srfi 160 s16) . "types/srfi.160.s16.scm")
((srfi 160 u32) . "types/srfi.160.u32.scm")
((srfi 160 s32) . "types/srfi.160.s32.scm")
((srfi 160 u64) . "types/srfi.160.u64.scm")
((srfi 160 s64) . "types/srfi.160.s64.scm")
((srfi 160 f32) . "types/srfi.160.f32.scm")
((srfi 160 f64) . "types/srfi.160.f64.scm")
((srfi 160 c64) . "types/srfi.160.c64.scm")
((srfi 160 c128) . "types/srfi.160.c128.scm")
((srfi 193) . "types/srfi.193.scm")
((srfi 219) . "types/srfi.219.scm")
(bigloo . "types/r5rs.scm")
(bigloo . "types/srfi.0.scm")
(bigloo . "types/srfi.2.scm")
(bigloo . "types/srfi.6.scm")
(bigloo . "types/srfi.8.scm")
(bigloo . "types/srfi.9.scm")
(bigloo . "types/srfi.18.scm")
(bigloo . "types/srfi.28.scm")
(bigloo . "types/srfi.34.scm")
)
|
2c6319537fe8dd90aa08d434595ffa63976e21d8f7591a0508be77112bc227c7 | xh4/web-toolkit | functions.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; functions.lisp --- High-level interface to foreign functions.
;;;
Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2005 - 2007 ,
;;;
;;; 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.
;;;
(in-package #:cffi)
;;;# Calling Foreign Functions
;;;
;;; FOREIGN-FUNCALL is the main primitive for calling foreign
;;; functions. It converts each argument based on the installed
;;; translators for its type, then passes the resulting list to
;;; CFFI-SYS:%FOREIGN-FUNCALL.
;;;
For implementation - specific reasons , DEFCFUN does n't use
;;; FOREIGN-FUNCALL directly and might use something else (passed to
;;; TRANSLATE-OBJECTS as the CALL-FORM argument) instead of
;;; CFFI-SYS:%FOREIGN-FUNCALL to call the foreign-function.
(defun translate-objects (syms args types rettype call-form &optional indirect)
"Helper function for FOREIGN-FUNCALL and DEFCFUN. If 'indirect is T, all arguments are represented by foreign pointers, even those that can be represented by CL objects."
(if (null args)
(expand-from-foreign call-form (parse-type rettype))
(funcall
(if indirect
#'expand-to-foreign-dyn-indirect
#'expand-to-foreign-dyn)
(car args) (car syms)
(list (translate-objects (cdr syms) (cdr args)
(cdr types) rettype call-form indirect))
(parse-type (car types)))))
(defun parse-args-and-types (args)
"Returns 4 values: types, canonicalized types, args and return type."
(let* ((len (length args))
(return-type (if (oddp len) (lastcar args) :void)))
(loop repeat (floor len 2)
for (type arg) on args by #'cddr
collect type into types
collect (canonicalize-foreign-type type) into ctypes
collect arg into fargs
finally (return (values types ctypes fargs return-type)))))
While the options passed directly to DEFCFUN / FOREIGN - FUNCALL have
;;; precedence, we also grab its library's options, if possible.
(defun parse-function-options (options &key pointer)
(destructuring-bind (&key (library :default libraryp)
(cconv nil cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list* :convention
(or convention
(when libraryp
(let ((lib-options (foreign-library-options
(get-foreign-library library))))
(getf lib-options :convention)))
:cdecl)
;; Don't pass the library option if we're dealing with
;; FOREIGN-FUNCALL-POINTER.
(unless pointer
(list :library library)))))
(defun structure-by-value-p (ctype)
"A structure or union is to be called or returned by value."
(let ((actual-type (ensure-parsed-base-type ctype)))
(or (and (typep actual-type 'foreign-struct-type)
(not (bare-struct-type-p actual-type)))
#+cffi::no-long-long (typep actual-type 'emulated-llong-type))))
(defun fn-call-by-value-p (argument-types return-type)
"One or more structures in the arguments or return from the function are called by value."
(or (some 'structure-by-value-p argument-types)
(structure-by-value-p return-type)))
(defvar *foreign-structures-by-value*
(lambda (&rest args)
(declare (ignore args))
(restart-case
(error "Unable to call structures by value without cffi-libffi loaded.")
(load-cffi-libffi () :report "Load cffi-libffi."
(asdf:operate 'asdf:load-op 'cffi-libffi))))
"A function that produces a form suitable for calling structures by value.")
(defun foreign-funcall-form (thing options args pointerp)
(multiple-value-bind (types ctypes fargs rettype)
(parse-args-and-types args)
(let ((syms (make-gensym-list (length fargs)))
(fsbvp (fn-call-by-value-p ctypes rettype)))
(if fsbvp
;; Structures by value call through *foreign-structures-by-value*
(funcall *foreign-structures-by-value*
thing
fargs
syms
types
rettype
ctypes
pointerp)
(translate-objects
syms fargs types rettype
`(,(if pointerp '%foreign-funcall-pointer '%foreign-funcall)
;; No structures by value, direct call
,thing
(,@(mapcan #'list ctypes syms)
,(canonicalize-foreign-type rettype))
,@(parse-function-options options :pointer pointerp)))))))
(defmacro foreign-funcall (name-and-options &rest args)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-form name options args nil)))
(defmacro foreign-funcall-pointer (pointer options &rest args)
(foreign-funcall-form pointer options args t))
(defun promote-varargs-type (builtin-type)
"Default argument promotions."
(case builtin-type
(:float :double)
((:char :short) :int)
((:unsigned-char :unsigned-short) :unsigned-int)
(t builtin-type)))
;; If cffi-sys doesn't provide a %foreign-funcall-varargs macros we
;; define one that use %foreign-funcall.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp '%foreign-funcall-varargs)
(defmacro %foreign-funcall-varargs (name fixed-args varargs
&rest args &key convention library)
(declare (ignore convention library))
`(%foreign-funcall ,name ,(append fixed-args varargs) ,@args)))
(unless (fboundp '%foreign-funcall-pointer-varargs)
(defmacro %foreign-funcall-pointer-varargs (pointer fixed-args varargs
&rest args &key convention)
(declare (ignore convention))
`(%foreign-funcall-pointer ,pointer ,(append fixed-args varargs) ,@args))))
(defun foreign-funcall-varargs-form (thing options fixed-args varargs pointerp)
(multiple-value-bind (fixed-types fixed-ctypes fixed-fargs)
(parse-args-and-types fixed-args)
(multiple-value-bind (varargs-types varargs-ctypes varargs-fargs rettype)
(parse-args-and-types varargs)
(let ((fixed-syms (make-gensym-list (length fixed-fargs)))
(varargs-syms (make-gensym-list (length varargs-fargs))))
(translate-objects
(append fixed-syms varargs-syms)
(append fixed-fargs varargs-fargs)
(append fixed-types varargs-types)
rettype
`(,(if pointerp '%foreign-funcall-pointer-varargs '%foreign-funcall-varargs)
,thing
,(mapcan #'list fixed-ctypes fixed-syms)
,(append
(mapcan #'list
(mapcar #'promote-varargs-type varargs-ctypes)
(loop for sym in varargs-syms
and type in varargs-ctypes
if (eq type :float)
collect `(float ,sym 1.0d0)
else collect sym))
(list (canonicalize-foreign-type rettype)))
,@options))))))
(defmacro foreign-funcall-varargs (name-and-options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments
and does type promotion for the variadic arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-varargs-form name options fixed-args varargs nil)))
(defmacro foreign-funcall-pointer-varargs (pointer options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL-POINTER that translates its
arguments and does type promotion for the variadic arguments."
(foreign-funcall-varargs-form pointer options fixed-args varargs t))
;;;# Defining Foreign Functions
;;;
The DEFCFUN macro provides a declarative interface for defining
;;; Lisp functions that call foreign functions.
;; If cffi-sys doesn't provide a defcfun-helper-forms,
;; we define one that uses %foreign-funcall.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp 'defcfun-helper-forms)
(defun defcfun-helper-forms (name lisp-name rettype args types options)
(declare (ignore lisp-name))
(values
'()
`(%foreign-funcall ,name ,(append (mapcan #'list types args)
(list rettype))
,@options)))))
(defun %defcfun (lisp-name foreign-name return-type args options docstring)
(let* ((arg-names (mapcar #'first args))
(arg-types (mapcar #'second args))
(syms (make-gensym-list (length args)))
(call-by-value (fn-call-by-value-p arg-types return-type)))
(multiple-value-bind (prelude caller)
(if call-by-value
(values nil nil)
(defcfun-helper-forms
foreign-name lisp-name (canonicalize-foreign-type return-type)
syms (mapcar #'canonicalize-foreign-type arg-types) options))
`(progn
,prelude
(defun ,lisp-name ,arg-names
,@(ensure-list docstring)
,(if call-by-value
`(foreign-funcall
,(cons foreign-name options)
,@(append (mapcan #'list arg-types arg-names)
(list return-type)))
(translate-objects
syms arg-names arg-types return-type caller)))))))
(defun %defcfun-varargs (lisp-name foreign-name return-type args options doc)
(with-unique-names (varargs)
(let ((arg-names (mapcar #'car args)))
`(defmacro ,lisp-name (,@arg-names &rest ,varargs)
,@(ensure-list doc)
`(foreign-funcall-varargs
,'(,foreign-name ,@options)
,,`(list ,@(loop for (name type) in args
collect `',type collect name))
,@,varargs
,',return-type)))))
(defgeneric translate-underscore-separated-name (name)
(:method ((name string))
(values (intern (canonicalize-symbol-name-case (substitute #\- #\_ name)))))
(:method ((name symbol))
(substitute #\_ #\- (string-downcase (symbol-name name)))))
(defun collapse-prefix (l special-words)
(unless (null l)
(multiple-value-bind (newpre skip) (check-prefix l special-words)
(cons newpre (collapse-prefix (nthcdr skip l) special-words)))))
(defun check-prefix (l special-words)
(let ((pl (loop for i from (1- (length l)) downto 0
collect (apply #'concatenate 'simple-string (butlast l i)))))
(loop for w in special-words
for p = (position-if #'(lambda (s) (string= s w)) pl)
when p do (return-from check-prefix (values (nth p pl) (1+ p))))
(values (first l) 1)))
(defgeneric translate-camelcase-name (name &key upper-initial-p special-words)
(:method ((name string) &key upper-initial-p special-words)
(declare (ignore upper-initial-p))
(values (intern (reduce #'(lambda (s1 s2)
(concatenate 'simple-string s1 "-" s2))
(mapcar #'string-upcase
(collapse-prefix
(split-if #'(lambda (ch)
(or (upper-case-p ch)
(digit-char-p ch)))
name)
special-words))))))
(:method ((name symbol) &key upper-initial-p special-words)
(apply #'concatenate
'string
(loop for str in (split-if #'(lambda (ch) (eq ch #\-))
(string name)
:elide)
for first-word-p = t then nil
for e = (member str special-words
:test #'equal :key #'string-upcase)
collect (cond
((and first-word-p (not upper-initial-p))
(string-downcase str))
(e (first e))
(t (string-capitalize str)))))))
(defgeneric translate-name-from-foreign (foreign-name package &optional varp)
(:method (foreign-name package &optional varp)
(declare (ignore package))
(let ((sym (translate-underscore-separated-name foreign-name)))
(if varp
(values (intern (format nil "*~A*"
(canonicalize-symbol-name-case
(symbol-name sym)))))
sym))))
(defgeneric translate-name-to-foreign (lisp-name package &optional varp)
(:method (lisp-name package &optional varp)
(declare (ignore package))
(let ((name (translate-underscore-separated-name lisp-name)))
(if varp
(string-trim '(#\*) name)
name))))
(defun lisp-name (spec varp)
(check-type spec string)
(translate-name-from-foreign spec *package* varp))
(defun foreign-name (spec varp)
(check-type spec (and symbol (not null)))
(translate-name-to-foreign spec *package* varp))
(defun foreign-options (opts varp)
(if varp
(funcall 'parse-defcvar-options opts)
(parse-function-options opts)))
(defun lisp-name-p (name)
(and name (symbolp name) (not (keywordp name))))
(defun %parse-name-and-options (spec varp)
(cond
((stringp spec)
(values (lisp-name spec varp) spec nil))
((symbolp spec)
(assert (not (null spec)))
(values spec (foreign-name spec varp) nil))
((and (consp spec) (stringp (first spec)))
(destructuring-bind (foreign-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values (lisp-name foreign-name varp) foreign-name options))
(t
(assert (lisp-name-p (first options)))
(values (first options) foreign-name (rest options))))))
((and (consp spec) (lisp-name-p (first spec)))
(destructuring-bind (lisp-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values lisp-name (foreign-name spec varp) options))
(t
(assert (stringp (first options)))
(values lisp-name (first options) (rest options))))))
(t
(error "Not a valid foreign function specifier: ~A" spec))))
DEFCFUN 's first argument has can have the following syntax :
;;;
1 . string
2 . symbol
3 . \ ( string [ symbol ] options * )
4 . \ ( symbol [ string ] options * )
;;;
;;; The string argument denotes the foreign function's name. The
;;; symbol argument is used to name the Lisp function. If one isn't
;;; present, its name is derived from the other. See the user
;;; documentation for an explanation of the derivation rules.
(defun parse-name-and-options (spec &optional varp)
(multiple-value-bind (lisp-name foreign-name options)
(%parse-name-and-options spec varp)
(values lisp-name foreign-name (foreign-options options varp))))
;;; If we find a &REST token at the end of ARGS, it means this is a
;;; varargs foreign function therefore we define a lisp macro using
;;; %DEFCFUN-VARARGS. Otherwise, a lisp function is defined with
% DEFCFUN .
(defmacro defcfun (name-and-options return-type &body args)
"Defines a Lisp function that calls a foreign function."
(let ((docstring (when (stringp (car args)) (pop args))))
(multiple-value-bind (lisp-name foreign-name options)
(parse-name-and-options name-and-options)
(if (eq (lastcar args) '&rest)
(%defcfun-varargs lisp-name foreign-name return-type
(butlast args) options docstring)
(%defcfun lisp-name foreign-name return-type args options
docstring)))))
;;;# Defining Callbacks
(defun inverse-translate-objects (args types declarations rettype call)
`(let (,@(loop for arg in args and type in types
collect (list arg (expand-from-foreign
arg (parse-type type)))))
,@declarations
,(expand-to-foreign call (parse-type rettype))))
(defun parse-defcallback-options (options)
(destructuring-bind (&key (cconv :cdecl cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list :convention convention)))
(defmacro defcallback (name-and-options return-type args &body body)
(multiple-value-bind (body declarations)
(parse-body body :documentation t)
(let ((arg-names (mapcar #'car args))
(arg-types (mapcar #'cadr args))
(name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
`(progn
(%defcallback ,name ,(canonicalize-foreign-type return-type)
,arg-names ,(mapcar #'canonicalize-foreign-type arg-types)
,(inverse-translate-objects
arg-names arg-types declarations return-type
`(block ,name ,@body))
,@(parse-defcallback-options options))
',name))))
(declaim (inline get-callback))
(defun get-callback (symbol)
(%callback symbol))
(defmacro callback (name)
`(%callback ',name))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cffi_0.20.1/src/functions.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
functions.lisp --- High-level interface to foreign functions.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
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.
# Calling Foreign Functions
FOREIGN-FUNCALL is the main primitive for calling foreign
functions. It converts each argument based on the installed
translators for its type, then passes the resulting list to
CFFI-SYS:%FOREIGN-FUNCALL.
FOREIGN-FUNCALL directly and might use something else (passed to
TRANSLATE-OBJECTS as the CALL-FORM argument) instead of
CFFI-SYS:%FOREIGN-FUNCALL to call the foreign-function.
precedence, we also grab its library's options, if possible.
Don't pass the library option if we're dealing with
FOREIGN-FUNCALL-POINTER.
Structures by value call through *foreign-structures-by-value*
No structures by value, direct call
If cffi-sys doesn't provide a %foreign-funcall-varargs macros we
define one that use %foreign-funcall.
# Defining Foreign Functions
Lisp functions that call foreign functions.
If cffi-sys doesn't provide a defcfun-helper-forms,
we define one that uses %foreign-funcall.
The string argument denotes the foreign function's name. The
symbol argument is used to name the Lisp function. If one isn't
present, its name is derived from the other. See the user
documentation for an explanation of the derivation rules.
If we find a &REST token at the end of ARGS, it means this is a
varargs foreign function therefore we define a lisp macro using
%DEFCFUN-VARARGS. Otherwise, a lisp function is defined with
# Defining Callbacks | Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2005 - 2007 ,
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:cffi)
For implementation - specific reasons , DEFCFUN does n't use
(defun translate-objects (syms args types rettype call-form &optional indirect)
"Helper function for FOREIGN-FUNCALL and DEFCFUN. If 'indirect is T, all arguments are represented by foreign pointers, even those that can be represented by CL objects."
(if (null args)
(expand-from-foreign call-form (parse-type rettype))
(funcall
(if indirect
#'expand-to-foreign-dyn-indirect
#'expand-to-foreign-dyn)
(car args) (car syms)
(list (translate-objects (cdr syms) (cdr args)
(cdr types) rettype call-form indirect))
(parse-type (car types)))))
(defun parse-args-and-types (args)
"Returns 4 values: types, canonicalized types, args and return type."
(let* ((len (length args))
(return-type (if (oddp len) (lastcar args) :void)))
(loop repeat (floor len 2)
for (type arg) on args by #'cddr
collect type into types
collect (canonicalize-foreign-type type) into ctypes
collect arg into fargs
finally (return (values types ctypes fargs return-type)))))
While the options passed directly to DEFCFUN / FOREIGN - FUNCALL have
(defun parse-function-options (options &key pointer)
(destructuring-bind (&key (library :default libraryp)
(cconv nil cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list* :convention
(or convention
(when libraryp
(let ((lib-options (foreign-library-options
(get-foreign-library library))))
(getf lib-options :convention)))
:cdecl)
(unless pointer
(list :library library)))))
(defun structure-by-value-p (ctype)
"A structure or union is to be called or returned by value."
(let ((actual-type (ensure-parsed-base-type ctype)))
(or (and (typep actual-type 'foreign-struct-type)
(not (bare-struct-type-p actual-type)))
#+cffi::no-long-long (typep actual-type 'emulated-llong-type))))
(defun fn-call-by-value-p (argument-types return-type)
"One or more structures in the arguments or return from the function are called by value."
(or (some 'structure-by-value-p argument-types)
(structure-by-value-p return-type)))
(defvar *foreign-structures-by-value*
(lambda (&rest args)
(declare (ignore args))
(restart-case
(error "Unable to call structures by value without cffi-libffi loaded.")
(load-cffi-libffi () :report "Load cffi-libffi."
(asdf:operate 'asdf:load-op 'cffi-libffi))))
"A function that produces a form suitable for calling structures by value.")
(defun foreign-funcall-form (thing options args pointerp)
(multiple-value-bind (types ctypes fargs rettype)
(parse-args-and-types args)
(let ((syms (make-gensym-list (length fargs)))
(fsbvp (fn-call-by-value-p ctypes rettype)))
(if fsbvp
(funcall *foreign-structures-by-value*
thing
fargs
syms
types
rettype
ctypes
pointerp)
(translate-objects
syms fargs types rettype
`(,(if pointerp '%foreign-funcall-pointer '%foreign-funcall)
,thing
(,@(mapcan #'list ctypes syms)
,(canonicalize-foreign-type rettype))
,@(parse-function-options options :pointer pointerp)))))))
(defmacro foreign-funcall (name-and-options &rest args)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-form name options args nil)))
(defmacro foreign-funcall-pointer (pointer options &rest args)
(foreign-funcall-form pointer options args t))
(defun promote-varargs-type (builtin-type)
"Default argument promotions."
(case builtin-type
(:float :double)
((:char :short) :int)
((:unsigned-char :unsigned-short) :unsigned-int)
(t builtin-type)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp '%foreign-funcall-varargs)
(defmacro %foreign-funcall-varargs (name fixed-args varargs
&rest args &key convention library)
(declare (ignore convention library))
`(%foreign-funcall ,name ,(append fixed-args varargs) ,@args)))
(unless (fboundp '%foreign-funcall-pointer-varargs)
(defmacro %foreign-funcall-pointer-varargs (pointer fixed-args varargs
&rest args &key convention)
(declare (ignore convention))
`(%foreign-funcall-pointer ,pointer ,(append fixed-args varargs) ,@args))))
(defun foreign-funcall-varargs-form (thing options fixed-args varargs pointerp)
(multiple-value-bind (fixed-types fixed-ctypes fixed-fargs)
(parse-args-and-types fixed-args)
(multiple-value-bind (varargs-types varargs-ctypes varargs-fargs rettype)
(parse-args-and-types varargs)
(let ((fixed-syms (make-gensym-list (length fixed-fargs)))
(varargs-syms (make-gensym-list (length varargs-fargs))))
(translate-objects
(append fixed-syms varargs-syms)
(append fixed-fargs varargs-fargs)
(append fixed-types varargs-types)
rettype
`(,(if pointerp '%foreign-funcall-pointer-varargs '%foreign-funcall-varargs)
,thing
,(mapcan #'list fixed-ctypes fixed-syms)
,(append
(mapcan #'list
(mapcar #'promote-varargs-type varargs-ctypes)
(loop for sym in varargs-syms
and type in varargs-ctypes
if (eq type :float)
collect `(float ,sym 1.0d0)
else collect sym))
(list (canonicalize-foreign-type rettype)))
,@options))))))
(defmacro foreign-funcall-varargs (name-and-options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL that translates its arguments
and does type promotion for the variadic arguments."
(let ((name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
(foreign-funcall-varargs-form name options fixed-args varargs nil)))
(defmacro foreign-funcall-pointer-varargs (pointer options fixed-args
&rest varargs)
"Wrapper around %FOREIGN-FUNCALL-POINTER that translates its
arguments and does type promotion for the variadic arguments."
(foreign-funcall-varargs-form pointer options fixed-args varargs t))
The DEFCFUN macro provides a declarative interface for defining
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp 'defcfun-helper-forms)
(defun defcfun-helper-forms (name lisp-name rettype args types options)
(declare (ignore lisp-name))
(values
'()
`(%foreign-funcall ,name ,(append (mapcan #'list types args)
(list rettype))
,@options)))))
(defun %defcfun (lisp-name foreign-name return-type args options docstring)
(let* ((arg-names (mapcar #'first args))
(arg-types (mapcar #'second args))
(syms (make-gensym-list (length args)))
(call-by-value (fn-call-by-value-p arg-types return-type)))
(multiple-value-bind (prelude caller)
(if call-by-value
(values nil nil)
(defcfun-helper-forms
foreign-name lisp-name (canonicalize-foreign-type return-type)
syms (mapcar #'canonicalize-foreign-type arg-types) options))
`(progn
,prelude
(defun ,lisp-name ,arg-names
,@(ensure-list docstring)
,(if call-by-value
`(foreign-funcall
,(cons foreign-name options)
,@(append (mapcan #'list arg-types arg-names)
(list return-type)))
(translate-objects
syms arg-names arg-types return-type caller)))))))
(defun %defcfun-varargs (lisp-name foreign-name return-type args options doc)
(with-unique-names (varargs)
(let ((arg-names (mapcar #'car args)))
`(defmacro ,lisp-name (,@arg-names &rest ,varargs)
,@(ensure-list doc)
`(foreign-funcall-varargs
,'(,foreign-name ,@options)
,,`(list ,@(loop for (name type) in args
collect `',type collect name))
,@,varargs
,',return-type)))))
(defgeneric translate-underscore-separated-name (name)
(:method ((name string))
(values (intern (canonicalize-symbol-name-case (substitute #\- #\_ name)))))
(:method ((name symbol))
(substitute #\_ #\- (string-downcase (symbol-name name)))))
(defun collapse-prefix (l special-words)
(unless (null l)
(multiple-value-bind (newpre skip) (check-prefix l special-words)
(cons newpre (collapse-prefix (nthcdr skip l) special-words)))))
(defun check-prefix (l special-words)
(let ((pl (loop for i from (1- (length l)) downto 0
collect (apply #'concatenate 'simple-string (butlast l i)))))
(loop for w in special-words
for p = (position-if #'(lambda (s) (string= s w)) pl)
when p do (return-from check-prefix (values (nth p pl) (1+ p))))
(values (first l) 1)))
(defgeneric translate-camelcase-name (name &key upper-initial-p special-words)
(:method ((name string) &key upper-initial-p special-words)
(declare (ignore upper-initial-p))
(values (intern (reduce #'(lambda (s1 s2)
(concatenate 'simple-string s1 "-" s2))
(mapcar #'string-upcase
(collapse-prefix
(split-if #'(lambda (ch)
(or (upper-case-p ch)
(digit-char-p ch)))
name)
special-words))))))
(:method ((name symbol) &key upper-initial-p special-words)
(apply #'concatenate
'string
(loop for str in (split-if #'(lambda (ch) (eq ch #\-))
(string name)
:elide)
for first-word-p = t then nil
for e = (member str special-words
:test #'equal :key #'string-upcase)
collect (cond
((and first-word-p (not upper-initial-p))
(string-downcase str))
(e (first e))
(t (string-capitalize str)))))))
(defgeneric translate-name-from-foreign (foreign-name package &optional varp)
(:method (foreign-name package &optional varp)
(declare (ignore package))
(let ((sym (translate-underscore-separated-name foreign-name)))
(if varp
(values (intern (format nil "*~A*"
(canonicalize-symbol-name-case
(symbol-name sym)))))
sym))))
(defgeneric translate-name-to-foreign (lisp-name package &optional varp)
(:method (lisp-name package &optional varp)
(declare (ignore package))
(let ((name (translate-underscore-separated-name lisp-name)))
(if varp
(string-trim '(#\*) name)
name))))
(defun lisp-name (spec varp)
(check-type spec string)
(translate-name-from-foreign spec *package* varp))
(defun foreign-name (spec varp)
(check-type spec (and symbol (not null)))
(translate-name-to-foreign spec *package* varp))
(defun foreign-options (opts varp)
(if varp
(funcall 'parse-defcvar-options opts)
(parse-function-options opts)))
(defun lisp-name-p (name)
(and name (symbolp name) (not (keywordp name))))
(defun %parse-name-and-options (spec varp)
(cond
((stringp spec)
(values (lisp-name spec varp) spec nil))
((symbolp spec)
(assert (not (null spec)))
(values spec (foreign-name spec varp) nil))
((and (consp spec) (stringp (first spec)))
(destructuring-bind (foreign-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values (lisp-name foreign-name varp) foreign-name options))
(t
(assert (lisp-name-p (first options)))
(values (first options) foreign-name (rest options))))))
((and (consp spec) (lisp-name-p (first spec)))
(destructuring-bind (lisp-name &rest options)
spec
(cond
((or (null options)
(keywordp (first options)))
(values lisp-name (foreign-name spec varp) options))
(t
(assert (stringp (first options)))
(values lisp-name (first options) (rest options))))))
(t
(error "Not a valid foreign function specifier: ~A" spec))))
DEFCFUN 's first argument has can have the following syntax :
1 . string
2 . symbol
3 . \ ( string [ symbol ] options * )
4 . \ ( symbol [ string ] options * )
(defun parse-name-and-options (spec &optional varp)
(multiple-value-bind (lisp-name foreign-name options)
(%parse-name-and-options spec varp)
(values lisp-name foreign-name (foreign-options options varp))))
% DEFCFUN .
(defmacro defcfun (name-and-options return-type &body args)
"Defines a Lisp function that calls a foreign function."
(let ((docstring (when (stringp (car args)) (pop args))))
(multiple-value-bind (lisp-name foreign-name options)
(parse-name-and-options name-and-options)
(if (eq (lastcar args) '&rest)
(%defcfun-varargs lisp-name foreign-name return-type
(butlast args) options docstring)
(%defcfun lisp-name foreign-name return-type args options
docstring)))))
(defun inverse-translate-objects (args types declarations rettype call)
`(let (,@(loop for arg in args and type in types
collect (list arg (expand-from-foreign
arg (parse-type type)))))
,@declarations
,(expand-to-foreign call (parse-type rettype))))
(defun parse-defcallback-options (options)
(destructuring-bind (&key (cconv :cdecl cconv-p)
(calling-convention cconv calling-convention-p)
(convention calling-convention))
options
(when cconv-p
(warn-obsolete-argument :cconv :convention))
(when calling-convention-p
(warn-obsolete-argument :calling-convention :convention))
(list :convention convention)))
(defmacro defcallback (name-and-options return-type args &body body)
(multiple-value-bind (body declarations)
(parse-body body :documentation t)
(let ((arg-names (mapcar #'car args))
(arg-types (mapcar #'cadr args))
(name (car (ensure-list name-and-options)))
(options (cdr (ensure-list name-and-options))))
`(progn
(%defcallback ,name ,(canonicalize-foreign-type return-type)
,arg-names ,(mapcar #'canonicalize-foreign-type arg-types)
,(inverse-translate-objects
arg-names arg-types declarations return-type
`(block ,name ,@body))
,@(parse-defcallback-options options))
',name))))
(declaim (inline get-callback))
(defun get-callback (symbol)
(%callback symbol))
(defmacro callback (name)
`(%callback ',name))
|
a6eb10f6a3131234b71cfe14f2a7ac25816b87b37c9c2e1328f69f2661df3966 | galdor/tungsten | package.lisp | (defpackage :log
(:use :cl)
(:export
#:level
#:domain-part
#:domain
#:message
#:message-time
#:message-domain
#:message-level
#:message-text
#:message-data
#:message-writer
#:sink
#:write-message
#:default-sink
#:make-terminal-sink
#:*logger*
#:logger
#:logger-domain
#:logger-data
#:logger-message-writer
#:logger-stream
#:make-logger
#:with-logger
#:log-message
#:log-debug
#:log-debug-data
#:log-info
#:log-info-data
#:log-error
#:log-error-data
#:log-condition))
| null | https://raw.githubusercontent.com/galdor/tungsten/61bc5e1c91c8027cce9f079f1eec9368316e181c/tungsten-log/src/package.lisp | lisp | (defpackage :log
(:use :cl)
(:export
#:level
#:domain-part
#:domain
#:message
#:message-time
#:message-domain
#:message-level
#:message-text
#:message-data
#:message-writer
#:sink
#:write-message
#:default-sink
#:make-terminal-sink
#:*logger*
#:logger
#:logger-domain
#:logger-data
#:logger-message-writer
#:logger-stream
#:make-logger
#:with-logger
#:log-message
#:log-debug
#:log-debug-data
#:log-info
#:log-info-data
#:log-error
#:log-error-data
#:log-condition))
| |
7f83fdd5d849e612c39d8769e6f79f84d7d6e2452a6d76165917ed9aeb77d3c1 | takano-akio/filelock | interrupt.hs | import Control.Concurrent
import Control.Exception
import Control.Monad
import System.FileLock
import System.Exit
import System.Timeout
main :: IO ()
main = withFileLock lockFilePath Exclusive $ \_ -> do
mvar <- newMVar Nothing
_ <- forkIO $ do
-- The attempt to lock the file again should block, but it should be
-- interrupted by the timeout, returning Nothing.
--
-- Also masking shouldn't change interruptibility.
r <- timeout 1000000 $ mask $ \_ -> lockFile lockFilePath Exclusive
_ <- swapMVar mvar (Just r)
return ()
threadDelay 2000000
res <- readMVar mvar
when (res /= Just Nothing) $
die $ "unexpected result: " ++ show (fmap (const ()) <$> res)
where
lockFilePath = "interrupt_test.lock"
| null | https://raw.githubusercontent.com/takano-akio/filelock/bf09ca2911a0d98720ef0624e9d15a69d40e66e6/tests/interrupt.hs | haskell | The attempt to lock the file again should block, but it should be
interrupted by the timeout, returning Nothing.
Also masking shouldn't change interruptibility. | import Control.Concurrent
import Control.Exception
import Control.Monad
import System.FileLock
import System.Exit
import System.Timeout
main :: IO ()
main = withFileLock lockFilePath Exclusive $ \_ -> do
mvar <- newMVar Nothing
_ <- forkIO $ do
r <- timeout 1000000 $ mask $ \_ -> lockFile lockFilePath Exclusive
_ <- swapMVar mvar (Just r)
return ()
threadDelay 2000000
res <- readMVar mvar
when (res /= Just Nothing) $
die $ "unexpected result: " ++ show (fmap (const ()) <$> res)
where
lockFilePath = "interrupt_test.lock"
|
af4bb8101d4a528c9491936654ff5b1f87fa975d3dfe2b6458704df850038032 | dgiot/dgiot | dgiot_parse_slave_channel.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT 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(dgiot_parse_slave_channel).
-define(TYPE1, <<"PARSESLAVE">>).
-author("kenneth").
-include("dgiot_parse.hrl").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-behavior(dgiot_channelx).
-export([start/2, init/3, handle_init/1, handle_event/3, handle_message/2, stop/3, handle_save/1]).
-record(state, {channel, cfg}).
注册通道类型
-channel(?TYPE1).
-channel_type(#{
cType => ?TYPE1,
type => ?BACKEND_CHL,
priority => 1,
title => #{
zh => <<"Parse 数据主备同步通道"/utf8>>
},
description => #{
zh => <<"Parse 数据主备同步通道"/utf8>>
}
}).
%% 注册通道参数
-params(#{
<<"issync">> => #{
order => 4,
type => boolean,
required => true,
default => true,
title => #{
zh => <<"是否同步"/utf8>>
},
description => #{
zh => <<"是否同步"/utf8>>
}
},
<<"interval">> => #{
order => 1,
type => integer,
required => false,
default => 180,
title => #{
zh => <<"同步间隔/秒"/utf8>>
},
description => #{
zh => <<"从库同步主库间隔/秒"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/parserIcon.jpg">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(Channel, Cfg) ->
dgiot_channelx:add(?TYPE1, Channel, ?MODULE, Cfg#{
<<"Size">> => 100
}).
通道初始化
init(?TYPE1, Channel, Cfg) ->
State = #state{channel = Channel, cfg = Cfg},
dgiot_parse : sync_parse ( ) ,
%% dgiot_parse:sync_user(),
%% dgiot_parse:sync_role(),
{ok, State}.
初始化池子
handle_init(State) ->
{ok, State}.
handle_message(export, #state{cfg = Cfg} = State) ->
{reply, {ok, Cfg}, State};
handle_message(config, #state{cfg = Cfg} = State) ->
{reply, {ok, Cfg}, State};
handle_message(_Message, State) ->
{ok, State}.
handle_event(_EventId, _Event, _State) ->
ok.
handle_save(Channel) ->
dgiot_parse_cache:do_save(Channel).
stop(_ChannelType, _ChannelId, _State) ->
ok.
| null | https://raw.githubusercontent.com/dgiot/dgiot/cae748d4065770bbed34b6f9a3d2b3dc4a2b0391/apps/dgiot_parse/src/sever/dgiot_parse_slave_channel.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.
--------------------------------------------------------------------
注册通道参数
dgiot_parse:sync_user(),
dgiot_parse:sync_role(), | Copyright ( c ) 2020 - 2021 DGIOT 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(dgiot_parse_slave_channel).
-define(TYPE1, <<"PARSESLAVE">>).
-author("kenneth").
-include("dgiot_parse.hrl").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-behavior(dgiot_channelx).
-export([start/2, init/3, handle_init/1, handle_event/3, handle_message/2, stop/3, handle_save/1]).
-record(state, {channel, cfg}).
注册通道类型
-channel(?TYPE1).
-channel_type(#{
cType => ?TYPE1,
type => ?BACKEND_CHL,
priority => 1,
title => #{
zh => <<"Parse 数据主备同步通道"/utf8>>
},
description => #{
zh => <<"Parse 数据主备同步通道"/utf8>>
}
}).
-params(#{
<<"issync">> => #{
order => 4,
type => boolean,
required => true,
default => true,
title => #{
zh => <<"是否同步"/utf8>>
},
description => #{
zh => <<"是否同步"/utf8>>
}
},
<<"interval">> => #{
order => 1,
type => integer,
required => false,
default => 180,
title => #{
zh => <<"同步间隔/秒"/utf8>>
},
description => #{
zh => <<"从库同步主库间隔/秒"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/parserIcon.jpg">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(Channel, Cfg) ->
dgiot_channelx:add(?TYPE1, Channel, ?MODULE, Cfg#{
<<"Size">> => 100
}).
通道初始化
init(?TYPE1, Channel, Cfg) ->
State = #state{channel = Channel, cfg = Cfg},
dgiot_parse : sync_parse ( ) ,
{ok, State}.
初始化池子
handle_init(State) ->
{ok, State}.
handle_message(export, #state{cfg = Cfg} = State) ->
{reply, {ok, Cfg}, State};
handle_message(config, #state{cfg = Cfg} = State) ->
{reply, {ok, Cfg}, State};
handle_message(_Message, State) ->
{ok, State}.
handle_event(_EventId, _Event, _State) ->
ok.
handle_save(Channel) ->
dgiot_parse_cache:do_save(Channel).
stop(_ChannelType, _ChannelId, _State) ->
ok.
|
4aabdc142d1c5580fa1501f72d11b77ed6fdd37a57c3ff13cc8309d6fe0f19d5 | whamtet/dogfort | cookies.cljs | (ns dogfort.middleware.cookies
"Middleware for parsing and generating cookies."
#_(:import [org.joda.time DateTime Interval])
(:require [dogfort.util.codec :as codec]
[clojure.string :as str]
[redlobster.promise :as p])
(:use-macros
[redlobster.macros :only [promise let-realised]]
))
(def ^{:doc "HTTP token: 1*<any CHAR except CTLs or tspecials>. See RFC2068"
:added "1.3"}
re-token
#"[!#$%&'*\-+.0-9A-Z\^_`a-z\|~]+")
(def ^{:private true, :doc "RFC6265 cookie-octet"}
re-cookie-octet
#"[!#$%&'()*+\-./0-9:<=>?@A-Z\[\]\^_`a-z\{\|\}~]")
(def ^{:private true, :doc "RFC6265 cookie-value"}
re-cookie-value
(re-pattern (str "\"" (.-source re-cookie-octet) "*\"|" (.-source re-cookie-octet) "*")))
(def ^{:private true, :doc "RFC6265 set-cookie-string"}
re-cookie
(re-pattern (str "\\s*(" (.-source re-token) ")=(" (.-source re-cookie-value) ")\\s*[;,]?")))
(def ^{:private true
:doc "Attributes defined by RFC6265 that apply to the Set-Cookie header."}
set-cookie-attrs
{:domain "Domain", :max-age "Max-Age", :path "Path"
:secure "Secure", :expires "Expires", :http-only "HttpOnly"})
#_(def ^:private rfc822-formatter
(with-locale (formatters :rfc822) java.util.Locale/US))
(defn- parse-cookie-header
"Turn a HTTP Cookie header into a list of name/value pairs."
[header]
(for [[_ name value] (re-seq re-cookie header)]
[name value]))
(defn- strip-quotes
"Strip quotes from a cookie value."
[value]
(str/replace value #"^\"|\"$" ""))
(defn- decode-values [cookies decoder]
(for [[name value] cookies]
(if-let [value (decoder (strip-quotes value))]
[name {:value value}])))
(defn- parse-cookies
"Parse the cookies from a request map."
[request encoder]
(if-let [cookie (get-in request [:headers "cookie"])]
(->> cookie
parse-cookie-header
((fn [c] (decode-values c encoder)))
(remove nil?)
(into {}))
{}))
(defn- write-value
"Write the main cookie value."
[key value encoder]
(encoder {key value}))
(defn- valid-attr?
"Is the attribute valid?"
[[key value]]
(and (contains? set-cookie-attrs key)
(= -1 (.indexOf (str value) ";"))
(case key
:max-age (or #_(instance? Interval value) (integer? value))
:expires (or (instance? js/Date value) (string? value))
true)))
(defn- write-attr-map
"Write a map of cookie attributes to a string."
[attrs]
{:pre [(every? valid-attr? attrs)]}
(for [[key value] attrs]
(let [attr-name (name (set-cookie-attrs key))]
(cond
; (instance? Interval value) (str ";" attr-name "=" (in-seconds value))
( instance ? js / Date value ) ( str " ; " attr - name " = " ( value ) )
(true? value) (str ";" attr-name)
(false? value) ""
:else (str ";" attr-name "=" value)))))
(defn- write-cookies
"Turn a map of cookies into a seq of strings for a Set-Cookie header."
[cookies encoder]
(for [[key value] cookies]
(if (map? value)
(apply str (write-value key (:value value) encoder)
(write-attr-map (dissoc value :value)))
(write-value key value encoder))))
(defn- set-cookies
"Add a Set-Cookie header to a response if there is a :cookies key."
[response encoder]
(if-let [cookies (:cookies response)]
(update-in response
[:headers "Set-Cookie"]
concat
(doall (write-cookies cookies encoder)))
response))
(defn cookies-request
"Parses cookies in the request map. See: wrap-cookies."
{:arglists '([request] [request options])
:added "1.2"}
[request & [{:keys [decoder] :or {decoder codec/form-decode-str}}]]
(if (request :cookies)
request
(assoc request :cookies (parse-cookies request decoder))))
(defn cookies-response
"For responses with :cookies, adds Set-Cookie header and returns response
without :cookies. See: wrap-cookies."
{:arglists '([response] [response options])
:added "1.2"}
[response & [{:keys [encoder] :or {encoder codec/form-encode}}]]
(let-realised [response response]
(-> @response (set-cookies encoder) (dissoc :cookies))))
#_(defn wrap-cookies2 [handler]
(fn [request]
(let-realised
[request (nrepl/my-eval `(cookies/cookies-request ~(dissoc request :body)))]
(let-realised
[response (handler @request)]
(let-realised
[response (nrepl/my-eval `(cookies/cookies-response ~(deref response)))]
@response)))))
(defn wrap-cookies
"Parses the cookies in the request map, then assocs the resulting map
to the :cookies key on the request.
Accepts the following options:
:decoder - a function to decode the cookie value. Expects a function that
takes a string and returns a string. Defaults to URL-decoding.
:encoder - a function to encode the cookie name and value. Expects a
function that takes a name/value map and returns a string.
Defaults to URL-encoding.
Each cookie is represented as a map, with its value being held in the
:value key. A cookie may optionally contain a :path, :domain or :port
attribute.
To set cookies, add a map to the :cookies key on the response. The values
of the cookie map can either be strings, or maps containing the following
keys:
:value - the new value of the cookie
:path - the subpath the cookie is valid for
:domain - the domain the cookie is valid for
:max-age - the maximum age in seconds of the cookie
:expires - a date string at which the cookie will expire
:secure - set to true if the cookie requires HTTPS, prevent HTTP access
:http-only - set to true if the cookie is valid for HTTP and HTTPS only
(ie. prevent JavaScript access)"
{:arglists '([handler] [handler options])}
[handler & [{:keys [decoder encoder]
:or {decoder codec/form-decode-str
encoder codec/form-encode}}]]
(fn [request]
(-> request
(cookies-request {:decoder decoder})
handler
(cookies-response {:encoder encoder}))))
| null | https://raw.githubusercontent.com/whamtet/dogfort/75c2908355cc18bf350a5b761d2906e013ee9f94/src/dogfort/middleware/cookies.cljs | clojure | (instance? Interval value) (str ";" attr-name "=" (in-seconds value)) | (ns dogfort.middleware.cookies
"Middleware for parsing and generating cookies."
#_(:import [org.joda.time DateTime Interval])
(:require [dogfort.util.codec :as codec]
[clojure.string :as str]
[redlobster.promise :as p])
(:use-macros
[redlobster.macros :only [promise let-realised]]
))
(def ^{:doc "HTTP token: 1*<any CHAR except CTLs or tspecials>. See RFC2068"
:added "1.3"}
re-token
#"[!#$%&'*\-+.0-9A-Z\^_`a-z\|~]+")
(def ^{:private true, :doc "RFC6265 cookie-octet"}
re-cookie-octet
#"[!#$%&'()*+\-./0-9:<=>?@A-Z\[\]\^_`a-z\{\|\}~]")
(def ^{:private true, :doc "RFC6265 cookie-value"}
re-cookie-value
(re-pattern (str "\"" (.-source re-cookie-octet) "*\"|" (.-source re-cookie-octet) "*")))
(def ^{:private true, :doc "RFC6265 set-cookie-string"}
re-cookie
(re-pattern (str "\\s*(" (.-source re-token) ")=(" (.-source re-cookie-value) ")\\s*[;,]?")))
(def ^{:private true
:doc "Attributes defined by RFC6265 that apply to the Set-Cookie header."}
set-cookie-attrs
{:domain "Domain", :max-age "Max-Age", :path "Path"
:secure "Secure", :expires "Expires", :http-only "HttpOnly"})
#_(def ^:private rfc822-formatter
(with-locale (formatters :rfc822) java.util.Locale/US))
(defn- parse-cookie-header
"Turn a HTTP Cookie header into a list of name/value pairs."
[header]
(for [[_ name value] (re-seq re-cookie header)]
[name value]))
(defn- strip-quotes
"Strip quotes from a cookie value."
[value]
(str/replace value #"^\"|\"$" ""))
(defn- decode-values [cookies decoder]
(for [[name value] cookies]
(if-let [value (decoder (strip-quotes value))]
[name {:value value}])))
(defn- parse-cookies
"Parse the cookies from a request map."
[request encoder]
(if-let [cookie (get-in request [:headers "cookie"])]
(->> cookie
parse-cookie-header
((fn [c] (decode-values c encoder)))
(remove nil?)
(into {}))
{}))
(defn- write-value
"Write the main cookie value."
[key value encoder]
(encoder {key value}))
(defn- valid-attr?
"Is the attribute valid?"
[[key value]]
(and (contains? set-cookie-attrs key)
(= -1 (.indexOf (str value) ";"))
(case key
:max-age (or #_(instance? Interval value) (integer? value))
:expires (or (instance? js/Date value) (string? value))
true)))
(defn- write-attr-map
"Write a map of cookie attributes to a string."
[attrs]
{:pre [(every? valid-attr? attrs)]}
(for [[key value] attrs]
(let [attr-name (name (set-cookie-attrs key))]
(cond
( instance ? js / Date value ) ( str " ; " attr - name " = " ( value ) )
(true? value) (str ";" attr-name)
(false? value) ""
:else (str ";" attr-name "=" value)))))
(defn- write-cookies
"Turn a map of cookies into a seq of strings for a Set-Cookie header."
[cookies encoder]
(for [[key value] cookies]
(if (map? value)
(apply str (write-value key (:value value) encoder)
(write-attr-map (dissoc value :value)))
(write-value key value encoder))))
(defn- set-cookies
"Add a Set-Cookie header to a response if there is a :cookies key."
[response encoder]
(if-let [cookies (:cookies response)]
(update-in response
[:headers "Set-Cookie"]
concat
(doall (write-cookies cookies encoder)))
response))
(defn cookies-request
"Parses cookies in the request map. See: wrap-cookies."
{:arglists '([request] [request options])
:added "1.2"}
[request & [{:keys [decoder] :or {decoder codec/form-decode-str}}]]
(if (request :cookies)
request
(assoc request :cookies (parse-cookies request decoder))))
(defn cookies-response
"For responses with :cookies, adds Set-Cookie header and returns response
without :cookies. See: wrap-cookies."
{:arglists '([response] [response options])
:added "1.2"}
[response & [{:keys [encoder] :or {encoder codec/form-encode}}]]
(let-realised [response response]
(-> @response (set-cookies encoder) (dissoc :cookies))))
#_(defn wrap-cookies2 [handler]
(fn [request]
(let-realised
[request (nrepl/my-eval `(cookies/cookies-request ~(dissoc request :body)))]
(let-realised
[response (handler @request)]
(let-realised
[response (nrepl/my-eval `(cookies/cookies-response ~(deref response)))]
@response)))))
(defn wrap-cookies
"Parses the cookies in the request map, then assocs the resulting map
to the :cookies key on the request.
Accepts the following options:
:decoder - a function to decode the cookie value. Expects a function that
takes a string and returns a string. Defaults to URL-decoding.
:encoder - a function to encode the cookie name and value. Expects a
function that takes a name/value map and returns a string.
Defaults to URL-encoding.
Each cookie is represented as a map, with its value being held in the
:value key. A cookie may optionally contain a :path, :domain or :port
attribute.
To set cookies, add a map to the :cookies key on the response. The values
of the cookie map can either be strings, or maps containing the following
keys:
:value - the new value of the cookie
:path - the subpath the cookie is valid for
:domain - the domain the cookie is valid for
:max-age - the maximum age in seconds of the cookie
:expires - a date string at which the cookie will expire
:secure - set to true if the cookie requires HTTPS, prevent HTTP access
:http-only - set to true if the cookie is valid for HTTP and HTTPS only
(ie. prevent JavaScript access)"
{:arglists '([handler] [handler options])}
[handler & [{:keys [decoder encoder]
:or {decoder codec/form-decode-str
encoder codec/form-encode}}]]
(fn [request]
(-> request
(cookies-request {:decoder decoder})
handler
(cookies-response {:encoder encoder}))))
|
abc67a263c851efc2d4aa7292362ac4481ecdb92168d57a912ef18c0492667a9 | fujita-y/ypsilon | core.scm | (library (core)
(export
&assertion
&condition
&error
&i/o
&i/o-decoding
&i/o-encoding
&i/o-file-already-exists
&i/o-file-does-not-exist
&i/o-file-is-read-only
&i/o-file-protection
&i/o-filename
&i/o-invalid-position
&i/o-port
&i/o-read
&i/o-write
&implementation-restriction
&irritants
&lexical
&message
&no-infinities
&no-nans
&non-continuable
&serious
&syntax
&undefined
&violation
&warning
&who
*
+
-
...
/
<
<=
=
=>
>
>=
_
abs
acos
acquire-lockfile
add-library-path
add-load-path
and
angle
append
apply
architecture-feature
asin
assert
assertion-violation
assertion-violation?
assoc
assp
assq
assv
atan
auto-compile-cache
auto-compile-verbose
backtrace
backtrace-line-length
begin
binary-port?
bitwise-and
bitwise-arithmetic-shift
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
bitwise-bit-count
bitwise-bit-field
bitwise-bit-set?
bitwise-copy-bit
bitwise-copy-bit-field
bitwise-first-bit-set
bitwise-if
bitwise-ior
bitwise-length
bitwise-not
bitwise-reverse-bit-field
bitwise-rotate-bit-field
bitwise-xor
boolean=?
boolean?
bound-identifier=?
break
buffer-mode
buffer-mode?
bytevector->pinned-c-void*
bytevector->sint-list
bytevector->string
bytevector->u8-list
bytevector->uint-list
bytevector-c-double-ref
bytevector-c-double-set!
bytevector-c-float-ref
bytevector-c-float-set!
bytevector-c-int-ref
bytevector-c-int-set!
bytevector-c-int16-ref
bytevector-c-int16-set!
bytevector-c-int32-ref
bytevector-c-int32-set!
bytevector-c-int64-ref
bytevector-c-int64-set!
bytevector-c-int8-ref
bytevector-c-int8-set!
bytevector-c-long-long-ref
bytevector-c-long-long-set!
bytevector-c-long-ref
bytevector-c-long-set!
bytevector-c-short-ref
bytevector-c-short-set!
bytevector-c-strlen
bytevector-c-uint16-ref
bytevector-c-uint32-ref
bytevector-c-uint64-ref
bytevector-c-uint8-ref
bytevector-c-unsigned-int-ref
bytevector-c-unsigned-long-long-ref
bytevector-c-unsigned-long-ref
bytevector-c-unsigned-short-ref
bytevector-c-void*-ref
bytevector-c-void*-set!
bytevector-copy
bytevector-copy!
bytevector-fill!
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!
bytevector-ieee-double-ref
bytevector-ieee-double-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!
bytevector-ieee-single-ref
bytevector-ieee-single-set!
bytevector-length
bytevector-mapping?
bytevector-s16-native-ref
bytevector-s16-native-set!
bytevector-s16-ref
bytevector-s16-set!
bytevector-s32-native-ref
bytevector-s32-native-set!
bytevector-s32-ref
bytevector-s32-set!
bytevector-s64-native-ref
bytevector-s64-native-set!
bytevector-s64-ref
bytevector-s64-set!
bytevector-s8-ref
bytevector-s8-set!
bytevector-sint-ref
bytevector-sint-set!
bytevector-u16-native-ref
bytevector-u16-native-set!
bytevector-u16-ref
bytevector-u16-set!
bytevector-u32-native-ref
bytevector-u32-native-set!
bytevector-u32-ref
bytevector-u32-set!
bytevector-u64-native-ref
bytevector-u64-native-set!
bytevector-u64-ref
bytevector-u64-set!
bytevector-u8-ref
bytevector-u8-set!
bytevector-uint-ref
bytevector-uint-set!
bytevector=?
bytevector?
c-main-argc
c-main-argv
caaaar
caaadr
caaar
caadar
caaddr
caadr
caar
cadaar
cadadr
cadar
caddar
cadddr
caddr
cadr
call-with-bytevector-output-port
call-with-current-continuation
call-with-input-file
call-with-output-file
call-with-port
call-with-string-output-port
call-with-values
call/cc
car
case
case-lambda
cdaaar
cdaadr
cdaar
cdadar
cdaddr
cdadr
cdar
cddaar
cddadr
cddar
cdddar
cddddr
cdddr
cddr
cdr
ceiling
change-file-mode
char->integer
char-alphabetic?
char-ci<=?
char-ci<?
char-ci=?
char-ci>=?
char-ci>?
char-downcase
char-foldcase
char-general-category
char-lower-case?
char-numeric?
char-title-case?
char-titlecase
char-upcase
char-upper-case?
char-whitespace?
char<=?
char<?
char=?
char>=?
char>?
char?
circular-list?
close-input-port
close-output-port
close-port
closure-code
closure-codegen
cmwc-random-real
cmwc-random-u32
codegen-cdecl-callback
codegen-cdecl-callout
codegen-queue-count
codegen-queue-push!
collect
collect-notify
collect-stack-notify
collect-trip-bytes
command-line
command-line-shift
compile
compile-coreform
complex?
cond
condition
condition-accessor
condition-irritants
condition-message
condition-predicate
condition-who
condition?
cons
cons*
continuation-to-exit
copy-environment-macros!
copy-environment-variables!
core-eval
core-hashtable->alist
core-hashtable-clear!
core-hashtable-contains?
core-hashtable-copy
core-hashtable-delete!
core-hashtable-equivalence-function
core-hashtable-hash-function
core-hashtable-mutable?
core-hashtable-ref
core-hashtable-set!
core-hashtable-size
core-hashtable?
core-read
coreform-optimize
cos
count-pair
create-directory
create-hard-link
create-symbolic-link
current-after-expansion-hook
current-directory
current-dynamic-environment
current-environment
current-error-port
current-exception-printer
current-input-port
current-library-infix
current-library-suffix
current-macro-environment
current-output-port
current-primitive-prefix
current-rename-delimiter
current-source-comments
current-variable-environment
cyclic-object?
datum
datum->syntax
decode-flonum
decode-microsecond
define
define-condition-type
define-enumeration
define-library
define-macro
define-record-type
define-struct
define-syntax
delay
delete-file
denominator
destructuring-bind
destructuring-match
directory-list
display
display-backtrace
display-codegen-statistics
display-heap-statistics
display-object-statistics
div
div-and-mod
div0
div0-and-mod0
do
drop
drop-last-cdr
drop-last-n-pair
drop-last-pair
dynamic-wind
else
encode-microsecond
endianness
enum-set->list
enum-set-complement
enum-set-constructor
enum-set-difference
enum-set-indexer
enum-set-intersection
enum-set-member?
enum-set-projection
enum-set-subset?
enum-set-union
enum-set-universe
enum-set=?
enum-set?
environment
eof-object
eof-object?
eol-style
eq?
equal-hash
equal?
eqv?
errno/string
error
error-handling-mode
error?
eval
even?
exact
exact->inexact
exact-integer-sqrt
exact?
exists
exit
exp
expansion-backtrace
expt
extract-accumulated-bytevector
extract-accumulated-string
feature-identifiers
fields
file-directory?
file-executable?
file-exists?
file-options
file-readable?
file-regular?
file-size-in-bytes
file-stat-atime
file-stat-ctime
file-stat-mtime
file-symbolic-link?
file-writable?
filter
find
finite?
fixnum->flonum
fixnum-width
fixnum?
fl*
fl+
fl-
fl/
fl<=?
fl<?
fl=?
fl>=?
fl>?
flabs
flacos
flasin
flatan
flceiling
flcos
fldenominator
fldiv
fldiv-and-mod
fldiv0
fldiv0-and-mod0
fleven?
flexp
flexpt
flfinite?
flfloor
flinfinite?
flinteger?
fllog
flmax
flmin
flmod
flmod0
flnan?
flnegative?
flnumerator
flodd?
flonum?
floor
flpositive?
flround
flsin
flsqrt
fltan
fltruncate
flush-output-port
flzero?
fold-left
fold-right
for-all
for-each
force
format
free-identifier=?
fulfill-feature-requirements?
fx*
fx*/carry
fx+
fx+/carry
fx-
fx-/carry
fx<=?
fx<?
fx=?
fx>=?
fx>?
fxand
fxarithmetic-shift
fxarithmetic-shift-left
fxarithmetic-shift-right
fxbit-count
fxbit-field
fxbit-set?
fxcopy-bit
fxcopy-bit-field
fxdiv
fxdiv-and-mod
fxdiv0
fxdiv0-and-mod0
fxeven?
fxfirst-bit-set
fxif
fxior
fxlength
fxmax
fxmin
fxmod
fxmod0
fxnegative?
fxnot
fxodd?
fxpositive?
fxreverse-bit-field
fxrotate-bit-field
fxxor
fxzero?
gcd
generate-temporaries
generate-temporary-symbol
gensym
get-accumulated-bytevector
get-accumulated-string
get-bytevector-all
get-bytevector-n
get-bytevector-n!
get-bytevector-some
get-char
get-datum
get-line
get-string-all
get-string-n
get-string-n!
get-u8
getenv
gethostname
greatest-fixnum
guard
hashtable->alist
hashtable-clear!
hashtable-contains?
hashtable-copy
hashtable-delete!
hashtable-entries
hashtable-equivalence-function
hashtable-hash-function
hashtable-keys
hashtable-mutable?
hashtable-ref
hashtable-set!
hashtable-size
hashtable-update!
hashtable?
home-directory
i/o-decoding-error?
i/o-encoding-error-char
i/o-encoding-error?
i/o-error-filename
i/o-error-port
i/o-error-position
i/o-error?
i/o-file-already-exists-error?
i/o-file-does-not-exist-error?
i/o-file-is-read-only-error?
i/o-file-protection-error?
i/o-filename-error?
i/o-invalid-position-error?
i/o-port-error?
i/o-read-error?
i/o-write-error?
identifier-syntax
identifier?
if
imag-part
immutable
implementation-restriction-violation?
include
include-ci
inexact
inexact->exact
inexact?
infinite?
input-port?
integer->char
integer-valued?
integer?
interaction-environment
iota
irritants-condition?
lambda
last-cdr
last-n-pair
last-pair
latin-1-codec
lcm
least-fixnum
length
let
let*
let*-values
let-optionals
let-syntax
let-values
letrec
letrec*
letrec-syntax
lexical-violation?
library
library-extensions
list
list->string
list->vector
list-copy
list-head
list-of-unique-symbols?
list-ref
list-sort
list-tail
list-transpose
list-transpose*
list-transpose+
list?
load
load-shared-object
log
lookahead-char
lookahead-u8
lookup-process-environment
lookup-shared-object
macro-expand
magnitude
make-assertion-violation
make-bytevector
make-bytevector-mapping
make-cmwc-random-state
make-core-hashtable
make-custom-binary-input-port
make-custom-binary-input/output-port
make-custom-binary-output-port
make-custom-textual-input-port
make-custom-textual-input/output-port
make-custom-textual-output-port
make-enumeration
make-environment
make-eq-hashtable
make-eqv-hashtable
make-error
make-hashtable
make-i/o-decoding-error
make-i/o-encoding-error
make-i/o-error
make-i/o-file-already-exists-error
make-i/o-file-does-not-exist-error
make-i/o-file-is-read-only-error
make-i/o-file-protection-error
make-i/o-filename-error
make-i/o-invalid-position-error
make-i/o-port-error
make-i/o-read-error
make-i/o-write-error
make-implementation-restriction-violation
make-irritants-condition
make-lexical-violation
make-list
make-message-condition
make-no-infinities-violation
make-no-nans-violation
make-non-continuable-violation
make-parameter
make-polar
make-record-constructor-descriptor
make-record-type
make-record-type-descriptor
make-rectangular
make-serious-condition
make-socket
make-string
make-string-hashtable
make-string-input-port
make-string-output-port
make-syntax-violation
make-temporary-file-port
make-transcoded-port
make-transcoder
make-tuple
make-undefined-violation
make-uuid
make-variable-transformer
make-vector
make-violation
make-warning
make-weak-core-hashtable
make-weak-hashtable
make-weak-mapping
make-who-condition
map
mat4x4-add
mat4x4-dup
mat4x4-frustum
mat4x4-identity
mat4x4-invert
mat4x4-look-at
mat4x4-mul
mat4x4-ortho
mat4x4-orthonormalize
mat4x4-perspective
mat4x4-rotate
mat4x4-scale
mat4x4-sub
mat4x4-translate
mat4x4-transpose
max
member
memp
memq
memv
message-condition?
microsecond
microsecond->string
microsecond->utc
min
mod
mod0
modulo
mutable
nan?
native-endianness
native-eol-style
native-transcoder
native-transcoder-descriptor
negative?
newline
no-infinities-violation?
no-nans-violation?
non-continuable-violation?
nonblock-byte-ready?
nongenerative
not
null?
number->string
number?
numerator
odd?
opaque
open-builtin-data-input-port
open-bytevector-input-port
open-bytevector-output-port
open-file-input-port
open-file-input/output-port
open-file-output-port
open-input-file
open-output-file
open-port
open-string-input-port
open-string-output-port
open-temporary-file-port
or
output-port-buffer-mode
output-port?
pair?
parameterize
parent
parent-rtd
partition
peek-char
port-closed?
port-device-subtype
port-eof?
port-has-port-position?
port-has-set-port-position!?
port-position
port-transcoder
port-transcoder-descriptor
port?
positive?
pretty-print
pretty-print-initial-indent
pretty-print-line-length
pretty-print-maximum-lines
pretty-print-unwrap-syntax
procedure?
process-environment->alist
process-spawn
process-wait
protocol
put-byte
put-bytevector
put-char
put-datum
put-fasl
put-string
put-u8
quasiquote
quasisyntax
quote
quotient
raise
raise-continuable
rational-valued?
rational?
rationalize
read
read-char
read-with-shared-structure
real->flonum
real-part
real-valued?
real?
record-accessor
record-constructor
record-constructor-descriptor
record-field-mutable?
record-mutator
record-predicate
record-print-nesting-limit
record-rtd
record-type-descriptor
record-type-descriptor?
record-type-field-names
record-type-generative?
record-type-name
record-type-opaque?
record-type-parent
record-type-rcd
record-type-rtd
record-type-sealed?
record-type-uid
record-type?
record?
release-lockfile
remainder
remove
remove-duplicate-symbols
remp
remq
remv
rename-file
restricted-print-line-length
reverse
round
scheme-error
scheme-library-exports
scheme-library-paths
scheme-load-paths
scheme-load-verbose
sealed
serious-condition?
set!
set-car!
set-cdr!
set-current-error-port!
set-current-input-port!
set-current-output-port!
set-port-position!
set-top-level-value!
shutdown-output-port
simple-conditions
sin
sint-list->bytevector
socket->port
socket-accept
socket-close
socket-port
socket-recv
socket-send
socket-shutdown
socket?
sqrt
standard-error-port
standard-input-port
standard-output-port
string
string->bytevector
string->list
string->number
string->symbol
string->uninterned-symbol
string->utf16
string->utf32
string->utf8
string->utf8/nul
string-append
string-ci-hash
string-ci<=?
string-ci<?
string-ci=?
string-ci>=?
string-ci>?
string-contains
string-copy
string-downcase
string-fill!
string-foldcase
string-for-each
string-hash
string-length
string-normalize-nfc
string-normalize-nfd
string-normalize-nfkc
string-normalize-nfkd
string-ref
string-set!
string-titlecase
string-upcase
string<=?
string<?
string=?
string>=?
string>?
string?
subr?
substring
symbol->string
symbol-contains
symbol-hash
symbol=?
symbol?
syntax
syntax->datum
syntax-case
syntax-rules
syntax-violation
syntax-violation-form
syntax-violation-subform
syntax-violation?
system
system-environment
system-extension-path
system-share-path
take
tan
textual-port?
time-usage
top-level-bound?
top-level-value
transcoded-port
transcoder-codec
transcoder-eol-style
transcoder-error-handling-mode
truncate
tuple
tuple->list
tuple-index
tuple-length
tuple-ref
tuple-set!
tuple?
u8-list->bytevector
uint-list->bytevector
undefined-violation?
uninterned-symbol-prefix
uninterned-symbol-suffix
uninterned-symbol?
unless
unquote
unquote-splicing
unspecified
unspecified?
unsyntax
unsyntax-splicing
usleep
utf-16-codec
utf-8-codec
utf16->string
utf32->string
utf8->string
values
vector
vector->list
vector-copy
vector-fill!
vector-for-each
vector-length
vector-map
vector-ref
vector-set!
vector-sort
vector-sort!
vector?
violation?
warning-level
warning?
weak-core-hashtable?
weak-hashtable?
weak-mapping-key
weak-mapping-value
weak-mapping?
when
who-condition?
with-exception-handler
with-input-from-file
with-output-to-file
with-syntax
write
write-char
write-with-shared-structure
zero?)
(import
(core primitives)
(core optimize)
(core parameters)
(core io)
(core files)
(core exceptions)
(core arithmetic)
(core sorting)
(core bytevectors)
(core syntax-case)
(core r5rs)
(core control)
(core optargs)
(core lists)
(core destructuring)
(core records)
(core conditions)
(core bytevector-transcoders)
(core unicode)
(core hashtables)
(core struct)
(core enums)))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/df2f76eff07a76fc6102dcd1eb6ef933ab8b8399/stdlib/core.scm | scheme | (library (core)
(export
&assertion
&condition
&error
&i/o
&i/o-decoding
&i/o-encoding
&i/o-file-already-exists
&i/o-file-does-not-exist
&i/o-file-is-read-only
&i/o-file-protection
&i/o-filename
&i/o-invalid-position
&i/o-port
&i/o-read
&i/o-write
&implementation-restriction
&irritants
&lexical
&message
&no-infinities
&no-nans
&non-continuable
&serious
&syntax
&undefined
&violation
&warning
&who
*
+
-
...
/
<
<=
=
=>
>
>=
_
abs
acos
acquire-lockfile
add-library-path
add-load-path
and
angle
append
apply
architecture-feature
asin
assert
assertion-violation
assertion-violation?
assoc
assp
assq
assv
atan
auto-compile-cache
auto-compile-verbose
backtrace
backtrace-line-length
begin
binary-port?
bitwise-and
bitwise-arithmetic-shift
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
bitwise-bit-count
bitwise-bit-field
bitwise-bit-set?
bitwise-copy-bit
bitwise-copy-bit-field
bitwise-first-bit-set
bitwise-if
bitwise-ior
bitwise-length
bitwise-not
bitwise-reverse-bit-field
bitwise-rotate-bit-field
bitwise-xor
boolean=?
boolean?
bound-identifier=?
break
buffer-mode
buffer-mode?
bytevector->pinned-c-void*
bytevector->sint-list
bytevector->string
bytevector->u8-list
bytevector->uint-list
bytevector-c-double-ref
bytevector-c-double-set!
bytevector-c-float-ref
bytevector-c-float-set!
bytevector-c-int-ref
bytevector-c-int-set!
bytevector-c-int16-ref
bytevector-c-int16-set!
bytevector-c-int32-ref
bytevector-c-int32-set!
bytevector-c-int64-ref
bytevector-c-int64-set!
bytevector-c-int8-ref
bytevector-c-int8-set!
bytevector-c-long-long-ref
bytevector-c-long-long-set!
bytevector-c-long-ref
bytevector-c-long-set!
bytevector-c-short-ref
bytevector-c-short-set!
bytevector-c-strlen
bytevector-c-uint16-ref
bytevector-c-uint32-ref
bytevector-c-uint64-ref
bytevector-c-uint8-ref
bytevector-c-unsigned-int-ref
bytevector-c-unsigned-long-long-ref
bytevector-c-unsigned-long-ref
bytevector-c-unsigned-short-ref
bytevector-c-void*-ref
bytevector-c-void*-set!
bytevector-copy
bytevector-copy!
bytevector-fill!
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!
bytevector-ieee-double-ref
bytevector-ieee-double-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!
bytevector-ieee-single-ref
bytevector-ieee-single-set!
bytevector-length
bytevector-mapping?
bytevector-s16-native-ref
bytevector-s16-native-set!
bytevector-s16-ref
bytevector-s16-set!
bytevector-s32-native-ref
bytevector-s32-native-set!
bytevector-s32-ref
bytevector-s32-set!
bytevector-s64-native-ref
bytevector-s64-native-set!
bytevector-s64-ref
bytevector-s64-set!
bytevector-s8-ref
bytevector-s8-set!
bytevector-sint-ref
bytevector-sint-set!
bytevector-u16-native-ref
bytevector-u16-native-set!
bytevector-u16-ref
bytevector-u16-set!
bytevector-u32-native-ref
bytevector-u32-native-set!
bytevector-u32-ref
bytevector-u32-set!
bytevector-u64-native-ref
bytevector-u64-native-set!
bytevector-u64-ref
bytevector-u64-set!
bytevector-u8-ref
bytevector-u8-set!
bytevector-uint-ref
bytevector-uint-set!
bytevector=?
bytevector?
c-main-argc
c-main-argv
caaaar
caaadr
caaar
caadar
caaddr
caadr
caar
cadaar
cadadr
cadar
caddar
cadddr
caddr
cadr
call-with-bytevector-output-port
call-with-current-continuation
call-with-input-file
call-with-output-file
call-with-port
call-with-string-output-port
call-with-values
call/cc
car
case
case-lambda
cdaaar
cdaadr
cdaar
cdadar
cdaddr
cdadr
cdar
cddaar
cddadr
cddar
cdddar
cddddr
cdddr
cddr
cdr
ceiling
change-file-mode
char->integer
char-alphabetic?
char-ci<=?
char-ci<?
char-ci=?
char-ci>=?
char-ci>?
char-downcase
char-foldcase
char-general-category
char-lower-case?
char-numeric?
char-title-case?
char-titlecase
char-upcase
char-upper-case?
char-whitespace?
char<=?
char<?
char=?
char>=?
char>?
char?
circular-list?
close-input-port
close-output-port
close-port
closure-code
closure-codegen
cmwc-random-real
cmwc-random-u32
codegen-cdecl-callback
codegen-cdecl-callout
codegen-queue-count
codegen-queue-push!
collect
collect-notify
collect-stack-notify
collect-trip-bytes
command-line
command-line-shift
compile
compile-coreform
complex?
cond
condition
condition-accessor
condition-irritants
condition-message
condition-predicate
condition-who
condition?
cons
cons*
continuation-to-exit
copy-environment-macros!
copy-environment-variables!
core-eval
core-hashtable->alist
core-hashtable-clear!
core-hashtable-contains?
core-hashtable-copy
core-hashtable-delete!
core-hashtable-equivalence-function
core-hashtable-hash-function
core-hashtable-mutable?
core-hashtable-ref
core-hashtable-set!
core-hashtable-size
core-hashtable?
core-read
coreform-optimize
cos
count-pair
create-directory
create-hard-link
create-symbolic-link
current-after-expansion-hook
current-directory
current-dynamic-environment
current-environment
current-error-port
current-exception-printer
current-input-port
current-library-infix
current-library-suffix
current-macro-environment
current-output-port
current-primitive-prefix
current-rename-delimiter
current-source-comments
current-variable-environment
cyclic-object?
datum
datum->syntax
decode-flonum
decode-microsecond
define
define-condition-type
define-enumeration
define-library
define-macro
define-record-type
define-struct
define-syntax
delay
delete-file
denominator
destructuring-bind
destructuring-match
directory-list
display
display-backtrace
display-codegen-statistics
display-heap-statistics
display-object-statistics
div
div-and-mod
div0
div0-and-mod0
do
drop
drop-last-cdr
drop-last-n-pair
drop-last-pair
dynamic-wind
else
encode-microsecond
endianness
enum-set->list
enum-set-complement
enum-set-constructor
enum-set-difference
enum-set-indexer
enum-set-intersection
enum-set-member?
enum-set-projection
enum-set-subset?
enum-set-union
enum-set-universe
enum-set=?
enum-set?
environment
eof-object
eof-object?
eol-style
eq?
equal-hash
equal?
eqv?
errno/string
error
error-handling-mode
error?
eval
even?
exact
exact->inexact
exact-integer-sqrt
exact?
exists
exit
exp
expansion-backtrace
expt
extract-accumulated-bytevector
extract-accumulated-string
feature-identifiers
fields
file-directory?
file-executable?
file-exists?
file-options
file-readable?
file-regular?
file-size-in-bytes
file-stat-atime
file-stat-ctime
file-stat-mtime
file-symbolic-link?
file-writable?
filter
find
finite?
fixnum->flonum
fixnum-width
fixnum?
fl*
fl+
fl-
fl/
fl<=?
fl<?
fl=?
fl>=?
fl>?
flabs
flacos
flasin
flatan
flceiling
flcos
fldenominator
fldiv
fldiv-and-mod
fldiv0
fldiv0-and-mod0
fleven?
flexp
flexpt
flfinite?
flfloor
flinfinite?
flinteger?
fllog
flmax
flmin
flmod
flmod0
flnan?
flnegative?
flnumerator
flodd?
flonum?
floor
flpositive?
flround
flsin
flsqrt
fltan
fltruncate
flush-output-port
flzero?
fold-left
fold-right
for-all
for-each
force
format
free-identifier=?
fulfill-feature-requirements?
fx*
fx*/carry
fx+
fx+/carry
fx-
fx-/carry
fx<=?
fx<?
fx=?
fx>=?
fx>?
fxand
fxarithmetic-shift
fxarithmetic-shift-left
fxarithmetic-shift-right
fxbit-count
fxbit-field
fxbit-set?
fxcopy-bit
fxcopy-bit-field
fxdiv
fxdiv-and-mod
fxdiv0
fxdiv0-and-mod0
fxeven?
fxfirst-bit-set
fxif
fxior
fxlength
fxmax
fxmin
fxmod
fxmod0
fxnegative?
fxnot
fxodd?
fxpositive?
fxreverse-bit-field
fxrotate-bit-field
fxxor
fxzero?
gcd
generate-temporaries
generate-temporary-symbol
gensym
get-accumulated-bytevector
get-accumulated-string
get-bytevector-all
get-bytevector-n
get-bytevector-n!
get-bytevector-some
get-char
get-datum
get-line
get-string-all
get-string-n
get-string-n!
get-u8
getenv
gethostname
greatest-fixnum
guard
hashtable->alist
hashtable-clear!
hashtable-contains?
hashtable-copy
hashtable-delete!
hashtable-entries
hashtable-equivalence-function
hashtable-hash-function
hashtable-keys
hashtable-mutable?
hashtable-ref
hashtable-set!
hashtable-size
hashtable-update!
hashtable?
home-directory
i/o-decoding-error?
i/o-encoding-error-char
i/o-encoding-error?
i/o-error-filename
i/o-error-port
i/o-error-position
i/o-error?
i/o-file-already-exists-error?
i/o-file-does-not-exist-error?
i/o-file-is-read-only-error?
i/o-file-protection-error?
i/o-filename-error?
i/o-invalid-position-error?
i/o-port-error?
i/o-read-error?
i/o-write-error?
identifier-syntax
identifier?
if
imag-part
immutable
implementation-restriction-violation?
include
include-ci
inexact
inexact->exact
inexact?
infinite?
input-port?
integer->char
integer-valued?
integer?
interaction-environment
iota
irritants-condition?
lambda
last-cdr
last-n-pair
last-pair
latin-1-codec
lcm
least-fixnum
length
let
let*
let*-values
let-optionals
let-syntax
let-values
letrec
letrec*
letrec-syntax
lexical-violation?
library
library-extensions
list
list->string
list->vector
list-copy
list-head
list-of-unique-symbols?
list-ref
list-sort
list-tail
list-transpose
list-transpose*
list-transpose+
list?
load
load-shared-object
log
lookahead-char
lookahead-u8
lookup-process-environment
lookup-shared-object
macro-expand
magnitude
make-assertion-violation
make-bytevector
make-bytevector-mapping
make-cmwc-random-state
make-core-hashtable
make-custom-binary-input-port
make-custom-binary-input/output-port
make-custom-binary-output-port
make-custom-textual-input-port
make-custom-textual-input/output-port
make-custom-textual-output-port
make-enumeration
make-environment
make-eq-hashtable
make-eqv-hashtable
make-error
make-hashtable
make-i/o-decoding-error
make-i/o-encoding-error
make-i/o-error
make-i/o-file-already-exists-error
make-i/o-file-does-not-exist-error
make-i/o-file-is-read-only-error
make-i/o-file-protection-error
make-i/o-filename-error
make-i/o-invalid-position-error
make-i/o-port-error
make-i/o-read-error
make-i/o-write-error
make-implementation-restriction-violation
make-irritants-condition
make-lexical-violation
make-list
make-message-condition
make-no-infinities-violation
make-no-nans-violation
make-non-continuable-violation
make-parameter
make-polar
make-record-constructor-descriptor
make-record-type
make-record-type-descriptor
make-rectangular
make-serious-condition
make-socket
make-string
make-string-hashtable
make-string-input-port
make-string-output-port
make-syntax-violation
make-temporary-file-port
make-transcoded-port
make-transcoder
make-tuple
make-undefined-violation
make-uuid
make-variable-transformer
make-vector
make-violation
make-warning
make-weak-core-hashtable
make-weak-hashtable
make-weak-mapping
make-who-condition
map
mat4x4-add
mat4x4-dup
mat4x4-frustum
mat4x4-identity
mat4x4-invert
mat4x4-look-at
mat4x4-mul
mat4x4-ortho
mat4x4-orthonormalize
mat4x4-perspective
mat4x4-rotate
mat4x4-scale
mat4x4-sub
mat4x4-translate
mat4x4-transpose
max
member
memp
memq
memv
message-condition?
microsecond
microsecond->string
microsecond->utc
min
mod
mod0
modulo
mutable
nan?
native-endianness
native-eol-style
native-transcoder
native-transcoder-descriptor
negative?
newline
no-infinities-violation?
no-nans-violation?
non-continuable-violation?
nonblock-byte-ready?
nongenerative
not
null?
number->string
number?
numerator
odd?
opaque
open-builtin-data-input-port
open-bytevector-input-port
open-bytevector-output-port
open-file-input-port
open-file-input/output-port
open-file-output-port
open-input-file
open-output-file
open-port
open-string-input-port
open-string-output-port
open-temporary-file-port
or
output-port-buffer-mode
output-port?
pair?
parameterize
parent
parent-rtd
partition
peek-char
port-closed?
port-device-subtype
port-eof?
port-has-port-position?
port-has-set-port-position!?
port-position
port-transcoder
port-transcoder-descriptor
port?
positive?
pretty-print
pretty-print-initial-indent
pretty-print-line-length
pretty-print-maximum-lines
pretty-print-unwrap-syntax
procedure?
process-environment->alist
process-spawn
process-wait
protocol
put-byte
put-bytevector
put-char
put-datum
put-fasl
put-string
put-u8
quasiquote
quasisyntax
quote
quotient
raise
raise-continuable
rational-valued?
rational?
rationalize
read
read-char
read-with-shared-structure
real->flonum
real-part
real-valued?
real?
record-accessor
record-constructor
record-constructor-descriptor
record-field-mutable?
record-mutator
record-predicate
record-print-nesting-limit
record-rtd
record-type-descriptor
record-type-descriptor?
record-type-field-names
record-type-generative?
record-type-name
record-type-opaque?
record-type-parent
record-type-rcd
record-type-rtd
record-type-sealed?
record-type-uid
record-type?
record?
release-lockfile
remainder
remove
remove-duplicate-symbols
remp
remq
remv
rename-file
restricted-print-line-length
reverse
round
scheme-error
scheme-library-exports
scheme-library-paths
scheme-load-paths
scheme-load-verbose
sealed
serious-condition?
set!
set-car!
set-cdr!
set-current-error-port!
set-current-input-port!
set-current-output-port!
set-port-position!
set-top-level-value!
shutdown-output-port
simple-conditions
sin
sint-list->bytevector
socket->port
socket-accept
socket-close
socket-port
socket-recv
socket-send
socket-shutdown
socket?
sqrt
standard-error-port
standard-input-port
standard-output-port
string
string->bytevector
string->list
string->number
string->symbol
string->uninterned-symbol
string->utf16
string->utf32
string->utf8
string->utf8/nul
string-append
string-ci-hash
string-ci<=?
string-ci<?
string-ci=?
string-ci>=?
string-ci>?
string-contains
string-copy
string-downcase
string-fill!
string-foldcase
string-for-each
string-hash
string-length
string-normalize-nfc
string-normalize-nfd
string-normalize-nfkc
string-normalize-nfkd
string-ref
string-set!
string-titlecase
string-upcase
string<=?
string<?
string=?
string>=?
string>?
string?
subr?
substring
symbol->string
symbol-contains
symbol-hash
symbol=?
symbol?
syntax
syntax->datum
syntax-case
syntax-rules
syntax-violation
syntax-violation-form
syntax-violation-subform
syntax-violation?
system
system-environment
system-extension-path
system-share-path
take
tan
textual-port?
time-usage
top-level-bound?
top-level-value
transcoded-port
transcoder-codec
transcoder-eol-style
transcoder-error-handling-mode
truncate
tuple
tuple->list
tuple-index
tuple-length
tuple-ref
tuple-set!
tuple?
u8-list->bytevector
uint-list->bytevector
undefined-violation?
uninterned-symbol-prefix
uninterned-symbol-suffix
uninterned-symbol?
unless
unquote
unquote-splicing
unspecified
unspecified?
unsyntax
unsyntax-splicing
usleep
utf-16-codec
utf-8-codec
utf16->string
utf32->string
utf8->string
values
vector
vector->list
vector-copy
vector-fill!
vector-for-each
vector-length
vector-map
vector-ref
vector-set!
vector-sort
vector-sort!
vector?
violation?
warning-level
warning?
weak-core-hashtable?
weak-hashtable?
weak-mapping-key
weak-mapping-value
weak-mapping?
when
who-condition?
with-exception-handler
with-input-from-file
with-output-to-file
with-syntax
write
write-char
write-with-shared-structure
zero?)
(import
(core primitives)
(core optimize)
(core parameters)
(core io)
(core files)
(core exceptions)
(core arithmetic)
(core sorting)
(core bytevectors)
(core syntax-case)
(core r5rs)
(core control)
(core optargs)
(core lists)
(core destructuring)
(core records)
(core conditions)
(core bytevector-transcoders)
(core unicode)
(core hashtables)
(core struct)
(core enums)))
| |
98a788fe00a480f654316de673003df55e215cdb3d7a8b3c1ea9105c766d3085 | tsloughter/kuberl | kuberl_v1alpha1_volume_attachment_status.erl | -module(kuberl_v1alpha1_volume_attachment_status).
-export([encode/1]).
-export_type([kuberl_v1alpha1_volume_attachment_status/0]).
-type kuberl_v1alpha1_volume_attachment_status() ::
#{ 'attachError' => kuberl_v1alpha1_volume_error:kuberl_v1alpha1_volume_error(),
'attached' := boolean(),
'attachmentMetadata' => maps:map(),
'detachError' => kuberl_v1alpha1_volume_error:kuberl_v1alpha1_volume_error()
}.
encode(#{ 'attachError' := AttachError,
'attached' := Attached,
'attachmentMetadata' := AttachmentMetadata,
'detachError' := DetachError
}) ->
#{ 'attachError' => AttachError,
'attached' => Attached,
'attachmentMetadata' => AttachmentMetadata,
'detachError' => DetachError
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1alpha1_volume_attachment_status.erl | erlang | -module(kuberl_v1alpha1_volume_attachment_status).
-export([encode/1]).
-export_type([kuberl_v1alpha1_volume_attachment_status/0]).
-type kuberl_v1alpha1_volume_attachment_status() ::
#{ 'attachError' => kuberl_v1alpha1_volume_error:kuberl_v1alpha1_volume_error(),
'attached' := boolean(),
'attachmentMetadata' => maps:map(),
'detachError' => kuberl_v1alpha1_volume_error:kuberl_v1alpha1_volume_error()
}.
encode(#{ 'attachError' := AttachError,
'attached' := Attached,
'attachmentMetadata' := AttachmentMetadata,
'detachError' := DetachError
}) ->
#{ 'attachError' => AttachError,
'attached' => Attached,
'attachmentMetadata' => AttachmentMetadata,
'detachError' => DetachError
}.
| |
aaaa47b4edda12a794c26fd6759ccd1099ab4e806925a6511e277d167b483274 | UlfNorell/insane | Internal.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies ,
DeriveDataTypeable , DeriveFunctor , ,
DeriveTraversable #
DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
module Syntax.Internal where
import Control.Applicative
import Data.Traversable
import Data.Typeable
import Data.Foldable
import qualified Syntax.Abs as Abs
import Utils
-- Pointers ---------------------------------------------------------------
newtype Ptr = Ptr Integer
deriving (Eq, Ord)
instance Show Ptr where
show (Ptr n) = "*" ++ show n
newtype Type = TypePtr Ptr deriving (Eq, Typeable)
newtype Term = TermPtr Ptr deriving (Eq, Typeable)
newtype Clause = ClausePtr Ptr deriving (Eq, Typeable)
newtype Pair a b = PairPtr Ptr deriving (Eq, Typeable)
newtype Unit = UnitPtr Ptr deriving (Eq, Typeable)
class (Show ptr, Eq ptr, Show a, Typeable a) => Pointer ptr a | ptr -> a, a -> ptr where
toRawPtr :: ptr -> Ptr
fromRawPtr :: Ptr -> ptr
instance Pointer Unit () where toRawPtr (UnitPtr p) = p; fromRawPtr = UnitPtr
instance Pointer Type Type' where toRawPtr (TypePtr p) = p; fromRawPtr = TypePtr
instance Pointer Term Term' where toRawPtr (TermPtr p) = p; fromRawPtr = TermPtr
instance Pointer Clause Clause' where toRawPtr (ClausePtr p) = p; fromRawPtr = ClausePtr
instance (Show a, Show b, Typeable a, Typeable b) =>
Pointer (Pair a b) (a,b) where
toRawPtr (PairPtr p) = p
fromRawPtr = PairPtr
instance Show Type where show = show . toRawPtr
instance Show Term where show = show . toRawPtr
instance Show Clause where show = show . toRawPtr
instance Show (Pair a b) where show (PairPtr p) = show p
instance Show Unit where show = show . toRawPtr
-- Syntax -----------------------------------------------------------------
type Arity = Int
data Definition
= Axiom Name Type
| Defn Name Type [Clause]
| Data Name Type [Constructor]
| Cons Name Type
deriving (Show, Typeable)
data Clause' = Clause [Pattern] Term
deriving (Show, Typeable)
data Constructor = Constr Name Arity
deriving (Show, Typeable)
data Pattern = VarP Name
| ConP Name [Pattern]
deriving (Show, Typeable)
type Name = String
type DeBruijnIndex = Integer
type Telescope = [RBind Type]
data RBind a = RBind String a
deriving (Show)
data Type' = Pi Type (Abs Type)
| RPi Telescope Type
| Fun Type Type
| El Term
| Set
deriving (Show, Typeable)
data Term' = Lam (Abs Term)
| App Term Term
| Var DeBruijnIndex
| Def Name
deriving (Show, Typeable)
data Abs a = Abs { absName :: Name, absBody :: a }
deriving (Typeable, Functor, Foldable, Traversable)
instance Show a => Show (Abs a) where
show (Abs _ b) = show b
| null | https://raw.githubusercontent.com/UlfNorell/insane/694d5dcfdc3d4dd4f31138228ef8d87dd84fa9ec/typechecker/Syntax/Internal.hs | haskell | Pointers ---------------------------------------------------------------
Syntax ----------------------------------------------------------------- | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies ,
DeriveDataTypeable , DeriveFunctor , ,
DeriveTraversable #
DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
DeriveTraversable #-}
module Syntax.Internal where
import Control.Applicative
import Data.Traversable
import Data.Typeable
import Data.Foldable
import qualified Syntax.Abs as Abs
import Utils
newtype Ptr = Ptr Integer
deriving (Eq, Ord)
instance Show Ptr where
show (Ptr n) = "*" ++ show n
newtype Type = TypePtr Ptr deriving (Eq, Typeable)
newtype Term = TermPtr Ptr deriving (Eq, Typeable)
newtype Clause = ClausePtr Ptr deriving (Eq, Typeable)
newtype Pair a b = PairPtr Ptr deriving (Eq, Typeable)
newtype Unit = UnitPtr Ptr deriving (Eq, Typeable)
class (Show ptr, Eq ptr, Show a, Typeable a) => Pointer ptr a | ptr -> a, a -> ptr where
toRawPtr :: ptr -> Ptr
fromRawPtr :: Ptr -> ptr
instance Pointer Unit () where toRawPtr (UnitPtr p) = p; fromRawPtr = UnitPtr
instance Pointer Type Type' where toRawPtr (TypePtr p) = p; fromRawPtr = TypePtr
instance Pointer Term Term' where toRawPtr (TermPtr p) = p; fromRawPtr = TermPtr
instance Pointer Clause Clause' where toRawPtr (ClausePtr p) = p; fromRawPtr = ClausePtr
instance (Show a, Show b, Typeable a, Typeable b) =>
Pointer (Pair a b) (a,b) where
toRawPtr (PairPtr p) = p
fromRawPtr = PairPtr
instance Show Type where show = show . toRawPtr
instance Show Term where show = show . toRawPtr
instance Show Clause where show = show . toRawPtr
instance Show (Pair a b) where show (PairPtr p) = show p
instance Show Unit where show = show . toRawPtr
type Arity = Int
data Definition
= Axiom Name Type
| Defn Name Type [Clause]
| Data Name Type [Constructor]
| Cons Name Type
deriving (Show, Typeable)
data Clause' = Clause [Pattern] Term
deriving (Show, Typeable)
data Constructor = Constr Name Arity
deriving (Show, Typeable)
data Pattern = VarP Name
| ConP Name [Pattern]
deriving (Show, Typeable)
type Name = String
type DeBruijnIndex = Integer
type Telescope = [RBind Type]
data RBind a = RBind String a
deriving (Show)
data Type' = Pi Type (Abs Type)
| RPi Telescope Type
| Fun Type Type
| El Term
| Set
deriving (Show, Typeable)
data Term' = Lam (Abs Term)
| App Term Term
| Var DeBruijnIndex
| Def Name
deriving (Show, Typeable)
data Abs a = Abs { absName :: Name, absBody :: a }
deriving (Typeable, Functor, Foldable, Traversable)
instance Show a => Show (Abs a) where
show (Abs _ b) = show b
|
03fa08867b0aa946c048a13f025faa502b253846c776debf19be117ba8f562be | jeromesimeon/Galax | shredded_load_sigs.mli | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : shredded_load_sigs.mli , v 1.7 2007/02/01 22:08:54 simeon Exp $
(* ad hoc loading structure this prevents nastier signatures
in other places of the code. *)
module type Shredded_Load_Store = sig
type shredded_store
type namespaceid
type text
val get_store_from_docid : Nodeid.docid -> shredded_store
val preorder_of_nodeid : Nodeid.nodeid -> Nodeid.large_preorder
val docid_of_nodeid : Nodeid.nodeid -> Nodeid.docid
val invalid_nodeid : Nodeid.nodeid
val close_store : shredded_store -> unit
val sync_store : shredded_store -> unit
val preorder_of_nodeid : Nodeid.nodeid -> Nodeid.large_preorder
(* Not implemented! - Can these be bundled more carefully? *)
val get_name_of_docid : Nodeid.docid -> string * string
val namespaceid_seed : namespaceid
(* val qname_of_string : string -> qname *)
(* Fix these types (no strings) *)
val shredded_text_of_xml_attribute : string -> text
val xml_attribute_of_shredded_text : text -> string
val shredded_text_of_text_desc : string -> text
val text_desc_of_shredded_text : text -> string
val xs_untyped_of_text : text -> Datatypes.xs_untyped
val text_of_xs_untyped : Datatypes.xs_untyped -> text
val create_shredded_store : Nodeid_context.nodeid_context -> string -> string -> int -> shredded_store
val get_docid : shredded_store -> Nodeid.docid
val store_document_node :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid
val store_element_node :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> (* Basetypes.shredded_qname *)
Namespace_symbols.relem_symbol ->
(Namespace_symbols.rtype_symbol * Dm_types.nilled * Dm_atomic.atomicValue list) option
-> namespaceid -> Nodeid.nodeid
val store_attribute_node :
shredded_store -> Nodeid.large_preorder -> (Nodeid.nodeid * namespaceid) ->
Namespace_symbols.rattr_symbol -> Datatypes.xs_untyped ->
(Dm_atomic.atomicValue list * Namespace_symbols.rtype_symbol) option
-> Nodeid.nodeid
val store_text_node :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Datatypes.xs_untyped -> Nodeid.nodeid
val store_processing_instruction :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Namespace_names.ncname * Datatypes.xs_untyped -> Nodeid.nodeid
val store_comment :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Datatypes.xs_untyped -> Nodeid.nodeid
val store_children :
shredded_store -> Nodeid.nodeid -> Nodeid.nodeid Cursor.cursor -> unit
val store_attributes :
shredded_store -> Nodeid.nodeid -> Nodeid.nodeid Cursor.cursor -> unit
val store_nsenv :
shredded_store -> namespaceid -> Namespace_context.binding_table -> namespaceid
val sync_store : shredded_store -> unit
end
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/shredded/shredded_load_sigs.mli | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
ad hoc loading structure this prevents nastier signatures
in other places of the code.
Not implemented! - Can these be bundled more carefully?
val qname_of_string : string -> qname
Fix these types (no strings)
Basetypes.shredded_qname | Copyright 2001 - 2007 .
$ I d : shredded_load_sigs.mli , v 1.7 2007/02/01 22:08:54 simeon Exp $
module type Shredded_Load_Store = sig
type shredded_store
type namespaceid
type text
val get_store_from_docid : Nodeid.docid -> shredded_store
val preorder_of_nodeid : Nodeid.nodeid -> Nodeid.large_preorder
val docid_of_nodeid : Nodeid.nodeid -> Nodeid.docid
val invalid_nodeid : Nodeid.nodeid
val close_store : shredded_store -> unit
val sync_store : shredded_store -> unit
val preorder_of_nodeid : Nodeid.nodeid -> Nodeid.large_preorder
val get_name_of_docid : Nodeid.docid -> string * string
val namespaceid_seed : namespaceid
val shredded_text_of_xml_attribute : string -> text
val xml_attribute_of_shredded_text : text -> string
val shredded_text_of_text_desc : string -> text
val text_desc_of_shredded_text : text -> string
val xs_untyped_of_text : text -> Datatypes.xs_untyped
val text_of_xs_untyped : Datatypes.xs_untyped -> text
val create_shredded_store : Nodeid_context.nodeid_context -> string -> string -> int -> shredded_store
val get_docid : shredded_store -> Nodeid.docid
val store_document_node :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid
val store_element_node :
Namespace_symbols.relem_symbol ->
(Namespace_symbols.rtype_symbol * Dm_types.nilled * Dm_atomic.atomicValue list) option
-> namespaceid -> Nodeid.nodeid
val store_attribute_node :
shredded_store -> Nodeid.large_preorder -> (Nodeid.nodeid * namespaceid) ->
Namespace_symbols.rattr_symbol -> Datatypes.xs_untyped ->
(Dm_atomic.atomicValue list * Namespace_symbols.rtype_symbol) option
-> Nodeid.nodeid
val store_text_node :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Datatypes.xs_untyped -> Nodeid.nodeid
val store_processing_instruction :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Namespace_names.ncname * Datatypes.xs_untyped -> Nodeid.nodeid
val store_comment :
shredded_store -> Nodeid.large_preorder -> Nodeid.nodeid -> Datatypes.xs_untyped -> Nodeid.nodeid
val store_children :
shredded_store -> Nodeid.nodeid -> Nodeid.nodeid Cursor.cursor -> unit
val store_attributes :
shredded_store -> Nodeid.nodeid -> Nodeid.nodeid Cursor.cursor -> unit
val store_nsenv :
shredded_store -> namespaceid -> Namespace_context.binding_table -> namespaceid
val sync_store : shredded_store -> unit
end
|
fcde98aa6f1fa3dae37255796180c432538fad23fd0c247b5d94fba34713e34b | footprintanalytics/footprint-web | async_test.clj | (ns metabase.query-processor.async-test
(:require [clojure.test :refer :all]
[metabase.query-processor.async :as qp.async]
[metabase.test :as mt]
[metabase.test.util.async :as tu.async]))
(deftest async-result-metadata-test
(testing "Should be able to get result metadata async"
(tu.async/with-open-channels [result-chan (qp.async/result-metadata-for-query-async
{:database (mt/id)
:type :query
:query {:source-table (mt/id :venues)
:fields [[:field (mt/id :venues :name) nil]]}})]
(is (= [{:name "NAME"
:display_name "Name"
:base_type :type/Text
:coercion_strategy nil
:effective_type :type/Text
:semantic_type :type/Name
:fingerprint {:global {:distinct-count 100, :nil% 0.0},
:type #:type {:Text
{:percent-json 0.0,
:percent-url 0.0,
:percent-email 0.0,
:percent-state 0.0,
:average-length 15.63}}}
:description nil
:table_id (mt/id :venues)
:settings nil
:source :fields
:nfc_path nil
:parent_id nil
:visibility_type :normal
:id (mt/id :venues :name)
:field_ref [:field (mt/id :venues :name) nil]}]
(mt/wait-for-result result-chan 1000))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/query_processor/async_test.clj | clojure | (ns metabase.query-processor.async-test
(:require [clojure.test :refer :all]
[metabase.query-processor.async :as qp.async]
[metabase.test :as mt]
[metabase.test.util.async :as tu.async]))
(deftest async-result-metadata-test
(testing "Should be able to get result metadata async"
(tu.async/with-open-channels [result-chan (qp.async/result-metadata-for-query-async
{:database (mt/id)
:type :query
:query {:source-table (mt/id :venues)
:fields [[:field (mt/id :venues :name) nil]]}})]
(is (= [{:name "NAME"
:display_name "Name"
:base_type :type/Text
:coercion_strategy nil
:effective_type :type/Text
:semantic_type :type/Name
:fingerprint {:global {:distinct-count 100, :nil% 0.0},
:type #:type {:Text
{:percent-json 0.0,
:percent-url 0.0,
:percent-email 0.0,
:percent-state 0.0,
:average-length 15.63}}}
:description nil
:table_id (mt/id :venues)
:settings nil
:source :fields
:nfc_path nil
:parent_id nil
:visibility_type :normal
:id (mt/id :venues :name)
:field_ref [:field (mt/id :venues :name) nil]}]
(mt/wait-for-result result-chan 1000))))))
| |
ea0e7d42d96e50d4f351becdda9ce1ed4c5a138cf9d65fb30be54ce7fa830a72 | tfeb/tfeb-lisp-hax | wrapping-standard.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File - wrapping-standard.lisp
;; Description - Wrapping standard method combination
Author - ( tfb at lostwithiel )
Created On - We d May 29 17:55:55 2002
Last Modified On - Sun Aug 30 14:03:13 2020
Last Modified By - ( tfb at kingston.fritz.box )
;; Update Count - 4
;; Status - Unknown
;;
$ Id$
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Wrapping standard method combination
;;;
wrapping-standard.lisp is copyright 2001,2012 by me , , and
;;; may be used for any purpose whatsoever by anyone. It has no
;;; warranty whatsoever. I would appreciate acknowledgement if you use
;;; it in anger, and I would also very much appreciate any feedback or
;;; bug fixes.
(defpackage :org.tfeb.hax.wrapping-standard
(:use :cl)
(:export #:wrapping-standard))
(in-package :org.tfeb.hax.wrapping-standard)
(provide :org.tfeb.hax.wrapping-standard)
(define-method-combination wrapping-standard ()
Like standard but WRAPPING methods get called in
;; *most-specific-last* order, and before and after any other methods
;; The complete order is then:
;;
;; least specific wrapping method
;; ... call-next-method ...
;; most specific around method
;; ... call-next-method ...
;; most specific before method ... least specific before method
;; most specific primary method
;; [... call-next-method ... other primary methods ...]
;; least specific after method ... most specific after method
;; rest of most specific around method
;; rest of least specific wrapping method
;;
((around (:around))
(wrapping (:wrapping) :order :most-specific-last)
(before (:before))
(primary () :required t)
(after (:after)))
(flet ((call-methods (methods)
(mapcar #'(lambda (method)
`(call-method ,method))
methods)))
(let* ((form (if (or before after (rest primary))
`(multiple-value-prog1
(progn ,@(call-methods before)
(call-method ,(first primary)
,(rest primary)))
,@(call-methods (reverse after)))
`(call-method ,(first primary))))
(around-form (if around
`(call-method ,(first around)
(,@(rest around)
(make-method ,form)))
form)))
(if wrapping
`(call-method ,(first wrapping)
(,@(rest wrapping)
(make-method ,around-form)))
around-form))))
#||
(defgeneric complicated (x &key cache recompute)
(:method-combination wrapping-standard)
(:method :wrapping (x &key (cache t) (recompute nil))
(call-next-method x :cache cache :recompute recompute)))
||#
| null | https://raw.githubusercontent.com/tfeb/tfeb-lisp-hax/6a56b40cc90d790be4ee9ad02afe8b459e583cb8/wrapping-standard.lisp | lisp | -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
File - wrapping-standard.lisp
Description - Wrapping standard method combination
Update Count - 4
Status - Unknown
Wrapping standard method combination
may be used for any purpose whatsoever by anyone. It has no
warranty whatsoever. I would appreciate acknowledgement if you use
it in anger, and I would also very much appreciate any feedback or
bug fixes.
*most-specific-last* order, and before and after any other methods
The complete order is then:
least specific wrapping method
... call-next-method ...
most specific around method
... call-next-method ...
most specific before method ... least specific before method
most specific primary method
[... call-next-method ... other primary methods ...]
least specific after method ... most specific after method
rest of most specific around method
rest of least specific wrapping method
(defgeneric complicated (x &key cache recompute)
(:method-combination wrapping-standard)
(:method :wrapping (x &key (cache t) (recompute nil))
(call-next-method x :cache cache :recompute recompute)))
| Author - ( tfb at lostwithiel )
Created On - We d May 29 17:55:55 2002
Last Modified On - Sun Aug 30 14:03:13 2020
Last Modified By - ( tfb at kingston.fritz.box )
$ Id$
wrapping-standard.lisp is copyright 2001,2012 by me , , and
(defpackage :org.tfeb.hax.wrapping-standard
(:use :cl)
(:export #:wrapping-standard))
(in-package :org.tfeb.hax.wrapping-standard)
(provide :org.tfeb.hax.wrapping-standard)
(define-method-combination wrapping-standard ()
Like standard but WRAPPING methods get called in
((around (:around))
(wrapping (:wrapping) :order :most-specific-last)
(before (:before))
(primary () :required t)
(after (:after)))
(flet ((call-methods (methods)
(mapcar #'(lambda (method)
`(call-method ,method))
methods)))
(let* ((form (if (or before after (rest primary))
`(multiple-value-prog1
(progn ,@(call-methods before)
(call-method ,(first primary)
,(rest primary)))
,@(call-methods (reverse after)))
`(call-method ,(first primary))))
(around-form (if around
`(call-method ,(first around)
(,@(rest around)
(make-method ,form)))
form)))
(if wrapping
`(call-method ,(first wrapping)
(,@(rest wrapping)
(make-method ,around-form)))
around-form))))
|
7b771a131b23aa0d4d90735d61d5d3e4733f05ff500ad3950586863e014e083f | smucclaw/dsl | Lib.hs | # LANGUAGE PostfixOperators #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
module Lib where
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Data.Text (Text, pack, unpack)
import qualified Data.Text.IO as TIO
import Prettyprinter hiding (space)
import qualified Prettyprinter as PP
import Data.Void
import Data.List (nub, permutations, sort, sortOn, intercalate, elemIndex)
import Data.Char (toLower)
import Control.Monad (forM_)
import qualified Data.Map.Lazy as Map
import Text.Pretty.Simple (pPrint, pShow)
import Options.Applicative.Simple (simpleOptions, addCommand, addSubCommands)
import Language.Prolog
type Parser = Parsec Void Text
sc :: Parser ()
sc = L.space space1 (L.skipLineComment "//") (L.skipBlockComment "/*" "*/")
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
stringLiteral = char '"' >> manyTill L.charLiteral (char '"')
first TermExpr should always be an NL expression (: @ )
| DRule { rulename :: TermExpr -- deontic rule
, party :: TermExpr
, dmodal :: Deontic
, action :: TermExpr
, when :: Maybe TermExpr
}
| CRule { item :: TermExpr
, body :: [TermExpr]
, when :: Maybe TermExpr
}
deriving (Show, Eq)
infix constructor for NL : " potato " : @ [ ( " en","Solanum Tuberosum " ) ]
| TKey Key -- "potato"
| All [TermExpr] -- and -- each element must evaluate true
or -- only one element is needed to be true
| And [TermExpr] -- set union! inclusive "and" is not a logical "and"! more of an "or"
ace " of " bass , useful when either lhs or rhs term is itself an All / Any list
| UnOp UnOp TermExpr
| Prim PrimType
| TE0 -- nil
deriving (Show, Eq)
data UnOp = HasAttr
deriving (Show, Eq)
data BinOp = Cons
| Compound
| HasType
| HasValue
| TE2 TermExpr
deriving (Show, Eq)
type Key = String -- ideally spaceless but can contain spaces. Maybe a Mk to s/ /_/g
type NLTag = (Key,String)
data Deontic = DMust | DMay | DShant deriving (Show, Eq)
an L4 document is a list of stanzas
parseL4 :: Parser [Stm]
parseL4 = do
stm <- parseStm
rhs <- parseL4
eof
return (stm : rhs)
-- a stanza
parseStm :: Parser Stm
parseStm = do
many newline
stm <- choice [ try (Section <$> (lexeme "SECTION" *> parseNLStr))
, try parseDeonticRule
, try parseConstitutiveRule
]
return stm
-- RULE PARTY X MUST Y
parseDeonticRule :: Parser Stm
parseDeonticRule = do
ruleName <- space *> lexeme "RULE" *> parseNLStr <* lexeme "ISA" <* lexeme "DeonticRule" <* some newline
party <- space *> lexeme "PARTY" *> parseNLStr <* some newline
dmodal <- space *> lexeme (DMust <$ "MUST" <|>
DMay <$ "MAY" <|>
DShant <$ "SHANT")
action <- lexeme parseTermExpr <* some newline
when <- optional (space *> lexeme "WHEN" *> parseTermExpr)
return (DRule ruleName party dmodal action when)
-- DEFINE X IS BLAH
parseConstitutiveRule :: Parser Stm
parseConstitutiveRule = do
item <- space *> lexeme "DEFINE" *> parseNLStr <* some newline
body <- many (lexeme parseTermExpr <* some newline)
when <- optional (space *> lexeme "WHEN" *> parseTermExpr)
return (CRule item body when)
SomeString : en:"Some String "
parseNLStr :: Parser TermExpr
parseNLStr = do
exPart <- lexeme $ some (alphaNumChar <|> char '.')
tagsPart <- many (lexeme parseTag)
return $ exPart :@ tagsPart
-- :en:"Some String"
parseTag :: Parser NLTag
parseTag = do
lhs <- between (char ':') (char ':') (some alphaNumChar)
rhs <- stringLiteral
return (lhs, rhs)
-- sooner or later we will need to think about -recursion
parseTermExpr :: Parser TermExpr
parseTermExpr = return $ "burf" :@ []
stmToPlain :: Stm -> String
stmToPlain (Section te) = plain te
stmToProlog :: Stm -> Doc ann
stmToProlog (Section te) = "%% " <> pretty (stmToL4 (Section te))
stmToProlog (DRule rn p d a w) =
let headP = "drule" <> parencomma [ dquotes (pretty $ plain rn)
, "SubRuleName"
, teToProlog p
, pretty ((toLower <$> dshow d) :: String)
, teToProlog a ]
varargs = teToProlog p : unwrapP a
in vsep ( [ if null w
then headP <> pretty '.'
else nest 4 (headP <+> ":-" <+> ("subRule" <> parencomma ("SubRuleName" : varargs) <> pretty '.') )
] ++ asPrologSubrules w varargs )
asPrologSubrules :: Maybe TermExpr -> [Doc ann] -> [Doc ann]
asPrologSubrules Nothing _ = [emptyDoc]
asPrologSubrules (Just (Any termexprs)) varargs = asPrologSubrule varargs <$> (zip ['A'..] termexprs)
asPrologSubrule :: [Doc ann] -> (Char, TermExpr) -> Doc ann
asPrologSubrule varargs (ruleNum, te) =
hang 5
("\nsubRule" <> parencomma ([ pretty ("subRule_"++[ruleNum]) ] ++ varargs) <+> (":-") <> line <> (teToProlog te) <> pretty '.')
unwrapP :: TermExpr -> [Doc ann]
unwrapP (mainex :@ nltags) = [pretty $ tr_ mainex]
unwrapP (TKey tkey) = [pretty $ tr_ tkey]
unwrapP (All termexprs) = teToProlog <$> termexprs
unwrapP orig@(Any termexprs) = teToProlog <$> termexprs
unwrapP (And termexprs) = teToProlog <$> termexprs
unwrapP orig@(BinOp te1 bo2 te3) = [teToProlog te1, teToProlog te3]
parencomma docs = parens (hsep $ punctuate (pretty ',') docs)
teToProlog :: TermExpr -> Doc ann
teToProlog orig@(mainex :@ nltags) = pretty $ plain orig
teToProlog orig@(TKey tkey) = pretty $ plain orig
teToProlog (All termexprs) = "TODO All"
teToProlog orig@(Any termexprs) = nest 8 $ vcat $ punctuate (semi <> PP.space) (teToProlog <$> termexprs)
teToProlog (And termexprs) = "TODO And"
teToProlog orig@(BinOp (x :@ _) Cons (y :@ _)) = pretty (x ++ "_" ++ y)
teToProlog orig@(BinOp te1 Cons te2) = ("compl") <> parencomma [teToProlog te1, teToProlog te2]
teToProlog orig@(BinOp (Any lhss) co rhs) = teToProlog (Any ((\lhs -> (BinOp lhs co rhs)) <$> lhss)) -- compound or cons
teToProlog orig@(BinOp lhs co (Any rhss)) = teToProlog (Any ((\rhs -> (BinOp lhs co rhs)) <$> rhss))
teToProlog orig@(BinOp (All lhss) co rhs) = teToProlog (All ((\lhs -> (BinOp lhs co rhs)) <$> lhss)) -- compound or cons
teToProlog orig@(BinOp lhs co (All rhss)) = teToProlog (All ((\rhs -> (BinOp lhs co rhs)) <$> rhss))
teToProlog orig@(BinOp (BinOp tk1 (TE2 ("'s" :@ [])) tk2) (TE2 ("of" :@ [])) te3) = teToProlog tk2 <> "_of" <> parencomma [teToProlog tk1, teToProlog te3]
teToProlog orig@(BinOp te1 Compound te2) = teToProlog te1 <> parencomma [teToProlog te2]
teToProlog orig@(BinOp te1 (TE2 ("'s" :@ [])) te3) = "of" <> parencomma [teToProlog te3, teToProlog te1]
teToProlog orig@(BinOp te1 (TE2 (prep :@ [])) te3) = pretty prep <> parencomma [teToProlog te1, teToProlog te3]
plain :: TermExpr -> String
plain (mainex :@ nltags) = tr_ mainex
plain (TKey tkey) = tr_ tkey
tr_ = tr " " "_"
tr " abc " " 123 " " a cow " - > " 1 3ow "
tr x y cs = [ maybe c (y !!) eI | c <- cs, let eI = elemIndex c x ]
stmToL4 :: Stm -> String
stmToL4 (Section te) = unlines [ unwords [ "SECTION", teToL4 toplevel te ] ]
stmToL4 (DRule rn p d a w) = unlines [ unwords [ " RULE", teToL4 toplevel rn ]
, unwords [ " PARTY", teToL4 toplevel p ]
, unwords [ " " ++ dshow d, teToL4 toplevel a ]
, unwords [ " " ++ maybe "-- EVER"
(("WHEN " ++) . teToL4 toplevel) w ]
]
rule_34_1(party(LegalPractitioner ) , , accept(ExecA ) ) : - assocWith(ExecA , Business ) ,
-- detracts_from
toplevel = Ctx []
data Context = Ctx { stack :: [TermExpr] } deriving (Show, Eq)
ppTE ctx orig@(Any termexprs) = "Any " ++ (show $ brackets (hcat $ punctuate (comma) (pretty . (teToL4' ctx orig) <$> termexprs )))
this Context thing really should be a State monad
teToL4 :: Context -> TermExpr -> String
teToL4 ctx (mainex :@ nltags) = mainex
teToL4 ctx (TKey tkey) = tkey
teToL4 ctx (All termexprs) = "TODO All"
teToL4 ctx orig@(Any termexprs) = "TODO Any"
teToL4 ctx (And termexprs) = "TODO And"
teToL4 ctx orig@(BinOp te1 bo2 te3) = show (bo2) ++ "(" ++ teToL4' ctx orig te1 ++ " , " ++ teToL4' ctx orig te3 ++ ")"
teToL4' ctx orig = teToL4 (ctx { stack = orig : stack ctx })
section34 :: [Stm]
section34 = [ (§) ("34" :@ [("en","Thirty Four, part One")
subsequently we speechbubble with English as default
, section34_1 ]
section34_1 :: Stm
section34_1 =
(§§) ("34.1" 💬 "Prohibitions")
("LP" 💬 "Legal Practitioner")
mustNot
(en_ "accept" ⏩ ["execA" 💬 "executive appointment", "Business" 💬 "business"])
(Any [ "Business" 👉 Any [ (en_ "detracts" `_from`) -- [ (1 +),
( 2 * ) ,
( 10 - ) ] < * > [ 400 ] = [ 401 , 800 , -390 ]
] $ (en_ "dignity") `of_` ("profession" 💬 "legal profession")
, "Business" 👉 (en_ "materially interferes with") $
Any [ lp's ("occ" 💬 "primary occupation") `of_` (en_ "practising") `as_` (en_ "lawyer")
, lp's $ en_ "availability to those who may seek" <> lp's (en_ "services as a lawyer")
, en_ "representation" `of_` lp's ( en_ "clients" ) ]
, "Business" 👉 (en_ "is likely to") $ (en_ "unfairly attract business") `in_` (en_ "practice of law")
, "Business" 👉 (en_ "involves") $ ( Any [ ((en_ "sharing") `of_` (lp's (en_ "fees")) `_with`)
, (en_ "payment" `of_` en_ "commission" `_to`) ] <>
Any [ en_ "unauthorised person" ] `for_`
en_ "legal work performed" `by_`
(TKey "LP") )
, "Business" 👉 ("isIn" 💬 "is in") $ ("Schedule1" 💬 "First Schedule")
, "Business" 👉 ("isProhibitedBy" 💬 "is prohibited by") $
Any [ en_ "Act"
, Any [ en_ "these Rules"
, en_ "any other subsidiary legislation made under the Act" ] -- not enough structure?
, And [ en_ "practice directions", en_ "guidance notes", en_ "rulings" ]
<> en_ "issued under section 71(6) of the Act" -- should "under" be a preposition like the others?
, And [ en_ "practice directions", en_ "guidance notes", en_ "rulings" ]
<> en_ "relating" `to_` And [ en_ "professional practice", en_ "etiquette", en_ "conduct", en_ "discipline" ]
<> en_ "issued" `by_` Any [ en_ "Council", en_ "Society" ]
]
]
)
by default , we construct an English term , but this could evolve toward wordnet
(💬) :: String -> String -> TermExpr
infixr 7 💬
ex 💬 tag = ex :@ [("en",tag)]
-- wordnet!
(🔤) :: String -> Integer -> TermExpr
infixr 7 🔤
ex 🔤 tag = ex :@ [("wordnet",show tag)]
(📭) :: TermExpr -> TermExpr -> TermExpr
infix 6 📭
var 📭 typ = BinOp var HasType typ
(📩) :: String -> PrimType -> TermExpr
infix 7 📩
var 📩 val = BinOp (var 💬 var) HasValue (Prim val)
data PrimType
= L4True | L4False
| L4S String
deriving (Show, Eq)
isa = (📭)
infix 6 `isa`
(📪) = typ
typ = "Type" 💬 "Base Type"
bool = "Bool" 💬 "Primitive Type Boolean"
str = "String" 💬 "Primitive Type String"
(§=) = (📬)
(📬) :: TermExpr -> String -> TermExpr
infix 6 📬
obj 📬 t = BinOp obj HasType (t 💬 "User Defined Type")
en_ :: String -> TermExpr
en_ ex = ex :@ [("en",ex)]
nl_ :: String -> TermExpr
nl_ ex = ex :@ []
-- syntactic sugar for a prolog-style Compound term: lhs(r,h,s)
(⏩) :: TermExpr -> [TermExpr] -> TermExpr
infixr 5 ⏩
lhs ⏩ rhs = BinOp lhs Compound (telist2conslist rhs)
telist2conslist :: [TermExpr] -> TermExpr
telist2conslist (te:[]) = te
telist2conslist (t:tes) = BinOp t Cons (telist2conslist tes)
StringValue - > " hasAttr " Compound StringValue
hasAttr :: TermExpr -> TermExpr
hasAttr te = UnOp HasAttr te
-- executive appointment IS associatedWith Something
-- becomes, in prolog, associatedWith(ExecutiveAppointment, Something)
-- which is basically a bit of a flip and rearrangement of the above
(👉) :: Key -> TermExpr -> TermExpr -> TermExpr
infixr 5 👉
lhs 👉 compound = \rhs -> BinOp compound Compound (telist2conslist [TKey lhs, rhs])
-- section marker. this always has to be wrapped in () because it's a section?
(§) :: TermExpr -> Stm
(§) = Section
-- deontic rule -- party x must y
type MkDRule = TermExpr -> TermExpr -> Deontic -> TermExpr -> TermExpr -> Stm
(§§) :: MkDRule
(§§) a b c d e = DRule a b c d (Just e)
-- constitutive rule
DEFINE x ISA Type
WITH attribute ISA String
attribute2 ISA Boolean
WITH attribute ISA String
attribute2 ISA Boolean
-}
type MkCRule = TermExpr -> [TermExpr] -> Stm
(§=§) :: MkCRule
(§=§) item body = CRule item body Nothing
-- attribute constructors
type MkDef = TermExpr -> TermExpr -> TermExpr
(§.=§) :: MkDef
(§.=§) a b = BinOp a HasType b
(§.=) :: MkDef
(§.=) a b = BinOp a HasValue b
instance Semigroup TermExpr where (<>) x y = BinOp x Cons y
_'s :: Key -> TermExpr -> TermExpr
infixr 6 `_'s`
x `_'s` y = TKey x `possessive` y
-- we hardcode "LP" to mean Legal Practitioner
lp's = _'s "LP"
mustNot = DShant
mayNot = DShant
must = DMust
may = DMay
dshow DShant = "SHANT"
dshow DMust = "MUST"
dshow DMay = "MAY"
binop op x y = BinOp x (TE2 (op :@ [])) y
this is a sign we need to learn
infixr 6 `of_`; of_ = binop "of"; infixr 5 `_of`; _of x = x <> (nl_ "of")
infixr 6 `to_`; to_ = binop "to"; infixr 5 `_to`; _to x = x <> (nl_ "to")
infixr 6 `as_`; as_ = binop "as"; infixr 5 `_as`; _as x = x <> (nl_ "as")
infixr 6 `in_`; in_ = binop "in"; infixr 5 `_in`; _in x = x <> (nl_ "in")
infixr 6 `is_`; is_ = binop "is"; infixr 5 `_is`; _is x = x <> (nl_ "is")
infixr 6 `by_`; by_ = binop "by"; infixr 5 `_by`; _by x = x <> (nl_ "by")
infixr 6 `for_`; for_ = binop "for"; infixr 5 `_for`; _for x = x <> (nl_ "for")
infixr 6 `with_`; with_ = binop "with"; infixr 5 `_with`; _with x = x <> (nl_ "with")
infixr 6 `from_`; from_ = binop "from"; infixr 5 `_from`; _from x = x <> (nl_ "from")
infixr 6 `possessive`
possessive = binop "'s"
superSimple1 :: [Stm]
superSimple1 =
[ (§=§) ("Business" 🔤 12345 📭 typ)
[ "is_operating" 🔤 23456 📭 bool
, "bus_name" 💬 "Business Name" 📭 str
]
, (§=§) ("megaCorp" 💬 "Mega Corporation" 📬 "Business")
[ "is_operating" 📩 L4True
, "bus_name" 📩 L4S "Mega"
]
]
data Target = To_TS deriving (Show, Eq)
-- we'll use -1.7.0/docs/Prettyprinter.html
-- interface definition
stm2ts :: Stm -> Doc ann
stm2ts (CRule (BinOp (te1 :@ _) HasType ("Type" :@ _)) crb crmw) =
vsep [ nest 2 (vsep (hsep ["interface", pretty te1, lbrace]
:
(attrdef To_TS <$> crb)))
, rbrace ]
-- instance definition
stm2ts (CRule (BinOp (te1 :@ _) HasType (te2 :@ _)) crb crmw) =
vsep [ nest 2 (vsep (hsep ["let", pretty te1, colon, pretty te2, equals, lbrace]
: -- alternatively, use encloseSep, but that does a hanging indent.
(punctuate comma (attrdef To_TS <$> crb))))
, rbrace ]
-- attribute type definition inside interface
attrdef :: Target -> TermExpr -> Doc ann
attrdef To_TS (BinOp (te1 :@ _) HasType (te2 :@_)) =
pretty te1 <+> colon <+> pretty (typecast To_TS te2) <> semi
-- attribute value definition inside instance
attrdef To_TS (BinOp (te1 :@ _) HasValue te2) =
pretty te1 <+> colon <+> pretty (showTSval te2)
-- attribute catch-all
attrdef target y = hsep (pretty <$> [ "// attrdef unimplemented: ", show target, show y])
showTSval (Prim L4True) = "true"
showTSval (Prim L4False) = "false"
showTSval (Prim (L4S str)) = "\"" ++ str ++ "\"" -- TODO: need to properly stringify by escaping internal " etc
showTSval x = show x
printStms To_TS stms = mapM_ (putStrLn . show . stm2ts) stms
typecast To_TS "Bool" = "boolean"
typecast To_TS "String" = "string"
typecast target y = y
someFunc :: String -> IO ()
someFunc myinput = do
let stdinAST = case parse parseL4 "parsing L4 toplevel" (pack myinput) of
Left someError -> error $ errorBundlePretty someError
Right rhs -> rhs
(opts,runCmd) <-
simpleOptions "v0.01" "lpapcr34" "an early L4 prototype for section 34" (pure ()) $
do addSubCommands "pretty" "pretty-print" (
do addCommand "ast" "the manual AST" (const (pPrint section34)) (pure ())
addCommand "baby" "the baby AST" (const (pPrint superSimple1)) (pure ())
addCommand "babyts" "the baby AST as typescript" (const (printStms To_TS superSimple1)) (pure ())
addCommand "stdin" "parsed STDIN" (const (pPrint stdinAST)) (pure ())
)
-- i think there is a bug in optparse-simple, honestly
addCommand "prolog" "output to prolog" (const (mapM_ (putStrLn . show . stmToProlog) section34)) (pure ())
addCommand "plain" "output to plain" (const (mapM_ (putStrLn . stmToPlain) section34)) (pure ())
runCmd
| null | https://raw.githubusercontent.com/smucclaw/dsl/9ee9dd7160c05b773ff20754ba8bbdccf37a5380/caseStudies/LPAPCR34/src/Lib.hs | haskell | # LANGUAGE OverloadedStrings #
deontic rule
"potato"
and -- each element must evaluate true
only one element is needed to be true
set union! inclusive "and" is not a logical "and"! more of an "or"
nil
ideally spaceless but can contain spaces. Maybe a Mk to s/ /_/g
a stanza
RULE PARTY X MUST Y
DEFINE X IS BLAH
:en:"Some String"
sooner or later we will need to think about -recursion
compound or cons
compound or cons
detracts_from
[ (1 +),
not enough structure?
should "under" be a preposition like the others?
wordnet!
syntactic sugar for a prolog-style Compound term: lhs(r,h,s)
executive appointment IS associatedWith Something
becomes, in prolog, associatedWith(ExecutiveAppointment, Something)
which is basically a bit of a flip and rearrangement of the above
section marker. this always has to be wrapped in () because it's a section?
deontic rule -- party x must y
constitutive rule
attribute constructors
we hardcode "LP" to mean Legal Practitioner
we'll use -1.7.0/docs/Prettyprinter.html
interface definition
instance definition
alternatively, use encloseSep, but that does a hanging indent.
attribute type definition inside interface
attribute value definition inside instance
attribute catch-all
TODO: need to properly stringify by escaping internal " etc
i think there is a bug in optparse-simple, honestly | # LANGUAGE PostfixOperators #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DuplicateRecordFields #
module Lib where
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Data.Text (Text, pack, unpack)
import qualified Data.Text.IO as TIO
import Prettyprinter hiding (space)
import qualified Prettyprinter as PP
import Data.Void
import Data.List (nub, permutations, sort, sortOn, intercalate, elemIndex)
import Data.Char (toLower)
import Control.Monad (forM_)
import qualified Data.Map.Lazy as Map
import Text.Pretty.Simple (pPrint, pShow)
import Options.Applicative.Simple (simpleOptions, addCommand, addSubCommands)
import Language.Prolog
type Parser = Parsec Void Text
sc :: Parser ()
sc = L.space space1 (L.skipLineComment "//") (L.skipBlockComment "/*" "*/")
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
stringLiteral = char '"' >> manyTill L.charLiteral (char '"')
first TermExpr should always be an NL expression (: @ )
, party :: TermExpr
, dmodal :: Deontic
, action :: TermExpr
, when :: Maybe TermExpr
}
| CRule { item :: TermExpr
, body :: [TermExpr]
, when :: Maybe TermExpr
}
deriving (Show, Eq)
infix constructor for NL : " potato " : @ [ ( " en","Solanum Tuberosum " ) ]
ace " of " bass , useful when either lhs or rhs term is itself an All / Any list
| UnOp UnOp TermExpr
| Prim PrimType
deriving (Show, Eq)
data UnOp = HasAttr
deriving (Show, Eq)
data BinOp = Cons
| Compound
| HasType
| HasValue
| TE2 TermExpr
deriving (Show, Eq)
type NLTag = (Key,String)
data Deontic = DMust | DMay | DShant deriving (Show, Eq)
an L4 document is a list of stanzas
parseL4 :: Parser [Stm]
parseL4 = do
stm <- parseStm
rhs <- parseL4
eof
return (stm : rhs)
parseStm :: Parser Stm
parseStm = do
many newline
stm <- choice [ try (Section <$> (lexeme "SECTION" *> parseNLStr))
, try parseDeonticRule
, try parseConstitutiveRule
]
return stm
parseDeonticRule :: Parser Stm
parseDeonticRule = do
ruleName <- space *> lexeme "RULE" *> parseNLStr <* lexeme "ISA" <* lexeme "DeonticRule" <* some newline
party <- space *> lexeme "PARTY" *> parseNLStr <* some newline
dmodal <- space *> lexeme (DMust <$ "MUST" <|>
DMay <$ "MAY" <|>
DShant <$ "SHANT")
action <- lexeme parseTermExpr <* some newline
when <- optional (space *> lexeme "WHEN" *> parseTermExpr)
return (DRule ruleName party dmodal action when)
parseConstitutiveRule :: Parser Stm
parseConstitutiveRule = do
item <- space *> lexeme "DEFINE" *> parseNLStr <* some newline
body <- many (lexeme parseTermExpr <* some newline)
when <- optional (space *> lexeme "WHEN" *> parseTermExpr)
return (CRule item body when)
SomeString : en:"Some String "
parseNLStr :: Parser TermExpr
parseNLStr = do
exPart <- lexeme $ some (alphaNumChar <|> char '.')
tagsPart <- many (lexeme parseTag)
return $ exPart :@ tagsPart
parseTag :: Parser NLTag
parseTag = do
lhs <- between (char ':') (char ':') (some alphaNumChar)
rhs <- stringLiteral
return (lhs, rhs)
parseTermExpr :: Parser TermExpr
parseTermExpr = return $ "burf" :@ []
stmToPlain :: Stm -> String
stmToPlain (Section te) = plain te
stmToProlog :: Stm -> Doc ann
stmToProlog (Section te) = "%% " <> pretty (stmToL4 (Section te))
stmToProlog (DRule rn p d a w) =
let headP = "drule" <> parencomma [ dquotes (pretty $ plain rn)
, "SubRuleName"
, teToProlog p
, pretty ((toLower <$> dshow d) :: String)
, teToProlog a ]
varargs = teToProlog p : unwrapP a
in vsep ( [ if null w
then headP <> pretty '.'
else nest 4 (headP <+> ":-" <+> ("subRule" <> parencomma ("SubRuleName" : varargs) <> pretty '.') )
] ++ asPrologSubrules w varargs )
asPrologSubrules :: Maybe TermExpr -> [Doc ann] -> [Doc ann]
asPrologSubrules Nothing _ = [emptyDoc]
asPrologSubrules (Just (Any termexprs)) varargs = asPrologSubrule varargs <$> (zip ['A'..] termexprs)
asPrologSubrule :: [Doc ann] -> (Char, TermExpr) -> Doc ann
asPrologSubrule varargs (ruleNum, te) =
hang 5
("\nsubRule" <> parencomma ([ pretty ("subRule_"++[ruleNum]) ] ++ varargs) <+> (":-") <> line <> (teToProlog te) <> pretty '.')
unwrapP :: TermExpr -> [Doc ann]
unwrapP (mainex :@ nltags) = [pretty $ tr_ mainex]
unwrapP (TKey tkey) = [pretty $ tr_ tkey]
unwrapP (All termexprs) = teToProlog <$> termexprs
unwrapP orig@(Any termexprs) = teToProlog <$> termexprs
unwrapP (And termexprs) = teToProlog <$> termexprs
unwrapP orig@(BinOp te1 bo2 te3) = [teToProlog te1, teToProlog te3]
parencomma docs = parens (hsep $ punctuate (pretty ',') docs)
teToProlog :: TermExpr -> Doc ann
teToProlog orig@(mainex :@ nltags) = pretty $ plain orig
teToProlog orig@(TKey tkey) = pretty $ plain orig
teToProlog (All termexprs) = "TODO All"
teToProlog orig@(Any termexprs) = nest 8 $ vcat $ punctuate (semi <> PP.space) (teToProlog <$> termexprs)
teToProlog (And termexprs) = "TODO And"
teToProlog orig@(BinOp (x :@ _) Cons (y :@ _)) = pretty (x ++ "_" ++ y)
teToProlog orig@(BinOp te1 Cons te2) = ("compl") <> parencomma [teToProlog te1, teToProlog te2]
teToProlog orig@(BinOp lhs co (Any rhss)) = teToProlog (Any ((\rhs -> (BinOp lhs co rhs)) <$> rhss))
teToProlog orig@(BinOp lhs co (All rhss)) = teToProlog (All ((\rhs -> (BinOp lhs co rhs)) <$> rhss))
teToProlog orig@(BinOp (BinOp tk1 (TE2 ("'s" :@ [])) tk2) (TE2 ("of" :@ [])) te3) = teToProlog tk2 <> "_of" <> parencomma [teToProlog tk1, teToProlog te3]
teToProlog orig@(BinOp te1 Compound te2) = teToProlog te1 <> parencomma [teToProlog te2]
teToProlog orig@(BinOp te1 (TE2 ("'s" :@ [])) te3) = "of" <> parencomma [teToProlog te3, teToProlog te1]
teToProlog orig@(BinOp te1 (TE2 (prep :@ [])) te3) = pretty prep <> parencomma [teToProlog te1, teToProlog te3]
plain :: TermExpr -> String
plain (mainex :@ nltags) = tr_ mainex
plain (TKey tkey) = tr_ tkey
tr_ = tr " " "_"
tr " abc " " 123 " " a cow " - > " 1 3ow "
tr x y cs = [ maybe c (y !!) eI | c <- cs, let eI = elemIndex c x ]
stmToL4 :: Stm -> String
stmToL4 (Section te) = unlines [ unwords [ "SECTION", teToL4 toplevel te ] ]
stmToL4 (DRule rn p d a w) = unlines [ unwords [ " RULE", teToL4 toplevel rn ]
, unwords [ " PARTY", teToL4 toplevel p ]
, unwords [ " " ++ dshow d, teToL4 toplevel a ]
, unwords [ " " ++ maybe "-- EVER"
(("WHEN " ++) . teToL4 toplevel) w ]
]
rule_34_1(party(LegalPractitioner ) , , accept(ExecA ) ) : - assocWith(ExecA , Business ) ,
toplevel = Ctx []
data Context = Ctx { stack :: [TermExpr] } deriving (Show, Eq)
ppTE ctx orig@(Any termexprs) = "Any " ++ (show $ brackets (hcat $ punctuate (comma) (pretty . (teToL4' ctx orig) <$> termexprs )))
this Context thing really should be a State monad
teToL4 :: Context -> TermExpr -> String
teToL4 ctx (mainex :@ nltags) = mainex
teToL4 ctx (TKey tkey) = tkey
teToL4 ctx (All termexprs) = "TODO All"
teToL4 ctx orig@(Any termexprs) = "TODO Any"
teToL4 ctx (And termexprs) = "TODO And"
teToL4 ctx orig@(BinOp te1 bo2 te3) = show (bo2) ++ "(" ++ teToL4' ctx orig te1 ++ " , " ++ teToL4' ctx orig te3 ++ ")"
teToL4' ctx orig = teToL4 (ctx { stack = orig : stack ctx })
section34 :: [Stm]
section34 = [ (§) ("34" :@ [("en","Thirty Four, part One")
subsequently we speechbubble with English as default
, section34_1 ]
section34_1 :: Stm
section34_1 =
(§§) ("34.1" 💬 "Prohibitions")
("LP" 💬 "Legal Practitioner")
mustNot
(en_ "accept" ⏩ ["execA" 💬 "executive appointment", "Business" 💬 "business"])
( 2 * ) ,
( 10 - ) ] < * > [ 400 ] = [ 401 , 800 , -390 ]
] $ (en_ "dignity") `of_` ("profession" 💬 "legal profession")
, "Business" 👉 (en_ "materially interferes with") $
Any [ lp's ("occ" 💬 "primary occupation") `of_` (en_ "practising") `as_` (en_ "lawyer")
, lp's $ en_ "availability to those who may seek" <> lp's (en_ "services as a lawyer")
, en_ "representation" `of_` lp's ( en_ "clients" ) ]
, "Business" 👉 (en_ "is likely to") $ (en_ "unfairly attract business") `in_` (en_ "practice of law")
, "Business" 👉 (en_ "involves") $ ( Any [ ((en_ "sharing") `of_` (lp's (en_ "fees")) `_with`)
, (en_ "payment" `of_` en_ "commission" `_to`) ] <>
Any [ en_ "unauthorised person" ] `for_`
en_ "legal work performed" `by_`
(TKey "LP") )
, "Business" 👉 ("isIn" 💬 "is in") $ ("Schedule1" 💬 "First Schedule")
, "Business" 👉 ("isProhibitedBy" 💬 "is prohibited by") $
Any [ en_ "Act"
, Any [ en_ "these Rules"
, And [ en_ "practice directions", en_ "guidance notes", en_ "rulings" ]
, And [ en_ "practice directions", en_ "guidance notes", en_ "rulings" ]
<> en_ "relating" `to_` And [ en_ "professional practice", en_ "etiquette", en_ "conduct", en_ "discipline" ]
<> en_ "issued" `by_` Any [ en_ "Council", en_ "Society" ]
]
]
)
by default , we construct an English term , but this could evolve toward wordnet
(💬) :: String -> String -> TermExpr
infixr 7 💬
ex 💬 tag = ex :@ [("en",tag)]
(🔤) :: String -> Integer -> TermExpr
infixr 7 🔤
ex 🔤 tag = ex :@ [("wordnet",show tag)]
(📭) :: TermExpr -> TermExpr -> TermExpr
infix 6 📭
var 📭 typ = BinOp var HasType typ
(📩) :: String -> PrimType -> TermExpr
infix 7 📩
var 📩 val = BinOp (var 💬 var) HasValue (Prim val)
data PrimType
= L4True | L4False
| L4S String
deriving (Show, Eq)
isa = (📭)
infix 6 `isa`
(📪) = typ
typ = "Type" 💬 "Base Type"
bool = "Bool" 💬 "Primitive Type Boolean"
str = "String" 💬 "Primitive Type String"
(§=) = (📬)
(📬) :: TermExpr -> String -> TermExpr
infix 6 📬
obj 📬 t = BinOp obj HasType (t 💬 "User Defined Type")
en_ :: String -> TermExpr
en_ ex = ex :@ [("en",ex)]
nl_ :: String -> TermExpr
nl_ ex = ex :@ []
(⏩) :: TermExpr -> [TermExpr] -> TermExpr
infixr 5 ⏩
lhs ⏩ rhs = BinOp lhs Compound (telist2conslist rhs)
telist2conslist :: [TermExpr] -> TermExpr
telist2conslist (te:[]) = te
telist2conslist (t:tes) = BinOp t Cons (telist2conslist tes)
StringValue - > " hasAttr " Compound StringValue
hasAttr :: TermExpr -> TermExpr
hasAttr te = UnOp HasAttr te
(👉) :: Key -> TermExpr -> TermExpr -> TermExpr
infixr 5 👉
lhs 👉 compound = \rhs -> BinOp compound Compound (telist2conslist [TKey lhs, rhs])
(§) :: TermExpr -> Stm
(§) = Section
type MkDRule = TermExpr -> TermExpr -> Deontic -> TermExpr -> TermExpr -> Stm
(§§) :: MkDRule
(§§) a b c d e = DRule a b c d (Just e)
DEFINE x ISA Type
WITH attribute ISA String
attribute2 ISA Boolean
WITH attribute ISA String
attribute2 ISA Boolean
-}
type MkCRule = TermExpr -> [TermExpr] -> Stm
(§=§) :: MkCRule
(§=§) item body = CRule item body Nothing
type MkDef = TermExpr -> TermExpr -> TermExpr
(§.=§) :: MkDef
(§.=§) a b = BinOp a HasType b
(§.=) :: MkDef
(§.=) a b = BinOp a HasValue b
instance Semigroup TermExpr where (<>) x y = BinOp x Cons y
_'s :: Key -> TermExpr -> TermExpr
infixr 6 `_'s`
x `_'s` y = TKey x `possessive` y
lp's = _'s "LP"
mustNot = DShant
mayNot = DShant
must = DMust
may = DMay
dshow DShant = "SHANT"
dshow DMust = "MUST"
dshow DMay = "MAY"
binop op x y = BinOp x (TE2 (op :@ [])) y
this is a sign we need to learn
infixr 6 `of_`; of_ = binop "of"; infixr 5 `_of`; _of x = x <> (nl_ "of")
infixr 6 `to_`; to_ = binop "to"; infixr 5 `_to`; _to x = x <> (nl_ "to")
infixr 6 `as_`; as_ = binop "as"; infixr 5 `_as`; _as x = x <> (nl_ "as")
infixr 6 `in_`; in_ = binop "in"; infixr 5 `_in`; _in x = x <> (nl_ "in")
infixr 6 `is_`; is_ = binop "is"; infixr 5 `_is`; _is x = x <> (nl_ "is")
infixr 6 `by_`; by_ = binop "by"; infixr 5 `_by`; _by x = x <> (nl_ "by")
infixr 6 `for_`; for_ = binop "for"; infixr 5 `_for`; _for x = x <> (nl_ "for")
infixr 6 `with_`; with_ = binop "with"; infixr 5 `_with`; _with x = x <> (nl_ "with")
infixr 6 `from_`; from_ = binop "from"; infixr 5 `_from`; _from x = x <> (nl_ "from")
infixr 6 `possessive`
possessive = binop "'s"
superSimple1 :: [Stm]
superSimple1 =
[ (§=§) ("Business" 🔤 12345 📭 typ)
[ "is_operating" 🔤 23456 📭 bool
, "bus_name" 💬 "Business Name" 📭 str
]
, (§=§) ("megaCorp" 💬 "Mega Corporation" 📬 "Business")
[ "is_operating" 📩 L4True
, "bus_name" 📩 L4S "Mega"
]
]
data Target = To_TS deriving (Show, Eq)
stm2ts :: Stm -> Doc ann
stm2ts (CRule (BinOp (te1 :@ _) HasType ("Type" :@ _)) crb crmw) =
vsep [ nest 2 (vsep (hsep ["interface", pretty te1, lbrace]
:
(attrdef To_TS <$> crb)))
, rbrace ]
stm2ts (CRule (BinOp (te1 :@ _) HasType (te2 :@ _)) crb crmw) =
vsep [ nest 2 (vsep (hsep ["let", pretty te1, colon, pretty te2, equals, lbrace]
(punctuate comma (attrdef To_TS <$> crb))))
, rbrace ]
attrdef :: Target -> TermExpr -> Doc ann
attrdef To_TS (BinOp (te1 :@ _) HasType (te2 :@_)) =
pretty te1 <+> colon <+> pretty (typecast To_TS te2) <> semi
attrdef To_TS (BinOp (te1 :@ _) HasValue te2) =
pretty te1 <+> colon <+> pretty (showTSval te2)
attrdef target y = hsep (pretty <$> [ "// attrdef unimplemented: ", show target, show y])
showTSval (Prim L4True) = "true"
showTSval (Prim L4False) = "false"
showTSval x = show x
printStms To_TS stms = mapM_ (putStrLn . show . stm2ts) stms
typecast To_TS "Bool" = "boolean"
typecast To_TS "String" = "string"
typecast target y = y
someFunc :: String -> IO ()
someFunc myinput = do
let stdinAST = case parse parseL4 "parsing L4 toplevel" (pack myinput) of
Left someError -> error $ errorBundlePretty someError
Right rhs -> rhs
(opts,runCmd) <-
simpleOptions "v0.01" "lpapcr34" "an early L4 prototype for section 34" (pure ()) $
do addSubCommands "pretty" "pretty-print" (
do addCommand "ast" "the manual AST" (const (pPrint section34)) (pure ())
addCommand "baby" "the baby AST" (const (pPrint superSimple1)) (pure ())
addCommand "babyts" "the baby AST as typescript" (const (printStms To_TS superSimple1)) (pure ())
addCommand "stdin" "parsed STDIN" (const (pPrint stdinAST)) (pure ())
)
addCommand "prolog" "output to prolog" (const (mapM_ (putStrLn . show . stmToProlog) section34)) (pure ())
addCommand "plain" "output to plain" (const (mapM_ (putStrLn . stmToPlain) section34)) (pure ())
runCmd
|
529cfccd803a3b3635d4d177a2f22878d93e3640bcd1800a1ddf62e8487f7a43 | bitc/omegagb | Display.hs | OmegaGB Copyright 2007 Bit
This program is distributed under the terms of the GNU General Public License
-----------------------------------------------------------------------------
-- |
-- Module : Display
Copyright : ( c ) Bit Connor 2007 < >
-- License : GPL
-- Maintainer :
-- Stability : in-progress
--
-- OmegaGB
-- Game Boy Emulator
--
-- This module defines the Display type that represents the Game Boy's LCD
display . The Game Boy LCD display has a resolution of 144x160 and 4
-- colors,
--
-----------------------------------------------------------------------------
module Display where
import Data.Array.Unboxed
import Data.Word
type Display = UArray (Int, Int) Word8
blankDisplay :: Display
blankDisplay = array ((0, 0), (143, 159)) (map (\i -> (i, 0)) (range ((0, 0), (143, 159))))
| null | https://raw.githubusercontent.com/bitc/omegagb/5ab9c3a22f5fc283906b8af53717d81fef96db7f/src/Display.hs | haskell | ---------------------------------------------------------------------------
|
Module : Display
License : GPL
Maintainer :
Stability : in-progress
OmegaGB
Game Boy Emulator
This module defines the Display type that represents the Game Boy's LCD
colors,
--------------------------------------------------------------------------- | OmegaGB Copyright 2007 Bit
This program is distributed under the terms of the GNU General Public License
Copyright : ( c ) Bit Connor 2007 < >
display . The Game Boy LCD display has a resolution of 144x160 and 4
module Display where
import Data.Array.Unboxed
import Data.Word
type Display = UArray (Int, Int) Word8
blankDisplay :: Display
blankDisplay = array ((0, 0), (143, 159)) (map (\i -> (i, 0)) (range ((0, 0), (143, 159))))
|
e78f2ad2a8f2504bcf5ee3cb6c581ad219673e7416def9c3b55ee295cdd10da0 | dnlkrgr/hsreduce | TypeFamilies.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE InstanceSigs #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
import GHC.Generics
import GHC.TypeLits
arst :: F Int Char -> String
arst = undefined
brst :: G Int Char -> String
brst = undefined
type family F a b where
F a b = a
type family G a b where
G a b = String
type family MaybeAdd b where
MaybeAdd b = 'Just (b)
type family AnotherLookupParam (p :: Nat) :: Maybe Nat where
AnotherLookupParam n = MaybeAdd 1
type family LookupParam (p :: Nat) :: Maybe Nat where
LookupParam n = IfEq n ('Just 0) ('Just 1)
type family IfEq (b :: k) (t :: l) (f :: l) :: l where
IfEq a t _ = t
main = undefined
| null | https://raw.githubusercontent.com/dnlkrgr/hsreduce/8f66fdee036f8639053067572b55d9a64359d22c/test-cases/regressions/TypeFamilies.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE InstanceSigs #
# LANGUAGE PolyKinds #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
import GHC.Generics
import GHC.TypeLits
arst :: F Int Char -> String
arst = undefined
brst :: G Int Char -> String
brst = undefined
type family F a b where
F a b = a
type family G a b where
G a b = String
type family MaybeAdd b where
MaybeAdd b = 'Just (b)
type family AnotherLookupParam (p :: Nat) :: Maybe Nat where
AnotherLookupParam n = MaybeAdd 1
type family LookupParam (p :: Nat) :: Maybe Nat where
LookupParam n = IfEq n ('Just 0) ('Just 1)
type family IfEq (b :: k) (t :: l) (f :: l) :: l where
IfEq a t _ = t
main = undefined
|
30f6bd1445bc24827db8fb645242b8e7ed3dad5aae19e9057d67455e871ceea5 | fmi-lab/fp-elective-2017 | reverse-digits.scm | (require rackunit rackunit/text-ui)
Докато изчерпваме цифрите от number , ги слагаме в reversed
(define (reverse-digits n)
(define (helper number reversed)
Изчерпали сме напълно number
reversed ; Съответно reversed e напълнен и готов
(helper (quotient number 10)
(+ (* reversed 10)
(remainder number 10)))))
(helper n 0))
(define reverse-digits-tests
(test-suite
"Tests for reverse-digits"
(check = (reverse-digits 3) 3)
(check = (reverse-digits 12) 21)
(check = (reverse-digits 42) 24)
(check = (reverse-digits 666) 666)
(check = (reverse-digits 1337) 7331)
(check = (reverse-digits 65510) 1556)
(check = (reverse-digits 1234567) 7654321)
(check = (reverse-digits 8833443388) 8833443388)
(check = (reverse-digits 100000000000) 1)))
(run-tests reverse-digits-tests)
| null | https://raw.githubusercontent.com/fmi-lab/fp-elective-2017/e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3/exercises/02/reverse-digits.scm | scheme | Съответно reversed e напълнен и готов | (require rackunit rackunit/text-ui)
Докато изчерпваме цифрите от number , ги слагаме в reversed
(define (reverse-digits n)
(define (helper number reversed)
Изчерпали сме напълно number
(helper (quotient number 10)
(+ (* reversed 10)
(remainder number 10)))))
(helper n 0))
(define reverse-digits-tests
(test-suite
"Tests for reverse-digits"
(check = (reverse-digits 3) 3)
(check = (reverse-digits 12) 21)
(check = (reverse-digits 42) 24)
(check = (reverse-digits 666) 666)
(check = (reverse-digits 1337) 7331)
(check = (reverse-digits 65510) 1556)
(check = (reverse-digits 1234567) 7654321)
(check = (reverse-digits 8833443388) 8833443388)
(check = (reverse-digits 100000000000) 1)))
(run-tests reverse-digits-tests)
|
1cf4641ec7a6a796e27019b0214f20967971bbc2033b67a1d4f4952b1ee2ca16 | dbuenzli/fmt | styled_perf_bug.ml | let n = 10000
let () =
while true do
let t0 = Unix.gettimeofday () in
for _i = 1 to n do
ignore @@ Fmt.str "Hello %a" Fmt.string "world"
done;
let t1 = Unix.gettimeofday () in
Printf.printf "Formatted %.0f messages/second\n%!" (float n /. (t1 -. t0))
done
| null | https://raw.githubusercontent.com/dbuenzli/fmt/7bb974aafa62ffb97304a34a06cfc1d588e19ea4/test/styled_perf_bug.ml | ocaml | let n = 10000
let () =
while true do
let t0 = Unix.gettimeofday () in
for _i = 1 to n do
ignore @@ Fmt.str "Hello %a" Fmt.string "world"
done;
let t1 = Unix.gettimeofday () in
Printf.printf "Formatted %.0f messages/second\n%!" (float n /. (t1 -. t0))
done
| |
660d4c176e94cf8d4d105ff439b7af646598d80993bc5f1a05d7926521219bf0 | Verites/verigraph | HSpecTests.hs | -- file test/Spec.hs
# OPTIONS_GHC -F - discover -optF --module - name = HSpecTests #
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/tests/HSpecTests.hs | haskell | file test/Spec.hs
module - name = HSpecTests # | |
2a33d950c91718938c840e18c24690d05bee9f4233e3b88f7b49c958d79600e5 | bgusach/exercises-htdp2e | ex-290.rkt | #lang htdp/isl+
(require test-engine/racket-tests)
(require 2htdp/image)
# # # Data Definitions
# # # Functions
; [A] [List-of A] [List-of A] -> [List-of A]
(check-expect (append-from-fold '(1) '()) '(1))
(check-expect (append-from-fold '(1 2) '(3)) '(1 2 3))
(define (append-from-fold a b)
(foldr cons b a)
)
; Q: What happens if you replace foldr with foldl?
A : The result list contains the elements of the first list
in reversed order , and then the elements of the second list .
; See function test-append-from-foldl
; [A] [List-of A] [List-of A] -> [List-of A]
(check-expect (test-append-from-foldl '(1 2) '(3)) '(2 1 3))
(define (test-append-from-foldl a b)
(foldl cons b a)
)
; [List-of Number] -> Number
; Returns the sum of all numbers in the list
(check-expect (sum '(1 2 3 4)) 10)
(define (sum lon)
(foldr + 0 lon)
; NOTE: foldl works too. Sum is commutative
)
[ NEList - of Number ] - > Number
; Returns the product of all numbers in the list
(check-expect (product '(1 2 3 4)) 24)
(define (product lon)
(foldl * 1 lon)
; NOTE: foldr works as well. Product is commutative
)
(define sq1 (square 100 "solid" "blue"))
(define sq2 (square 100 "solid" "yellow"))
; [List-of Image] -> Image
Composes horizontally from left to right the list of images
(check-expect (compose-h '()) empty-image)
(check-expect (compose-h (list sq1 sq2)) (beside sq1 sq2))
(define (compose-h loi)
(foldl
(λ (img acc) (beside acc img))
empty-image
loi
))
; Q: Can you use the other fold function?
; A: Yes, but the images are merged in the reversed order
; [List-of Image] -> Image
Stacks a list of image . The first one of the list is on the
; bottom of the stack.
(check-expect (compose-v '()) empty-image)
(check-expect (compose-v (list sq1 sq2)) (above sq2 sq1))
(define (compose-v loi)
(foldl above empty-image loi)
)
(test)
| null | https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/3-abstraction/ex-290.rkt | racket | [A] [List-of A] [List-of A] -> [List-of A]
Q: What happens if you replace foldr with foldl?
See function test-append-from-foldl
[A] [List-of A] [List-of A] -> [List-of A]
[List-of Number] -> Number
Returns the sum of all numbers in the list
NOTE: foldl works too. Sum is commutative
Returns the product of all numbers in the list
NOTE: foldr works as well. Product is commutative
[List-of Image] -> Image
Q: Can you use the other fold function?
A: Yes, but the images are merged in the reversed order
[List-of Image] -> Image
bottom of the stack. | #lang htdp/isl+
(require test-engine/racket-tests)
(require 2htdp/image)
# # # Data Definitions
# # # Functions
(check-expect (append-from-fold '(1) '()) '(1))
(check-expect (append-from-fold '(1 2) '(3)) '(1 2 3))
(define (append-from-fold a b)
(foldr cons b a)
)
A : The result list contains the elements of the first list
in reversed order , and then the elements of the second list .
(check-expect (test-append-from-foldl '(1 2) '(3)) '(2 1 3))
(define (test-append-from-foldl a b)
(foldl cons b a)
)
(check-expect (sum '(1 2 3 4)) 10)
(define (sum lon)
(foldr + 0 lon)
)
[ NEList - of Number ] - > Number
(check-expect (product '(1 2 3 4)) 24)
(define (product lon)
(foldl * 1 lon)
)
(define sq1 (square 100 "solid" "blue"))
(define sq2 (square 100 "solid" "yellow"))
Composes horizontally from left to right the list of images
(check-expect (compose-h '()) empty-image)
(check-expect (compose-h (list sq1 sq2)) (beside sq1 sq2))
(define (compose-h loi)
(foldl
(λ (img acc) (beside acc img))
empty-image
loi
))
Stacks a list of image . The first one of the list is on the
(check-expect (compose-v '()) empty-image)
(check-expect (compose-v (list sq1 sq2)) (above sq2 sq1))
(define (compose-v loi)
(foldl above empty-image loi)
)
(test)
|
c006f024a890dcc77de61c11f0a21ee3f9d751b9174a9f5d267b8163608ee792 | simmone/racket-simple-xlsx | cell-border-style-test.rkt | #lang racket
(require rackunit/text-ui rackunit)
(require "../../../../main.rkt")
(require racket/runtime-path)
(define-runtime-path cell_border_file "cell_border.xlsx")
(define-runtime-path cell_border_read_and_write_file "cell_border_read_and_write.xlsx")
(define test-writer
(test-suite
"test-writer"
(test-case
"test-border"
(dynamic-wind
(lambda () (void))
(lambda ()
(write-xlsx
cell_border_file
(lambda ()
(add-data-sheet
"Sheet1"
(let loop-row ([rows_count 100]
[rows '()])
(if (>= rows_count 1)
(loop-row
(sub1 rows_count)
(cons
(let loop-col ([cols_count 100]
[cols '()])
(if (>= cols_count 1)
(loop-col
(sub1 cols_count)
(cons cols_count cols))
cols))
rows))
rows)))
(with-sheet
(lambda ()
(set-cell-range-border-style "B2-F6" "all" "ff0000" "thick")
(set-cell-range-border-style "B8-F12" "left" "ff0000" "thick")
(set-cell-range-border-style "H2-L6" "right" "ff0000" "dashed")
(set-cell-range-border-style "H8-L12" "top" "ff0000" "double")
(set-cell-range-border-style "N2-R6" "bottom" "ff0000" "thick")
(set-cell-range-border-style "N8-R12" "side" "ff0000" "thick")
))))
(read-and-write-xlsx
cell_border_file
cell_border_read_and_write_file
(lambda ()
(void)))
)
(lambda ()
;; (void)
(delete-file cell_border_file)
(delete-file cell_border_read_and_write_file)
)))
))
(run-tests test-writer)
| null | https://raw.githubusercontent.com/simmone/racket-simple-xlsx/e0ac3190b6700b0ee1dd80ed91a8f4318533d012/simple-xlsx/tests/write-and-read/style/cell-border-style/cell-border-style-test.rkt | racket | (void) | #lang racket
(require rackunit/text-ui rackunit)
(require "../../../../main.rkt")
(require racket/runtime-path)
(define-runtime-path cell_border_file "cell_border.xlsx")
(define-runtime-path cell_border_read_and_write_file "cell_border_read_and_write.xlsx")
(define test-writer
(test-suite
"test-writer"
(test-case
"test-border"
(dynamic-wind
(lambda () (void))
(lambda ()
(write-xlsx
cell_border_file
(lambda ()
(add-data-sheet
"Sheet1"
(let loop-row ([rows_count 100]
[rows '()])
(if (>= rows_count 1)
(loop-row
(sub1 rows_count)
(cons
(let loop-col ([cols_count 100]
[cols '()])
(if (>= cols_count 1)
(loop-col
(sub1 cols_count)
(cons cols_count cols))
cols))
rows))
rows)))
(with-sheet
(lambda ()
(set-cell-range-border-style "B2-F6" "all" "ff0000" "thick")
(set-cell-range-border-style "B8-F12" "left" "ff0000" "thick")
(set-cell-range-border-style "H2-L6" "right" "ff0000" "dashed")
(set-cell-range-border-style "H8-L12" "top" "ff0000" "double")
(set-cell-range-border-style "N2-R6" "bottom" "ff0000" "thick")
(set-cell-range-border-style "N8-R12" "side" "ff0000" "thick")
))))
(read-and-write-xlsx
cell_border_file
cell_border_read_and_write_file
(lambda ()
(void)))
)
(lambda ()
(delete-file cell_border_file)
(delete-file cell_border_read_and_write_file)
)))
))
(run-tests test-writer)
|
9487c91ee60e39aa9087aa9382882a73a7403abf01443f762a7f2e8ca697f02b | mentat-collective/emmy | boole_test.cljc | #_"SPDX-License-Identifier: GPL-3.0"
(ns emmy.numerical.quadrature.boole-test
(:refer-clojure :exclude [+ - * /])
(:require [clojure.test :refer [is deftest testing use-fixtures]]
[emmy.abstract.function :as f]
[emmy.generic :as g :refer [+ - * /]]
[emmy.numerical.quadrature.boole :as qb]
[emmy.numerical.quadrature.trapezoid :as qt]
[emmy.numsymb]
[emmy.simplify :as s :refer [hermetic-simplify-fixture]]
[emmy.value :as v]
[same :refer [ish?]]))
(use-fixtures :each hermetic-simplify-fixture)
(defn boole-step
"Implements a single step of Boole's method, as laid out in the [Wikipedia
entry on Newton Cotes
formulas](#Closed_Newton%E2%80%93Cotes_formulas)."
[f a b]
(let [h (/ (- b a) 4)
mid (/ (+ a b) 2)
l-mid (/ (+ a mid) 2)
r-mid (/ (+ mid b) 2)]
(* (/ (* 2 h) 45)
(+ (* 7 (f a))
(* 32 (f l-mid))
(* 12 (f mid))
(* 32 (f r-mid))
(* 7 (f b))))))
(deftest boole-tests
(testing "Boole's Method is equivalent to TWO steps of Richardson
extrapolation on the Trapezoid method."
(f/with-literal-functions [f]
(let [a 'a
b 'b
mid (/ (+ a b) 2)
l-mid (/ (+ a mid) 2)
r-mid (/ (+ mid b) 2)
t1 (qt/single-trapezoid f a b)
t2 (+ (qt/single-trapezoid f a mid)
(qt/single-trapezoid f mid b))
t4 (+ (qt/single-trapezoid f a l-mid)
(qt/single-trapezoid f l-mid mid)
(qt/single-trapezoid f mid r-mid)
(qt/single-trapezoid f r-mid b))
;; Richardson extrapolation step with t=2, p=2,4,6... since the
error series of the rule = the even naturals .
richardson-step (fn [p a b]
(let [t**p (g/expt 2 p)]
(/ (- (* t**p b) a)
(- t**p 1))))]
(is (v/zero?
(g/simplify
(- (richardson-step 4
(richardson-step 2 t1 t2)
(richardson-step 2 t2 t4))
(boole-step f a b))))
"A boole step is equivalent to 2 pairwise Richardson steps with p=2,
and then a final combining step with p=4 (since we're now cancelling
a quartic error term)."))))
(testing "Boole's rule converges, and the interface works properly."
(let [pi-test (fn [x] (/ 4 (+ 1 (* x x))))]
(is (ish? {:converged? true
:terms-checked 4
:result 3.1415926537080376}
(qb/integral pi-test 0 1)))
(is (ish? {:converged? false
:terms-checked 3
:result 3.141592661142563}
(qb/integral pi-test 0 1 {:maxterms 3}))
"options get passed through."))))
| null | https://raw.githubusercontent.com/mentat-collective/emmy/90a1de10e78187c70d546c3cfd63c8d32b783bed/test/emmy/numerical/quadrature/boole_test.cljc | clojure | Richardson extrapolation step with t=2, p=2,4,6... since the | #_"SPDX-License-Identifier: GPL-3.0"
(ns emmy.numerical.quadrature.boole-test
(:refer-clojure :exclude [+ - * /])
(:require [clojure.test :refer [is deftest testing use-fixtures]]
[emmy.abstract.function :as f]
[emmy.generic :as g :refer [+ - * /]]
[emmy.numerical.quadrature.boole :as qb]
[emmy.numerical.quadrature.trapezoid :as qt]
[emmy.numsymb]
[emmy.simplify :as s :refer [hermetic-simplify-fixture]]
[emmy.value :as v]
[same :refer [ish?]]))
(use-fixtures :each hermetic-simplify-fixture)
(defn boole-step
"Implements a single step of Boole's method, as laid out in the [Wikipedia
entry on Newton Cotes
formulas](#Closed_Newton%E2%80%93Cotes_formulas)."
[f a b]
(let [h (/ (- b a) 4)
mid (/ (+ a b) 2)
l-mid (/ (+ a mid) 2)
r-mid (/ (+ mid b) 2)]
(* (/ (* 2 h) 45)
(+ (* 7 (f a))
(* 32 (f l-mid))
(* 12 (f mid))
(* 32 (f r-mid))
(* 7 (f b))))))
(deftest boole-tests
(testing "Boole's Method is equivalent to TWO steps of Richardson
extrapolation on the Trapezoid method."
(f/with-literal-functions [f]
(let [a 'a
b 'b
mid (/ (+ a b) 2)
l-mid (/ (+ a mid) 2)
r-mid (/ (+ mid b) 2)
t1 (qt/single-trapezoid f a b)
t2 (+ (qt/single-trapezoid f a mid)
(qt/single-trapezoid f mid b))
t4 (+ (qt/single-trapezoid f a l-mid)
(qt/single-trapezoid f l-mid mid)
(qt/single-trapezoid f mid r-mid)
(qt/single-trapezoid f r-mid b))
error series of the rule = the even naturals .
richardson-step (fn [p a b]
(let [t**p (g/expt 2 p)]
(/ (- (* t**p b) a)
(- t**p 1))))]
(is (v/zero?
(g/simplify
(- (richardson-step 4
(richardson-step 2 t1 t2)
(richardson-step 2 t2 t4))
(boole-step f a b))))
"A boole step is equivalent to 2 pairwise Richardson steps with p=2,
and then a final combining step with p=4 (since we're now cancelling
a quartic error term)."))))
(testing "Boole's rule converges, and the interface works properly."
(let [pi-test (fn [x] (/ 4 (+ 1 (* x x))))]
(is (ish? {:converged? true
:terms-checked 4
:result 3.1415926537080376}
(qb/integral pi-test 0 1)))
(is (ish? {:converged? false
:terms-checked 3
:result 3.141592661142563}
(qb/integral pi-test 0 1 {:maxterms 3}))
"options get passed through."))))
|
c84c285015ecf3e20774ab88f9caed4fd2e4340a4bd76d83f953e576770428de | coalton-lang/coalton | iterator.lisp | (coalton-library/utils:defstdlib-package #:coalton-library/iterator
(:shadow #:empty)
(:use
#:coalton
#:coalton-library/classes
#:coalton-library/hash
#:coalton-library/builtin
#:coalton-library/functions
#:coalton-library/optional
#:coalton-library/tuple
#:coalton-library/char)
(:local-nicknames
(#:types #:coalton-library/types)
(#:list #:coalton-library/list)
(#:string #:coalton-library/string)
(#:cell #:coalton-library/cell)
(#:vector #:coalton-library/vector)
(#:hashtable #:coalton-library/hashtable))
(:import-from
#:coalton-library/vector
#:Vector)
(:import-from
#:coalton-library/hashtable
#:Hashtable)
(:export
#:Iterator
#:new
#:next!
#:fold!
#:empty
#:last!
#:IntoIterator
#:into-iter
#:list-iter
#:vector-iter
#:string-chars
#:recursive-iter
#:range-increasing
#:up-to
#:up-through
#:range-decreasing
#:down-from
#:count-forever
#:repeat-forever
#:repeat-item
#:char-range
#:interleave!
#:zip!
#:zipWith!
#:enumerate!
#:filter!
#:unwrapped!
#:take!
#:flatten!
#:chain!
#:concat!
#:remove-duplicates!
#:pair-with!
#:sum!
#:and!
#:or!
#:count!
#:for-each!
#:find!
#:index-of!
#:optimize!
#:max!
#:min!
#:every!
#:any!
#:elementwise-match!
#:elementwise==!
#:elementwise-hash!
#:FromIterator
#:collect!
#:collect-list!
#:collect-vector-size-hint!
#:collect-vector!
#:collect-hashtable!))
#+coalton-release
(cl:declaim #.coalton-impl:*coalton-optimize-library*)
(in-package #:coalton-library/iterator)
;;; fundamental operators
(coalton-toplevel
(repr :transparent)
(define-type (Iterator :elt)
"A forward-moving pointer into an ordered sequence of :ELTs"
(%Iterator (Unit -> (Optional :elt))))
(declare new ((Unit -> Optional :elt) -> Iterator :elt))
(define new
"Create a new iterator from a function that yields elements."
%Iterator)
(declare next! (Iterator :elt -> Optional :elt))
(define (next! iter)
"Advance ITER, returning its next yielded value, or `None` if the iterator is exhausted.
Behavior is undefined if two threads concurrently call `next!` on the same iterator without a lock. Note that
most of the operators defined on iterators call `next!` internally, or create new iterators which will call
`next!` on their inputs."
(match iter
((%Iterator func) (func Unit))))
(declare fold! ((:state -> :elt -> :state) -> :state -> Iterator :elt -> :state))
(define (fold! func init iter)
"Tail recursive in-order fold. Common Lisp calls this operation `reduce`.
If ITER is empty, returns INIT. Otherwise, calls (FUNC STATE ITEM) for each ITEM of ITER to produce a new
STATE, using INIT as the first STATE."
(match (next! iter)
((Some item) (fold! func
(func init item)
iter))
((None) init)))
;;; instances
;; should iterator implement applicative or monad? the only law-abiding applicative instances are
;; pathological, so i doubt it.
(define-instance (Functor Iterator)
(define (map func iter)
(%Iterator (fn () (map func (next! iter))))))
;;; constructors
(declare empty (Iterator :any))
(define empty
"Yields nothing; stops immediately"
(%Iterator (fn () None)))
(define-class (IntoIterator :container :elt (:container -> :elt))
"Containers which can be converted into iterators.
`into-iter' must not mutate its argument, only produce a \"view\" into it."
(into-iter (:container -> Iterator :elt)))
(declare list-iter ((List :elt) -> (Iterator :elt)))
(define (list-iter lst)
"Yield successive elements of LST.
Behavior is undefined if the iterator is advanced after a destructive modification of LST."
(let ((remaining (cell:new lst)))
(%Iterator (fn () (cell:pop! remaining)))))
(define-instance (IntoIterator (List :elt) :elt)
(define into-iter list-iter))
(define-instance (IntoIterator (Iterator :elt) :elt)
(define into-iter id))
(define-instance (IntoIterator (Optional :elt) :elt)
(define (into-iter opt)
"Yield the single value of this OPT, or nothing."
(match opt
((Some a) (let ((cell (cell:new True)))
(%Iterator (fn () (if (cell:read cell)
(progn (cell:write! cell False)
(Some a))
None)))))
((None) (%Iterator (fn () None))))))
(define-instance (IntoIterator (Result :a :elt) :elt)
(define (into-iter result)
"Yield the single value of this RESULT, or nothing."
(match result
((Ok a) (let ((cell (cell:new True)))
(%Iterator (fn () (if (cell:read cell)
(progn (cell:write! cell False)
(Some a))
None)))))
((Err _) (%Iterator (fn () None))))))
(declare vector-iter (Vector :elt -> Iterator :elt))
(define (vector-iter vec)
"Yield successive elements of VEC.
Behavior is undefined if the iterator is advanced after a destructive modification of VEC."
(map ((flip vector:index-unsafe) vec)
(up-to (vector:length vec))))
(define-instance (IntoIterator (Vector :elt) :elt)
(define into-iter vector-iter))
(declare string-chars (String -> Iterator Char))
(define (string-chars str)
"Yield successive `Char`s from STR.
Behavior is undefined if the iterator is advanced after a destructive modification of STR."
(map (string:ref-unchecked str)
(up-to (string:length str))))
(define-instance (IntoIterator String Char)
(define into-iter string-chars))
(declare recursive-iter ((:elt -> :elt) -> (:elt -> Boolean) -> :elt -> Iterator :elt))
(define (recursive-iter succ done? start)
"An iterator which yields first START, then (SUCC START), then (SUCC (SUCC START)), and so on, stopping as soon as such a value is `done?`.
Beware off-by-one errors: the first value which is `done?` is not yielded. If `(done? start)' is true, the
iterator is empty."
(let ((next (cell:new start)))
(%Iterator
(fn ()
(let ((this (cell:read next)))
(if (done? this)
None
(Some (cell:update-swap! succ next))))))))
(declare range-increasing ((Num :num) (Ord :num) =>
:num ->
:num ->
:num ->
Iterator :num))
(define (range-increasing step start end)
"An iterator which begins at START and yields successive elements spaced by STEP, stopping before END."
(assert (>= end start)
"END ~a should be greater than or equal to START ~a in RANGE-INCREASING"
end start)
(assert (> step 0)
"STEP ~a should be positive and non-zero in RANGE-INCREASING"
step)
(recursive-iter (+ step) (<= end) start))
(declare up-to ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (up-to limit)
"An iterator which begins at zero and counts up to, but not including, LIMIT."
(range-increasing 1 0 limit))
(declare up-through ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (up-through limit)
"An iterator which begins at zero and counts up through and including LIMIT."
(up-to (+ 1 limit)))
(declare range-decreasing ((Num :num) (Ord :num) =>
:num ->
:num ->
:num ->
(Iterator :num)))
(define (range-decreasing step start end)
"A range which begins below START and counts down through and including END by STEP.
Equivalent to reversing `range-increasing`"
(assert (<= end start)
"END ~a should be less than or equal to START ~a in RANGE-INCREASING"
end start)
(assert (> step 0)
"STEP ~a should be positive and non-zero in RANGE-INCREASING"
step)
;; FIXME: avoid underflow in the DONE? test
(recursive-iter ((flip -) step)
(fn (n) (>= end (+ n step))) ; like (>= (- end step)), but without potential underflow
begin after START
))
(declare down-from ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (down-from limit)
"An iterator which begins below the provided limit and counts down through and including zero."
(range-decreasing 1 limit 0))
(declare count-forever ((Num :num) (Ord :num) => Unit -> Iterator :num))
(define (count-forever _)
"An infinite iterator which starts at 0 and counts upwards by 1."
(recursive-iter (+ 1)
(const False)
0))
(declare repeat-forever (:item -> Iterator :item))
(define (repeat-forever item)
"Yield ITEM over and over, infinitely."
(%Iterator
(fn ()
(Some item))))
(declare repeat-item (:item -> UFix -> Iterator :item))
(define (repeat-item item count)
"Yield ITEM COUNT times, then stop."
(take! count (repeat-forever item)))
(declare char-range (Char -> Char -> Iterator Char))
(define (char-range start end)
"An inclusive range of characters from START to END by cl:char-code."
(map (compose unwrap code-char)
(range-increasing 1
(char-code start)
(+ 1 (char-code end)))))
;;; combinators
;; these are named with a !, even though they're lazy and therefore do not actually mutate anything on their
own , for two reasons :
1 . it prevents name conflicts with list operators
2 . to emphasize the flow of mutable data
(declare interleave! (Iterator :a -> Iterator :a -> Iterator :a))
(define (interleave! left right)
"Return an interator of interleaved elements from LEFT and RIGHT which terminates as soon as both LEFT and RIGHT do.
If one iterator terminates before the other, elements from the longer iterator will be yielded without
interleaving. (interleave empty ITER) is equivalent to (id ITER)."
(let flag = (cell:new False))
(%Iterator
(fn ()
(cell:update! not flag)
(if (cell:read flag)
(match (next! left)
((Some val) (Some val))
((None) (next! right)))
(match (next! right)
((Some val) (Some val))
((None) (next! left)))))))
(declare zipWith! ((:left -> :right -> :out) -> Iterator :left -> Iterator :right -> Iterator :out))
(define (zipWith! f left right)
"Return an iterator of elements from LEFT and RIGHT which terminates as soon as either LEFT or RIGHT does."
(%Iterator
(fn ()
(match (Tuple (next! left) (next! right))
((Tuple (Some l) (Some r)) (Some (f l r)))
(_ None)))))
(declare zip! (Iterator :left -> Iterator :right -> Iterator (Tuple :left :right)))
(define zip!
"Return an iterator of tuples contining elements from two iterators."
(zipWith! Tuple))
(declare enumerate! (Iterator :elt -> Iterator (Tuple UFix :elt)))
(define (enumerate! iter)
"Pair successive zero-based incides with elements from ITER"
(zip! (count-forever) iter))
(declare filter! ((:elt -> Boolean) -> Iterator :elt -> Iterator :elt))
(define (filter! keep? iter)
"Return an iterator over the elements from ITER for which KEEP? returns true."
(let ((filter-iter (fn (u)
(match (next! iter)
((None) None)
((Some candidate) (if (keep? candidate)
(Some candidate)
(filter-iter u)))))))
(%Iterator filter-iter)))
(declare unwrapped! ((Unwrappable :wrapper) => Iterator (:wrapper :elt) -> Iterator :elt))
(define (unwrapped! iter)
(let ((next (fn ()
(match (next! iter)
((None) None)
((Some container)
(unwrap-or-else Some
next
container))))))
(new next)))
(declare take! (UFix -> Iterator :elt -> Iterator :elt))
(define (take! count iter)
"An `Iterator` which yields at most COUNT elements from ITER."
(map fst
(zip! iter
(up-to count))))
;; this appears to be a synonym for `concat!'. i would like to remove it - gefjon
(declare chain! (Iterator :elt -> Iterator :elt -> Iterator :elt))
(define (chain! iter1 iter2)
(%iterator
(fn ()
(match (next! iter1)
((None) (next! iter2))
((Some el) (Some el))))))
(declare flatten! (Iterator (Iterator :elt) -> Iterator :elt))
(define (flatten! iters)
"Yield all the elements from each of the ITERS in order."
(match (next! iters)
((None) empty)
((Some first)
(let ((current (cell:new first))
(flatten-iter-inner
(fn ()
(match (next! (cell:read current))
((Some elt) (Some elt))
((None) (match (next! iters)
((Some next-iter) (progn (cell:write! current next-iter)
(flatten-iter-inner)))
((None) None)))))))
(%Iterator flatten-iter-inner)))))
(declare concat! (Iterator :elt -> Iterator :elt -> Iterator :elt))
(define (concat! first second)
"Yield all the elements of FIRST followed by all the elements from SECOND."
(flatten! (list-iter (make-list first second))))
(declare remove-duplicates! (Hash :elt => Iterator :elt -> Iterator :elt))
(define (remove-duplicates! iter)
"Yield unique elements from ITER in order of first appearance."
(let ((already-seen (hashtable:new))
(unique? (fn (elt)
(match (hashtable:get already-seen elt)
((Some (Unit)) False)
((None) (progn (hashtable:set! already-seen elt Unit)
True))))))
(filter! unique? iter)))
(declare pair-with! ((:key -> :value) -> Iterator :key -> Iterator (Tuple :key :value)))
(define (pair-with! func keys)
"Returns an iterator over tuples whose FSTs are elements from KEYS, and whose SNDs are the results of applying FUNC to those KEYS."
(map (fn (key) (Tuple key (func key)))
keys))
;;; consumers
(declare last! ((Iterator :a) -> (Optional :a)))
(define (last! iter)
"Yields the last element of ITER, completely consuming it."
(fold! (fn (s e) (Some e)) None iter))
(declare and! (Iterator Boolean -> Boolean))
(define (and! iter)
"Returns True if all iterator elements are True. May not consume the entire iterator. Returns True on an empty iterator."
(let ((inner
(fn (state)
(when (not state)
(return False))
(match (next! iter)
((Some x) (inner (and state x)))
((None) True)))))
(inner True)))
(declare or! (Iterator Boolean -> Boolean))
(define (or! iter)
"Returns True if any iterator elements are True. May not consume the entire iterator. Returns False on an empty iterator."
(let ((inner
(fn (state)
(when state
(return True))
(match (next! iter)
((Some x) (inner (or state x)))
((None) False)))))
(inner False)))
(declare sum! (Num :num => Iterator :num -> :num))
(define (sum! iter)
"Add together all the elements of ITER."
(fold! + 0 iter))
(declare count! (Iterator :elt -> UFix))
(define (count! iter)
"Return the number of elements in ITER.
This operation could be called `length!`, but `count!` emphasizes the fact that it consumes ITER, and
afterwards, ITER will be exhausted."
(sum! (map (const 1) iter)))
(declare for-each! ((:elt -> :any) -> Iterator :elt -> Unit))
(define (for-each! thunk iter)
"Call THUNK on each element of ITER in order for side effects.
Discard values returned by THUNK."
(fold! (fn (u elt) (thunk elt) u)
Unit
iter))
(declare find! ((:elt -> Boolean) -> Iterator :elt -> Optional :elt))
(define (find! this? iter)
"Return the first element of ITER for which THIS? returns `True`, or `None` if no element matches."
(match (next! iter)
((Some elt) (if (this? elt)
(Some elt)
(find! this? iter)))
((None) None)))
(declare index-of! ((:elt -> Boolean) -> Iterator :elt -> Optional UFix))
(define (index-of! this? iter)
"Return the zero-based index of the first element of ITER for which THIS? is `True`, or `None` if no element matches."
(map fst
(find! (compose this? snd)
(enumerate! iter))))
(declare optimize! ((:elt -> :elt -> Boolean) -> Iterator :elt -> Optional :elt))
(define (optimize! better? iter)
"For an order BETTER? which returns `True` if its first argument is better than its second argument, return the best element of ITER.
Return `None` if ITER is empty."
(match (next! iter)
((None) None)
((Some first)
(Some
(fold! (fn (best new)
(if (better? new best) new best))
first
iter)))))
(declare max! (Ord :num => Iterator :num -> Optional :num))
(define (max! iter)
"Return the most-positive element of ITER, or `None` if ITER is empty."
(optimize! > iter))
(declare min! (Ord :num => Iterator :num -> Optional :num))
(define (min! iter)
"Return the most-negative element of ITER, or `None` if ITER is empty."
(optimize! < iter))
(declare every! ((:elt -> Boolean) -> Iterator :elt -> Boolean))
(define (every! good? iter)
"Return `True` if every element of ITER is GOOD?, or `False` as soon as any element is not GOOD?.
Returns `True` if ITER is empty."
(match (next! iter)
((None) True)
((Some item) (and (good? item) (every! good? iter)))))
(declare any! ((:elt -> Boolean) -> Iterator :elt -> Boolean))
(define (any! good? iter)
"Return `True` as soon as any element of ITER is GOOD?, or `False` if none of them are.
Returns `False` if ITER is empty."
(some? (find! good? iter)))
(declare elementwise-match! ((:elt -> :elt -> Boolean) -> (Iterator :elt) -> (Iterator :elt) -> Boolean))
(define (elementwise-match! same? left right)
"Are LEFT and RIGHT elementwise-identical under SAME?
True if, for every pair of elements (A B) in (LEFT RIGHT), (same? A B) is True, and LEFT and RIGHT have the
same length."
(match (Tuple (next! left) (next! right))
((Tuple (None) (None)) True)
((Tuple (Some l) (Some r)) (and (same? l r)
(elementwise-match! same? left right)))
(_ False)))
(declare elementwise==! ((Eq :elt) => ((Iterator :elt) -> (Iterator :elt) -> Boolean)))
(define elementwise==!
"Is every element of the first iterator `==' to the corresponding element of the second?
True if two iterators have the same length, and for every N, the Nth element of the first iterator is `==' to
the Nth element of the second iterator."
(elementwise-match! ==))
(declare elementwise-hash! ((Hash :elt) => ((Iterator :elt) -> Hash)))
(define (elementwise-hash! iter)
"Hash an iterator by combining the hashes of all its elements.
The empty iterator will hash as 0."
(match (next! iter)
((Some first) (fold! (fn (current new)
(combine-hashes current (hash new)))
(hash first)
iter))
((None) mempty)))
;;; collecting
(define-class (FromIterator :container :elt (:container -> :elt))
(collect! (Iterator :elt -> :container)))
(declare collect-list! (Iterator :elt -> List :elt))
(define (collect-list! iter)
"Construct a `List` containing all the elements from ITER in order."
(list:reverse (fold! (flip Cons) Nil iter)))
(define-instance (FromIterator (List :elt) :elt)
(define collect! collect-list!))
(declare collect-vector-size-hint! (types:RuntimeRepr :elt => UFix -> Iterator :elt -> Vector :elt))
(define (collect-vector-size-hint! size iter)
"Construct a `Vector` with initial allocation for SIZE elements, and fill it with all the elements from ITER in order.
The vector will be resized if ITER contains more than SIZE elements."
(let v = (vector:with-capacity size))
(for-each! ((flip vector:push!) v) iter)
v)
(declare collect-vector! (types:RuntimeRepr :elt => Iterator :elt -> Vector :elt))
(define (collect-vector! iter)
"Construct a `Vector` containing all the elements from ITER in order."
(collect-vector-size-hint! 0 iter))
(define-instance (types:RuntimeRepr :elt => FromIterator (Vector :elt) :elt)
(define collect! collect-vector!))
(declare collect-hashtable-size-hint!
((Hash :key) =>
UFix ->
(Iterator (Tuple :key :value)) ->
(HashTable :key :value)))
(define (collect-hashtable-size-hint! size iter)
"Construct a `HashTable` with initial allocation for SIZE key/value pairs, and fill it with all the key/value pairs from ITER.
If a key appears in ITER multiple times, the resulting table will contain its last corresponding value.
The table will be resized if ITER contains more than SIZE unique keys."
(let ht = (hashtable:with-capacity (into size)))
(for-each! (uncurry (hashtable:set! ht))
iter)
ht)
(declare collect-hashtable!
(Hash :key => Iterator (Tuple :key :value) -> HashTable :key :value))
(define (collect-hashtable! iter)
"Construct a `HashTable` containing all the key/value pairs from ITER.
If a key appears in ITER multiple times, the resulting table will contain its last corresponding value."
(collect-hashtable-size-hint! coalton-library/hashtable::default-hash-table-capacity iter))
(define-instance (Hash :key => FromIterator (hashtable:HashTable :key :value) (Tuple :key :value))
(define collect! collect-hashtable!)))
#+sb-package-locks
(sb-ext:lock-package "COALTON-LIBRARY/ITERATOR")
| null | https://raw.githubusercontent.com/coalton-lang/coalton/1d756c71c033fd750cd4757a3c2e91f6272e8814/library/iterator.lisp | lisp | fundamental operators
instances
should iterator implement applicative or monad? the only law-abiding applicative instances are
pathological, so i doubt it.
constructors
FIXME: avoid underflow in the DONE? test
like (>= (- end step)), but without potential underflow
combinators
these are named with a !, even though they're lazy and therefore do not actually mutate anything on their
this appears to be a synonym for `concat!'. i would like to remove it - gefjon
consumers
collecting | (coalton-library/utils:defstdlib-package #:coalton-library/iterator
(:shadow #:empty)
(:use
#:coalton
#:coalton-library/classes
#:coalton-library/hash
#:coalton-library/builtin
#:coalton-library/functions
#:coalton-library/optional
#:coalton-library/tuple
#:coalton-library/char)
(:local-nicknames
(#:types #:coalton-library/types)
(#:list #:coalton-library/list)
(#:string #:coalton-library/string)
(#:cell #:coalton-library/cell)
(#:vector #:coalton-library/vector)
(#:hashtable #:coalton-library/hashtable))
(:import-from
#:coalton-library/vector
#:Vector)
(:import-from
#:coalton-library/hashtable
#:Hashtable)
(:export
#:Iterator
#:new
#:next!
#:fold!
#:empty
#:last!
#:IntoIterator
#:into-iter
#:list-iter
#:vector-iter
#:string-chars
#:recursive-iter
#:range-increasing
#:up-to
#:up-through
#:range-decreasing
#:down-from
#:count-forever
#:repeat-forever
#:repeat-item
#:char-range
#:interleave!
#:zip!
#:zipWith!
#:enumerate!
#:filter!
#:unwrapped!
#:take!
#:flatten!
#:chain!
#:concat!
#:remove-duplicates!
#:pair-with!
#:sum!
#:and!
#:or!
#:count!
#:for-each!
#:find!
#:index-of!
#:optimize!
#:max!
#:min!
#:every!
#:any!
#:elementwise-match!
#:elementwise==!
#:elementwise-hash!
#:FromIterator
#:collect!
#:collect-list!
#:collect-vector-size-hint!
#:collect-vector!
#:collect-hashtable!))
#+coalton-release
(cl:declaim #.coalton-impl:*coalton-optimize-library*)
(in-package #:coalton-library/iterator)
(coalton-toplevel
(repr :transparent)
(define-type (Iterator :elt)
"A forward-moving pointer into an ordered sequence of :ELTs"
(%Iterator (Unit -> (Optional :elt))))
(declare new ((Unit -> Optional :elt) -> Iterator :elt))
(define new
"Create a new iterator from a function that yields elements."
%Iterator)
(declare next! (Iterator :elt -> Optional :elt))
(define (next! iter)
"Advance ITER, returning its next yielded value, or `None` if the iterator is exhausted.
Behavior is undefined if two threads concurrently call `next!` on the same iterator without a lock. Note that
most of the operators defined on iterators call `next!` internally, or create new iterators which will call
`next!` on their inputs."
(match iter
((%Iterator func) (func Unit))))
(declare fold! ((:state -> :elt -> :state) -> :state -> Iterator :elt -> :state))
(define (fold! func init iter)
"Tail recursive in-order fold. Common Lisp calls this operation `reduce`.
If ITER is empty, returns INIT. Otherwise, calls (FUNC STATE ITEM) for each ITEM of ITER to produce a new
STATE, using INIT as the first STATE."
(match (next! iter)
((Some item) (fold! func
(func init item)
iter))
((None) init)))
(define-instance (Functor Iterator)
(define (map func iter)
(%Iterator (fn () (map func (next! iter))))))
(declare empty (Iterator :any))
(define empty
"Yields nothing; stops immediately"
(%Iterator (fn () None)))
(define-class (IntoIterator :container :elt (:container -> :elt))
"Containers which can be converted into iterators.
`into-iter' must not mutate its argument, only produce a \"view\" into it."
(into-iter (:container -> Iterator :elt)))
(declare list-iter ((List :elt) -> (Iterator :elt)))
(define (list-iter lst)
"Yield successive elements of LST.
Behavior is undefined if the iterator is advanced after a destructive modification of LST."
(let ((remaining (cell:new lst)))
(%Iterator (fn () (cell:pop! remaining)))))
(define-instance (IntoIterator (List :elt) :elt)
(define into-iter list-iter))
(define-instance (IntoIterator (Iterator :elt) :elt)
(define into-iter id))
(define-instance (IntoIterator (Optional :elt) :elt)
(define (into-iter opt)
"Yield the single value of this OPT, or nothing."
(match opt
((Some a) (let ((cell (cell:new True)))
(%Iterator (fn () (if (cell:read cell)
(progn (cell:write! cell False)
(Some a))
None)))))
((None) (%Iterator (fn () None))))))
(define-instance (IntoIterator (Result :a :elt) :elt)
(define (into-iter result)
"Yield the single value of this RESULT, or nothing."
(match result
((Ok a) (let ((cell (cell:new True)))
(%Iterator (fn () (if (cell:read cell)
(progn (cell:write! cell False)
(Some a))
None)))))
((Err _) (%Iterator (fn () None))))))
(declare vector-iter (Vector :elt -> Iterator :elt))
(define (vector-iter vec)
"Yield successive elements of VEC.
Behavior is undefined if the iterator is advanced after a destructive modification of VEC."
(map ((flip vector:index-unsafe) vec)
(up-to (vector:length vec))))
(define-instance (IntoIterator (Vector :elt) :elt)
(define into-iter vector-iter))
(declare string-chars (String -> Iterator Char))
(define (string-chars str)
"Yield successive `Char`s from STR.
Behavior is undefined if the iterator is advanced after a destructive modification of STR."
(map (string:ref-unchecked str)
(up-to (string:length str))))
(define-instance (IntoIterator String Char)
(define into-iter string-chars))
(declare recursive-iter ((:elt -> :elt) -> (:elt -> Boolean) -> :elt -> Iterator :elt))
(define (recursive-iter succ done? start)
"An iterator which yields first START, then (SUCC START), then (SUCC (SUCC START)), and so on, stopping as soon as such a value is `done?`.
Beware off-by-one errors: the first value which is `done?` is not yielded. If `(done? start)' is true, the
iterator is empty."
(let ((next (cell:new start)))
(%Iterator
(fn ()
(let ((this (cell:read next)))
(if (done? this)
None
(Some (cell:update-swap! succ next))))))))
(declare range-increasing ((Num :num) (Ord :num) =>
:num ->
:num ->
:num ->
Iterator :num))
(define (range-increasing step start end)
"An iterator which begins at START and yields successive elements spaced by STEP, stopping before END."
(assert (>= end start)
"END ~a should be greater than or equal to START ~a in RANGE-INCREASING"
end start)
(assert (> step 0)
"STEP ~a should be positive and non-zero in RANGE-INCREASING"
step)
(recursive-iter (+ step) (<= end) start))
(declare up-to ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (up-to limit)
"An iterator which begins at zero and counts up to, but not including, LIMIT."
(range-increasing 1 0 limit))
(declare up-through ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (up-through limit)
"An iterator which begins at zero and counts up through and including LIMIT."
(up-to (+ 1 limit)))
(declare range-decreasing ((Num :num) (Ord :num) =>
:num ->
:num ->
:num ->
(Iterator :num)))
(define (range-decreasing step start end)
"A range which begins below START and counts down through and including END by STEP.
Equivalent to reversing `range-increasing`"
(assert (<= end start)
"END ~a should be less than or equal to START ~a in RANGE-INCREASING"
end start)
(assert (> step 0)
"STEP ~a should be positive and non-zero in RANGE-INCREASING"
step)
(recursive-iter ((flip -) step)
begin after START
))
(declare down-from ((Num :num) (Ord :num) => :num -> Iterator :num))
(define (down-from limit)
"An iterator which begins below the provided limit and counts down through and including zero."
(range-decreasing 1 limit 0))
(declare count-forever ((Num :num) (Ord :num) => Unit -> Iterator :num))
(define (count-forever _)
"An infinite iterator which starts at 0 and counts upwards by 1."
(recursive-iter (+ 1)
(const False)
0))
(declare repeat-forever (:item -> Iterator :item))
(define (repeat-forever item)
"Yield ITEM over and over, infinitely."
(%Iterator
(fn ()
(Some item))))
(declare repeat-item (:item -> UFix -> Iterator :item))
(define (repeat-item item count)
"Yield ITEM COUNT times, then stop."
(take! count (repeat-forever item)))
(declare char-range (Char -> Char -> Iterator Char))
(define (char-range start end)
"An inclusive range of characters from START to END by cl:char-code."
(map (compose unwrap code-char)
(range-increasing 1
(char-code start)
(+ 1 (char-code end)))))
own , for two reasons :
1 . it prevents name conflicts with list operators
2 . to emphasize the flow of mutable data
(declare interleave! (Iterator :a -> Iterator :a -> Iterator :a))
(define (interleave! left right)
"Return an interator of interleaved elements from LEFT and RIGHT which terminates as soon as both LEFT and RIGHT do.
If one iterator terminates before the other, elements from the longer iterator will be yielded without
interleaving. (interleave empty ITER) is equivalent to (id ITER)."
(let flag = (cell:new False))
(%Iterator
(fn ()
(cell:update! not flag)
(if (cell:read flag)
(match (next! left)
((Some val) (Some val))
((None) (next! right)))
(match (next! right)
((Some val) (Some val))
((None) (next! left)))))))
(declare zipWith! ((:left -> :right -> :out) -> Iterator :left -> Iterator :right -> Iterator :out))
(define (zipWith! f left right)
"Return an iterator of elements from LEFT and RIGHT which terminates as soon as either LEFT or RIGHT does."
(%Iterator
(fn ()
(match (Tuple (next! left) (next! right))
((Tuple (Some l) (Some r)) (Some (f l r)))
(_ None)))))
(declare zip! (Iterator :left -> Iterator :right -> Iterator (Tuple :left :right)))
(define zip!
"Return an iterator of tuples contining elements from two iterators."
(zipWith! Tuple))
(declare enumerate! (Iterator :elt -> Iterator (Tuple UFix :elt)))
(define (enumerate! iter)
"Pair successive zero-based incides with elements from ITER"
(zip! (count-forever) iter))
(declare filter! ((:elt -> Boolean) -> Iterator :elt -> Iterator :elt))
(define (filter! keep? iter)
"Return an iterator over the elements from ITER for which KEEP? returns true."
(let ((filter-iter (fn (u)
(match (next! iter)
((None) None)
((Some candidate) (if (keep? candidate)
(Some candidate)
(filter-iter u)))))))
(%Iterator filter-iter)))
(declare unwrapped! ((Unwrappable :wrapper) => Iterator (:wrapper :elt) -> Iterator :elt))
(define (unwrapped! iter)
(let ((next (fn ()
(match (next! iter)
((None) None)
((Some container)
(unwrap-or-else Some
next
container))))))
(new next)))
(declare take! (UFix -> Iterator :elt -> Iterator :elt))
(define (take! count iter)
"An `Iterator` which yields at most COUNT elements from ITER."
(map fst
(zip! iter
(up-to count))))
(declare chain! (Iterator :elt -> Iterator :elt -> Iterator :elt))
(define (chain! iter1 iter2)
(%iterator
(fn ()
(match (next! iter1)
((None) (next! iter2))
((Some el) (Some el))))))
(declare flatten! (Iterator (Iterator :elt) -> Iterator :elt))
(define (flatten! iters)
"Yield all the elements from each of the ITERS in order."
(match (next! iters)
((None) empty)
((Some first)
(let ((current (cell:new first))
(flatten-iter-inner
(fn ()
(match (next! (cell:read current))
((Some elt) (Some elt))
((None) (match (next! iters)
((Some next-iter) (progn (cell:write! current next-iter)
(flatten-iter-inner)))
((None) None)))))))
(%Iterator flatten-iter-inner)))))
(declare concat! (Iterator :elt -> Iterator :elt -> Iterator :elt))
(define (concat! first second)
"Yield all the elements of FIRST followed by all the elements from SECOND."
(flatten! (list-iter (make-list first second))))
(declare remove-duplicates! (Hash :elt => Iterator :elt -> Iterator :elt))
(define (remove-duplicates! iter)
"Yield unique elements from ITER in order of first appearance."
(let ((already-seen (hashtable:new))
(unique? (fn (elt)
(match (hashtable:get already-seen elt)
((Some (Unit)) False)
((None) (progn (hashtable:set! already-seen elt Unit)
True))))))
(filter! unique? iter)))
(declare pair-with! ((:key -> :value) -> Iterator :key -> Iterator (Tuple :key :value)))
(define (pair-with! func keys)
"Returns an iterator over tuples whose FSTs are elements from KEYS, and whose SNDs are the results of applying FUNC to those KEYS."
(map (fn (key) (Tuple key (func key)))
keys))
(declare last! ((Iterator :a) -> (Optional :a)))
(define (last! iter)
"Yields the last element of ITER, completely consuming it."
(fold! (fn (s e) (Some e)) None iter))
(declare and! (Iterator Boolean -> Boolean))
(define (and! iter)
"Returns True if all iterator elements are True. May not consume the entire iterator. Returns True on an empty iterator."
(let ((inner
(fn (state)
(when (not state)
(return False))
(match (next! iter)
((Some x) (inner (and state x)))
((None) True)))))
(inner True)))
(declare or! (Iterator Boolean -> Boolean))
(define (or! iter)
"Returns True if any iterator elements are True. May not consume the entire iterator. Returns False on an empty iterator."
(let ((inner
(fn (state)
(when state
(return True))
(match (next! iter)
((Some x) (inner (or state x)))
((None) False)))))
(inner False)))
(declare sum! (Num :num => Iterator :num -> :num))
(define (sum! iter)
"Add together all the elements of ITER."
(fold! + 0 iter))
(declare count! (Iterator :elt -> UFix))
(define (count! iter)
"Return the number of elements in ITER.
This operation could be called `length!`, but `count!` emphasizes the fact that it consumes ITER, and
afterwards, ITER will be exhausted."
(sum! (map (const 1) iter)))
(declare for-each! ((:elt -> :any) -> Iterator :elt -> Unit))
(define (for-each! thunk iter)
"Call THUNK on each element of ITER in order for side effects.
Discard values returned by THUNK."
(fold! (fn (u elt) (thunk elt) u)
Unit
iter))
(declare find! ((:elt -> Boolean) -> Iterator :elt -> Optional :elt))
(define (find! this? iter)
"Return the first element of ITER for which THIS? returns `True`, or `None` if no element matches."
(match (next! iter)
((Some elt) (if (this? elt)
(Some elt)
(find! this? iter)))
((None) None)))
(declare index-of! ((:elt -> Boolean) -> Iterator :elt -> Optional UFix))
(define (index-of! this? iter)
"Return the zero-based index of the first element of ITER for which THIS? is `True`, or `None` if no element matches."
(map fst
(find! (compose this? snd)
(enumerate! iter))))
(declare optimize! ((:elt -> :elt -> Boolean) -> Iterator :elt -> Optional :elt))
(define (optimize! better? iter)
"For an order BETTER? which returns `True` if its first argument is better than its second argument, return the best element of ITER.
Return `None` if ITER is empty."
(match (next! iter)
((None) None)
((Some first)
(Some
(fold! (fn (best new)
(if (better? new best) new best))
first
iter)))))
(declare max! (Ord :num => Iterator :num -> Optional :num))
(define (max! iter)
"Return the most-positive element of ITER, or `None` if ITER is empty."
(optimize! > iter))
(declare min! (Ord :num => Iterator :num -> Optional :num))
(define (min! iter)
"Return the most-negative element of ITER, or `None` if ITER is empty."
(optimize! < iter))
(declare every! ((:elt -> Boolean) -> Iterator :elt -> Boolean))
(define (every! good? iter)
"Return `True` if every element of ITER is GOOD?, or `False` as soon as any element is not GOOD?.
Returns `True` if ITER is empty."
(match (next! iter)
((None) True)
((Some item) (and (good? item) (every! good? iter)))))
(declare any! ((:elt -> Boolean) -> Iterator :elt -> Boolean))
(define (any! good? iter)
"Return `True` as soon as any element of ITER is GOOD?, or `False` if none of them are.
Returns `False` if ITER is empty."
(some? (find! good? iter)))
(declare elementwise-match! ((:elt -> :elt -> Boolean) -> (Iterator :elt) -> (Iterator :elt) -> Boolean))
(define (elementwise-match! same? left right)
"Are LEFT and RIGHT elementwise-identical under SAME?
True if, for every pair of elements (A B) in (LEFT RIGHT), (same? A B) is True, and LEFT and RIGHT have the
same length."
(match (Tuple (next! left) (next! right))
((Tuple (None) (None)) True)
((Tuple (Some l) (Some r)) (and (same? l r)
(elementwise-match! same? left right)))
(_ False)))
(declare elementwise==! ((Eq :elt) => ((Iterator :elt) -> (Iterator :elt) -> Boolean)))
(define elementwise==!
"Is every element of the first iterator `==' to the corresponding element of the second?
True if two iterators have the same length, and for every N, the Nth element of the first iterator is `==' to
the Nth element of the second iterator."
(elementwise-match! ==))
(declare elementwise-hash! ((Hash :elt) => ((Iterator :elt) -> Hash)))
(define (elementwise-hash! iter)
"Hash an iterator by combining the hashes of all its elements.
The empty iterator will hash as 0."
(match (next! iter)
((Some first) (fold! (fn (current new)
(combine-hashes current (hash new)))
(hash first)
iter))
((None) mempty)))
(define-class (FromIterator :container :elt (:container -> :elt))
(collect! (Iterator :elt -> :container)))
(declare collect-list! (Iterator :elt -> List :elt))
(define (collect-list! iter)
"Construct a `List` containing all the elements from ITER in order."
(list:reverse (fold! (flip Cons) Nil iter)))
(define-instance (FromIterator (List :elt) :elt)
(define collect! collect-list!))
(declare collect-vector-size-hint! (types:RuntimeRepr :elt => UFix -> Iterator :elt -> Vector :elt))
(define (collect-vector-size-hint! size iter)
"Construct a `Vector` with initial allocation for SIZE elements, and fill it with all the elements from ITER in order.
The vector will be resized if ITER contains more than SIZE elements."
(let v = (vector:with-capacity size))
(for-each! ((flip vector:push!) v) iter)
v)
(declare collect-vector! (types:RuntimeRepr :elt => Iterator :elt -> Vector :elt))
(define (collect-vector! iter)
"Construct a `Vector` containing all the elements from ITER in order."
(collect-vector-size-hint! 0 iter))
(define-instance (types:RuntimeRepr :elt => FromIterator (Vector :elt) :elt)
(define collect! collect-vector!))
(declare collect-hashtable-size-hint!
((Hash :key) =>
UFix ->
(Iterator (Tuple :key :value)) ->
(HashTable :key :value)))
(define (collect-hashtable-size-hint! size iter)
"Construct a `HashTable` with initial allocation for SIZE key/value pairs, and fill it with all the key/value pairs from ITER.
If a key appears in ITER multiple times, the resulting table will contain its last corresponding value.
The table will be resized if ITER contains more than SIZE unique keys."
(let ht = (hashtable:with-capacity (into size)))
(for-each! (uncurry (hashtable:set! ht))
iter)
ht)
(declare collect-hashtable!
(Hash :key => Iterator (Tuple :key :value) -> HashTable :key :value))
(define (collect-hashtable! iter)
"Construct a `HashTable` containing all the key/value pairs from ITER.
If a key appears in ITER multiple times, the resulting table will contain its last corresponding value."
(collect-hashtable-size-hint! coalton-library/hashtable::default-hash-table-capacity iter))
(define-instance (Hash :key => FromIterator (hashtable:HashTable :key :value) (Tuple :key :value))
(define collect! collect-hashtable!)))
#+sb-package-locks
(sb-ext:lock-package "COALTON-LIBRARY/ITERATOR")
|
494904652cf75cf52ef9f89e0aede36697ff5396ef5c52b320030d56888ecdfb | komi1230/kai | main.lisp | scatter.lisp - A collection of scatter plotting
;;;
;;; This code has been placed in the Public Domain. All warranties
;;; are disclaimed.
;;;
;;; This file is composed of a collection of exampeles of plotting.
;;; Here's codes are mainly deal scatter plotting.
(in-package :cl-user)
(defpackage :kai-example
(:use :cl)
(:import-from :kai
:title
:line
:pie
:box
:heatmap
:contour
:line3d
:surface
:fillarea
:marker
:marker3d
:xaxis
:yaxis
:show)
(:export :line
:marker-example
:pie-chart
:sunburst-chart
:heatmap-chart
:box-chart
:contour-chart
:line3d
:marker3d-example
:surface-chart))
(in-package :kai-example)
;;;; Parameters
;;;
;;; These are parameters to plot in the figure.
(defparameter x-data-index
(loop for i from 0 below 10
collect i))
(defparameter x-data-random
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter y-data-10
(loop for i from 0 below 10
collect (random 10.0)))
(defparameter y-data-100
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter z-data-100
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter pie-label
'("Residential" "Non-Residential" "Utility"))
(defparameter pie-data
'(19 26 55))
(defparameter box-data
(loop :repeat 50
:collect (random 100.0)))
(defparameter heatmap-data
(loop :repeat 100
:collect (loop :repeat 100
:collect (random 10.0))))
(defparameter contour-data
(loop :repeat 20
:collect (loop :repeat 20
:collect (random 10.0))))
;;;; Basic plotting
;;;
;;; Line and scatter
(defun line-chart ()
(line x-data-index
y-data-10)
(title "Line plot example")
(xaxis (list :|title| "X axis"))
(yaxis (list :|title| "Y axis"))
(show))
(defun marker-example ()
(marker x-data-random
y-data-100
:size 20)
(title "Marker plot example")
(show))
(defun fill-chart ()
(fillarea '(1 2 3)
'(2 1 3)
'(5 2 7)
:color :aqua)
(title "Fill chart with line plotting")
(show))
;;;; Pie chart
;;;
;;; pie cahrt with labels
(defun pie-chart ()
(pie pie-data pie-label)
(title "Pie chart example")
(show))
;;;; Box
;;;
;;; box plots example
(defun box-chart ()
(box box-data)
(title "Box chart example")
(show))
Heatmap
;;;
;;; heatmap example
(defun heatmap-chart ()
(heatmap heatmap-data
:showscale t)
(title "Heatmap example")
(show))
Contour
;;;
Contour example
(defun contour-chart ()
(contour contour-data
:showscale t)
(title "Contour example")
(show))
;;;; Scatter3D
;;;
;;; scatter3d plots: line and marker
(defun line3d-example ()
(line3d x-data-random
y-data-100
z-data-100)
(title "Line3D plot example")
(show))
(defun marker3d-example ()
(marker3d x-data-random
y-data-100
z-data-100)
(title "Marker3D plot example")
(show))
;;;; Surface
;;;
;;; surface chart-example
(defun surface-chart ()
(surface contour-data)
(title "Surface chart example")
(show))
| null | https://raw.githubusercontent.com/komi1230/kai/7481aae3ca11a79c117dd6fbc4e3bf2122a89627/examples/main.lisp | lisp |
This code has been placed in the Public Domain. All warranties
are disclaimed.
This file is composed of a collection of exampeles of plotting.
Here's codes are mainly deal scatter plotting.
Parameters
These are parameters to plot in the figure.
Basic plotting
Line and scatter
Pie chart
pie cahrt with labels
Box
box plots example
heatmap example
Scatter3D
scatter3d plots: line and marker
Surface
surface chart-example | scatter.lisp - A collection of scatter plotting
(in-package :cl-user)
(defpackage :kai-example
(:use :cl)
(:import-from :kai
:title
:line
:pie
:box
:heatmap
:contour
:line3d
:surface
:fillarea
:marker
:marker3d
:xaxis
:yaxis
:show)
(:export :line
:marker-example
:pie-chart
:sunburst-chart
:heatmap-chart
:box-chart
:contour-chart
:line3d
:marker3d-example
:surface-chart))
(in-package :kai-example)
(defparameter x-data-index
(loop for i from 0 below 10
collect i))
(defparameter x-data-random
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter y-data-10
(loop for i from 0 below 10
collect (random 10.0)))
(defparameter y-data-100
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter z-data-100
(loop for i from 0 below 100
collect (random 10.0)))
(defparameter pie-label
'("Residential" "Non-Residential" "Utility"))
(defparameter pie-data
'(19 26 55))
(defparameter box-data
(loop :repeat 50
:collect (random 100.0)))
(defparameter heatmap-data
(loop :repeat 100
:collect (loop :repeat 100
:collect (random 10.0))))
(defparameter contour-data
(loop :repeat 20
:collect (loop :repeat 20
:collect (random 10.0))))
(defun line-chart ()
(line x-data-index
y-data-10)
(title "Line plot example")
(xaxis (list :|title| "X axis"))
(yaxis (list :|title| "Y axis"))
(show))
(defun marker-example ()
(marker x-data-random
y-data-100
:size 20)
(title "Marker plot example")
(show))
(defun fill-chart ()
(fillarea '(1 2 3)
'(2 1 3)
'(5 2 7)
:color :aqua)
(title "Fill chart with line plotting")
(show))
(defun pie-chart ()
(pie pie-data pie-label)
(title "Pie chart example")
(show))
(defun box-chart ()
(box box-data)
(title "Box chart example")
(show))
Heatmap
(defun heatmap-chart ()
(heatmap heatmap-data
:showscale t)
(title "Heatmap example")
(show))
Contour
Contour example
(defun contour-chart ()
(contour contour-data
:showscale t)
(title "Contour example")
(show))
(defun line3d-example ()
(line3d x-data-random
y-data-100
z-data-100)
(title "Line3D plot example")
(show))
(defun marker3d-example ()
(marker3d x-data-random
y-data-100
z-data-100)
(title "Marker3D plot example")
(show))
(defun surface-chart ()
(surface contour-data)
(title "Surface chart example")
(show))
|
07b317b262fa1584b6dead979e4e3ad46ceaa3a7565d86dc8a34126337dbc063 | bsansouci/bsb-native | bytelibrarian.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 Q Public License version 1.0 .
(* *)
(***********************************************************************)
Build libraries of .cmo files
(* Format of a library file:
magic number (Config.cma_magic_number)
absolute offset of content table
blocks of relocatable bytecode
content table = list of compilation units
*)
val create_archive: Format.formatter -> string list -> string -> unit
type error =
File_not_found of string
| Not_an_object_file of string
exception Error of error
open Format
val report_error: formatter -> error -> unit
val reset: unit -> unit
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/bytecomp/bytelibrarian.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Format of a library file:
magic number (Config.cma_magic_number)
absolute offset of content table
blocks of relocatable bytecode
content table = list of compilation units
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
Build libraries of .cmo files
val create_archive: Format.formatter -> string list -> string -> unit
type error =
File_not_found of string
| Not_an_object_file of string
exception Error of error
open Format
val report_error: formatter -> error -> unit
val reset: unit -> unit
|
adab90be29fb741d26b75616cedc02bf2a5f294b0a7bfcecb2e77c6cf4684ece | HugoPeters1024/hs-sleuth | Encoding.hs | # LANGUAGE BangPatterns , CPP , GeneralizedNewtypeDeriving , MagicHash ,
UnliftedFFITypes #
UnliftedFFITypes #-}
# LANGUAGE Trustworthy #
# LANGUAGE TypeApplications #
-- |
-- Module : Data.Text.Encoding
Copyright : ( c ) 2009 , 2010 , 2011 ,
( c ) 2009 ,
( c ) 2008 , 2009
--
-- License : BSD-style
-- Maintainer :
-- Portability : portable
--
Functions for converting ' Text ' values to and from ' ByteString ' ,
-- using several standard encodings.
--
-- To gain access to a much larger family of encodings, use the
-- <-icu text-icu package>.
module Data.Text.Encoding
(
* Decoding ByteStrings to Text
-- $strict
decodeASCII
, decodeLatin1
, decodeUtf8
, decodeUtf16LE
, decodeUtf16BE
, decodeUtf32LE
, decodeUtf32BE
* * failure
, decodeUtf8'
-- ** Controllable error handling
, decodeUtf8With
, decodeUtf8Lenient
, decodeUtf16LEWith
, decodeUtf16BEWith
, decodeUtf32LEWith
, decodeUtf32BEWith
-- ** Stream oriented decoding
-- $stream
, streamDecodeUtf8
, streamDecodeUtf8With
, Decoding(..)
* Encoding Text to ByteStrings
, encodeUtf8
, encodeUtf16LE
, encodeUtf16BE
, encodeUtf32LE
, encodeUtf32BE
* Encoding Text using ByteString Builders
, encodeUtf8Builder
, encodeUtf8BuilderEscaped
) where
import Control.Monad.ST.Unsafe (unsafeIOToST, unsafeSTToIO)
import Control.Exception (evaluate, try, throwIO, ErrorCall(ErrorCall))
import Control.Monad.ST (runST)
import Data.Bits ((.&.), shiftR)
import Data.ByteString as B
import qualified Data.ByteString.Internal as B
import Data.Foldable (traverse_)
import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode, lenientDecode)
import Data.Text.Internal (Text(..), safe, text)
import Data.Text.Internal.Functions
import Data.Text.Internal.Private (runText)
import Data.Text.Internal.Unsafe.Char (ord, unsafeWrite)
import Data.Text.Show ()
import Data.Text.Unsafe (unsafeDupablePerformIO)
import Data.Word (Word8, Word16, Word32)
import Foreign.C.Types (CSize(CSize))
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr, minusPtr, nullPtr, plusPtr)
import Foreign.Storable (Storable, peek, poke)
import GHC.Base (ByteArray#, MutableByteArray#)
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Internal as B hiding (empty, append)
import qualified Data.ByteString.Builder.Prim as BP
import qualified Data.ByteString.Builder.Prim.Internal as BP
import qualified Data.Text.Array as A
import qualified Data.Text.Internal.Encoding.Fusion as E
import qualified Data.Text.Internal.Encoding.Utf16 as U16
import qualified Data.Text.Internal.Fusion as F
import Data.Text.Internal.ByteStringCompat
#if defined(ASSERTS)
import GHC.Stack (HasCallStack)
#endif
#include "text_cbits.h"
-- $strict
--
-- All of the single-parameter functions for decoding bytestrings
encoded in one of the Unicode Transformation Formats ( UTF ) operate
in a /strict/ mode : each will throw an exception if given invalid
-- input.
--
-- Each function has a variant, whose name is suffixed with -'With',
-- that gives greater control over the handling of decoding errors.
-- For instance, 'decodeUtf8' will throw an exception, but
-- 'decodeUtf8With' allows the programmer to determine what to do on a
-- decoding error.
| a ' ByteString ' containing 7 - bit ASCII
-- encoded text.
decodeASCII :: ByteString -> Text
decodeASCII = decodeUtf8
{-# DEPRECATED decodeASCII "Use decodeUtf8 instead" #-}
-- | Decode a 'ByteString' containing Latin-1 (aka ISO-8859-1) encoded text.
--
-- 'decodeLatin1' is semantically equivalent to
-- @Data.Text.pack . Data.ByteString.Char8.unpack@
decodeLatin1 ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Text
decodeLatin1 bs = withBS bs aux where
aux fp len = text a 0 len
where
a = A.run (A.new len >>= unsafeIOToST . go)
go dest = unsafeWithForeignPtr fp $ \ptr -> do
c_decode_latin1 (A.maBA dest) ptr (ptr `plusPtr` len)
return dest
| Decode a ' ByteString ' containing UTF-8 encoded text .
--
-- __NOTE__: The replacement character returned by 'OnDecodeError'
MUST be within the BMP plane ; surrogate code points will
automatically be remapped to the replacement char @U+FFFD@
( /since 0.11.3.0/ ) , whereas code points beyond the BMP will throw an
-- 'error' (/since 1.2.3.1/); For earlier versions of @text@ using
-- those unsupported code points would result in undefined behavior.
decodeUtf8With ::
#if defined(ASSERTS)
HasCallStack =>
#endif
OnDecodeError -> ByteString -> Text
decodeUtf8With onErr bs = withBS bs aux
where
aux fp len = runText $ \done -> do
let go dest = unsafeWithForeignPtr fp $ \ptr ->
with (0::CSize) $ \destOffPtr -> do
let end = ptr `plusPtr` len
loop curPtr = do
curPtr' <- c_decode_utf8 (A.maBA dest) destOffPtr curPtr end
if curPtr' == end
then do
n <- peek destOffPtr
unsafeSTToIO (done dest (cSizeToInt n))
else do
x <- peek curPtr'
case onErr desc (Just x) of
Nothing -> loop $ curPtr' `plusPtr` 1
Just c
| c > '\xFFFF' -> throwUnsupportedReplChar
| otherwise -> do
destOff <- peek destOffPtr
w <- unsafeSTToIO $
unsafeWrite dest (cSizeToInt destOff)
(safe c)
poke destOffPtr (destOff + intToCSize w)
loop $ curPtr' `plusPtr` 1
loop ptr
(unsafeIOToST . go) =<< A.new len
where
desc = "Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream"
throwUnsupportedReplChar = throwIO $
ErrorCall "decodeUtf8With: non-BMP replacement characters not supported"
-- TODO: The code currently assumes that the transcoded UTF-16
stream is at most twice as long ( in bytes ) as the input UTF-8
-- stream. To justify this assumption one has to assume that the
-- error handler replacement character also satisfies this
invariant , by emitting at most one UTF16 code unit .
--
One easy way to support the full range of code - points for
-- replacement characters in the error handler is to simply change
the ( over-)allocation to ` A.new ( 2*len ) ` and then shrink back the
` ByteArray # ` to the real size ( recent GHCs have a cheap
` ByteArray # ` resize - primop for that which allow the GC to reclaim
the overallocation ) . However , this would require 4 times as much
( temporary ) storage as the original UTF-8 required .
--
-- Another strategy would be to optimistically assume that
replacement characters are within the BMP , and if the case of a
-- non-BMP replacement occurs reallocate the target buffer (or throw
an exception , and fallback to a pessimistic codepath , like e.g.
` decodeUtf8With onErr bs = F.unstream ( E.streamUtf8 onErr bs ) ` )
--
-- Alternatively, `OnDecodeError` could become a datastructure which
-- statically encodes the replacement-character range,
-- e.g. something isomorphic to
--
Either ( ... - > Maybe ) ( ... - > Maybe )
--
And allow to statically switch between the BMP / non - BMP
-- replacement-character codepaths. There's multiple ways to address
-- this with different tradeoffs; but ideally we should optimise for
-- the optimistic/error-free case.
{- INLINE[0] decodeUtf8With #-}
-- $stream
--
-- The 'streamDecodeUtf8' and 'streamDecodeUtf8With' functions accept
-- a 'ByteString' that represents a possibly incomplete input (e.g. a
packet from a network stream ) that may not end on a UTF-8 boundary .
--
1 . The maximal prefix of ' Text ' that could be decoded from the
-- given input.
--
2 . The suffix of the ' ByteString ' that could not be decoded due to
-- insufficient input.
--
3 . A function that accepts another ' ByteString ' . That string will
-- be assumed to directly follow the string that was passed as
-- input to the original function, and it will in turn be decoded.
--
To help understand the use of these functions , consider the Unicode
string @\"hi & # 9731;\"@. If encoded as UTF-8 , this becomes @\"hi
\\xe2\\x98\\x83\"@ ; the final @\'☃\'@ is encoded as 3 bytes .
--
Now suppose that we receive this encoded string as 3 packets that
-- are split up on untidy boundaries: @[\"hi \\xe2\", \"\\x98\",
\"\\x83\"]@. We can not decode the entire Unicode string until we
have received all three packets , but we would like to make progress
-- as we receive each one.
--
-- @
ghci > let ' _ _ f0 ) = ' streamDecodeUtf8 ' \"hi \\xe2\ "
-- ghci> s0
-- 'Some' \"hi \" \"\\xe2\" _
-- @
--
We use the continuation @f0@ to decode our second packet .
--
-- @
ghci > let s1\@('Some ' _ _ f1 ) = f0 \"\\x98\ "
-- ghci> s1
-- 'Some' \"\" \"\\xe2\\x98\"
-- @
--
-- We could not give @f0@ enough input to decode anything, so it
returned an empty string . Once we feed our second continuation
-- the last byte of input, it will make progress.
--
-- @
-- ghci> let s2\@('Some' _ _ f2) = f1 \"\\x83\"
-- ghci> s2
-- 'Some' \"\\x2603\" \"\" _
-- @
--
-- If given invalid input, an exception will be thrown by the function
-- or continuation where it is encountered.
-- | A stream oriented decoding result.
--
@since 1.0.0.0
data Decoding = Some Text ByteString (ByteString -> Decoding)
instance Show Decoding where
showsPrec d (Some t bs _) = showParen (d > prec) $
showString "Some " . showsPrec prec' t .
showChar ' ' . showsPrec prec' bs .
showString " _"
where prec = 10; prec' = prec + 1
newtype CodePoint = CodePoint Word32 deriving (Eq, Show, Num, Storable)
newtype DecoderState = DecoderState Word32 deriving (Eq, Show, Num, Storable)
| Decode , in a stream oriented way , a ' ByteString ' containing UTF-8
-- encoded text that is known to be valid.
--
If the input contains any invalid UTF-8 data , an exception will be
-- thrown (either by this function or a continuation) that cannot be
-- caught in pure code. For more control over the handling of invalid
-- data, use 'streamDecodeUtf8With'.
--
@since 1.0.0.0
streamDecodeUtf8 ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Decoding
streamDecodeUtf8 = streamDecodeUtf8With strictDecode
| Decode , in a stream oriented way , a lazy ' ByteString ' containing UTF-8
-- encoded text.
--
@since 1.0.0.0
streamDecodeUtf8With ::
#if defined(ASSERTS)
HasCallStack =>
#endif
OnDecodeError -> ByteString -> Decoding
streamDecodeUtf8With onErr = decodeChunk B.empty 0 0
where
-- We create a slightly larger than necessary buffer to accommodate a
-- potential surrogate pair started in the last buffer (@undecoded0@), or
-- replacement characters for each byte in @undecoded0@ if the
sequence turns out to be invalid . There can be up to three bytes there ,
hence we allocate @len+3@ 16 - bit words .
decodeChunk :: ByteString -> CodePoint -> DecoderState -> ByteString
-> Decoding
decodeChunk undecoded0 codepoint0 state0 bs = withBS bs aux where
aux fp len = runST $ (unsafeIOToST . decodeChunkToBuffer) =<< A.new (len+3)
where
decodeChunkToBuffer :: A.MArray s -> IO Decoding
decodeChunkToBuffer dest = unsafeWithForeignPtr fp $ \ptr ->
with (0::CSize) $ \destOffPtr ->
with codepoint0 $ \codepointPtr ->
with state0 $ \statePtr ->
with nullPtr $ \curPtrPtr ->
let end = ptr `plusPtr` len
loop curPtr = do
prevState <- peek statePtr
poke curPtrPtr curPtr
lastPtr <- c_decode_utf8_with_state (A.maBA dest) destOffPtr
curPtrPtr end codepointPtr statePtr
state <- peek statePtr
case state of
UTF8_REJECT -> do
-- We encountered an encoding error
poke statePtr 0
let skipByte x = case onErr desc (Just x) of
Nothing -> return ()
Just c -> do
destOff <- peek destOffPtr
w <- unsafeSTToIO $
unsafeWrite dest (cSizeToInt destOff) (safe c)
poke destOffPtr (destOff + intToCSize w)
if ptr == lastPtr && prevState /= UTF8_ACCEPT then do
-- If we can't complete the sequence @undecoded0@ from
-- the previous chunk, we invalidate the bytes from
-- @undecoded0@ and retry decoding the current chunk from
-- the initial state.
traverse_ skipByte (B.unpack undecoded0 )
loop lastPtr
else do
peek lastPtr >>= skipByte
loop (lastPtr `plusPtr` 1)
_ -> do
-- We encountered the end of the buffer while decoding
n <- peek destOffPtr
codepoint <- peek codepointPtr
chunkText <- unsafeSTToIO $ do
arr <- A.unsafeFreeze dest
return $! text arr 0 (cSizeToInt n)
let left = lastPtr `minusPtr` ptr
!undecoded = case state of
UTF8_ACCEPT -> B.empty
_ | left == 0 && prevState /= UTF8_ACCEPT -> B.append undecoded0 bs
| otherwise -> B.drop left bs
return $ Some chunkText undecoded
(decodeChunk undecoded codepoint state)
in loop ptr
desc = "Data.Text.Internal.Encoding.streamDecodeUtf8With: Invalid UTF-8 stream"
| Decode a ' ByteString ' containing UTF-8 encoded text that is known
-- to be valid.
--
If the input contains any invalid UTF-8 data , an exception will be
-- thrown that cannot be caught in pure code. For more control over
-- the handling of invalid data, use 'decodeUtf8'' or
-- 'decodeUtf8With'.
decodeUtf8 :: ByteString -> Text
decodeUtf8 = decodeUtf8With strictDecode
{-# INLINE[0] decodeUtf8 #-}
| Decode a ' ByteString ' containing UTF-8 encoded text .
--
If the input contains any invalid UTF-8 data , the relevant
-- exception will be returned, otherwise the decoded text.
decodeUtf8' ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Either UnicodeException Text
decodeUtf8' = unsafeDupablePerformIO . try . evaluate . decodeUtf8With strictDecode
{-# INLINE decodeUtf8' #-}
| Decode a ' ByteString ' containing UTF-8 encoded text .
--
Any invalid input bytes will be replaced with the Unicode replacement
character U+FFFD .
decodeUtf8Lenient :: ByteString -> Text
decodeUtf8Lenient = decodeUtf8With lenientDecode
| Encode text to a ByteString ' B.Builder ' using UTF-8 encoding .
--
-- @since 1.1.0.0
encodeUtf8Builder :: Text -> B.Builder
encodeUtf8Builder = encodeUtf8BuilderEscaped (BP.liftFixedToBounded BP.word8)
| Encode text using UTF-8 encoding and escape the ASCII characters using
-- a 'BP.BoundedPrim'.
--
-- Use this function is to implement efficient encoders for text-based formats
-- like JSON or HTML.
--
-- @since 1.1.0.0
{-# INLINE encodeUtf8BuilderEscaped #-}
TODO : Extend documentation with references to source code in @blaze - html@
or @aeson@ that uses this function .
encodeUtf8BuilderEscaped :: BP.BoundedPrim Word8 -> Text -> B.Builder
encodeUtf8BuilderEscaped be =
-- manual eta-expansion to ensure inlining works as expected
\txt -> B.builder (mkBuildstep txt)
where
bound = max 4 $ BP.sizeBound be
mkBuildstep (Text arr off len) !k =
outerLoop off
where
iend = off + len
outerLoop !i0 !br@(B.BufferRange op0 ope)
| i0 >= iend = k br
| outRemaining > 0 = goPartial (i0 + min outRemaining inpRemaining)
TODO : Use a loop with an integrated bound 's check if outRemaining
is smaller than 8 , as this will save on divisions .
| otherwise = return $ B.bufferFull bound op0 (outerLoop i0)
where
outRemaining = (ope `minusPtr` op0) `div` bound
inpRemaining = iend - i0
goPartial !iendTmp = go i0 op0
where
go !i !op
| i < iendTmp = case A.unsafeIndex arr i of
w | w <= 0x7F -> do
BP.runB be (word16ToWord8 w) op >>= go (i + 1)
| w <= 0x7FF -> do
poke8 @Word16 0 $ (w `shiftR` 6) + 0xC0
poke8 @Word16 1 $ (w .&. 0x3f) + 0x80
go (i + 1) (op `plusPtr` 2)
| 0xD800 <= w && w <= 0xDBFF -> do
let c = ord $ U16.chr2 w (A.unsafeIndex arr (i+1))
poke8 @Int 0 $ (c `shiftR` 18) + 0xF0
poke8 @Int 1 $ ((c `shiftR` 12) .&. 0x3F) + 0x80
poke8 @Int 2 $ ((c `shiftR` 6) .&. 0x3F) + 0x80
poke8 @Int 3 $ (c .&. 0x3F) + 0x80
go (i + 2) (op `plusPtr` 4)
| otherwise -> do
poke8 @Word16 0 $ (w `shiftR` 12) + 0xE0
poke8 @Word16 1 $ ((w `shiftR` 6) .&. 0x3F) + 0x80
poke8 @Word16 2 $ (w .&. 0x3F) + 0x80
go (i + 1) (op `plusPtr` 3)
| otherwise =
outerLoop i (B.BufferRange op ope)
where
Take care , a is either above
poke8 :: Integral a => Int -> a -> IO ()
poke8 j v = poke (op `plusPtr` j) (fromIntegral v :: Word8)
| Encode text using UTF-8 encoding .
encodeUtf8 :: Text -> ByteString
encodeUtf8 (Text arr off len)
| len == 0 = B.empty
| otherwise = unsafeDupablePerformIO $ do
see for why is enough
unsafeWithForeignPtr fp $ \ptr ->
with ptr $ \destPtr -> do
c_encode_utf8 destPtr (A.aBA arr) (intToCSize off) (intToCSize len)
newDest <- peek destPtr
let utf8len = newDest `minusPtr` ptr
if utf8len >= len `shiftR` 1
then return (mkBS fp utf8len)
else do
fp' <- B.mallocByteString utf8len
unsafeWithForeignPtr fp' $ \ptr' -> do
B.memcpy ptr' ptr utf8len
return (mkBS fp' utf8len)
| Decode text from little endian UTF-16 encoding .
decodeUtf16LEWith :: OnDecodeError -> ByteString -> Text
decodeUtf16LEWith onErr bs = F.unstream (E.streamUtf16LE onErr bs)
# INLINE decodeUtf16LEWith #
| Decode text from little endian UTF-16 encoding .
--
If the input contains any invalid little endian UTF-16 data , an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf16LEWith'.
decodeUtf16LE :: ByteString -> Text
decodeUtf16LE = decodeUtf16LEWith strictDecode
# INLINE decodeUtf16LE #
-- | Decode text from big endian UTF-16 encoding.
decodeUtf16BEWith :: OnDecodeError -> ByteString -> Text
decodeUtf16BEWith onErr bs = F.unstream (E.streamUtf16BE onErr bs)
# INLINE decodeUtf16BEWith #
-- | Decode text from big endian UTF-16 encoding.
--
If the input contains any invalid big endian UTF-16 data , an
-- exception will be thrown. For more control over the handling of
invalid data , use ' decodeUtf16BEWith ' .
decodeUtf16BE :: ByteString -> Text
decodeUtf16BE = decodeUtf16BEWith strictDecode
# INLINE decodeUtf16BE #
| Encode text using little endian UTF-16 encoding .
encodeUtf16LE :: Text -> ByteString
encodeUtf16LE txt = E.unstream (E.restreamUtf16LE (F.stream txt))
# INLINE encodeUtf16LE #
-- | Encode text using big endian UTF-16 encoding.
encodeUtf16BE :: Text -> ByteString
encodeUtf16BE txt = E.unstream (E.restreamUtf16BE (F.stream txt))
# INLINE encodeUtf16BE #
-- | Decode text from little endian UTF-32 encoding.
decodeUtf32LEWith :: OnDecodeError -> ByteString -> Text
decodeUtf32LEWith onErr bs = F.unstream (E.streamUtf32LE onErr bs)
# INLINE decodeUtf32LEWith #
-- | Decode text from little endian UTF-32 encoding.
--
-- If the input contains any invalid little endian UTF-32 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf32LEWith'.
decodeUtf32LE :: ByteString -> Text
decodeUtf32LE = decodeUtf32LEWith strictDecode
# INLINE decodeUtf32LE #
-- | Decode text from big endian UTF-32 encoding.
decodeUtf32BEWith :: OnDecodeError -> ByteString -> Text
decodeUtf32BEWith onErr bs = F.unstream (E.streamUtf32BE onErr bs)
# INLINE decodeUtf32BEWith #
-- | Decode text from big endian UTF-32 encoding.
--
-- If the input contains any invalid big endian UTF-32 data, an
-- exception will be thrown. For more control over the handling of
-- invalid data, use 'decodeUtf32BEWith'.
decodeUtf32BE :: ByteString -> Text
decodeUtf32BE = decodeUtf32BEWith strictDecode
# INLINE decodeUtf32BE #
-- | Encode text using little endian UTF-32 encoding.
encodeUtf32LE :: Text -> ByteString
encodeUtf32LE txt = E.unstream (E.restreamUtf32LE (F.stream txt))
# INLINE encodeUtf32LE #
-- | Encode text using big endian UTF-32 encoding.
encodeUtf32BE :: Text -> ByteString
encodeUtf32BE txt = E.unstream (E.restreamUtf32BE (F.stream txt))
# INLINE encodeUtf32BE #
cSizeToInt :: CSize -> Int
cSizeToInt = fromIntegral
intToCSize :: Int -> CSize
intToCSize = fromIntegral
word16ToWord8 :: Word16 -> Word8
word16ToWord8 = fromIntegral
foreign import ccall unsafe "_hs_text_decode_utf8" c_decode_utf8
:: MutableByteArray# s -> Ptr CSize
-> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "_hs_text_decode_utf8_state" c_decode_utf8_with_state
:: MutableByteArray# s -> Ptr CSize
-> Ptr (Ptr Word8) -> Ptr Word8
-> Ptr CodePoint -> Ptr DecoderState -> IO (Ptr Word8)
foreign import ccall unsafe "_hs_text_decode_latin1" c_decode_latin1
:: MutableByteArray# s -> Ptr Word8 -> Ptr Word8 -> IO ()
foreign import ccall unsafe "_hs_text_encode_utf8" c_encode_utf8
:: Ptr (Ptr Word8) -> ByteArray# -> CSize -> CSize -> IO ()
| null | https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/91aa2806ea71b7a26add3801383b3133200971a5/test-project/text-nofusion/src/Data/Text/Encoding.hs | haskell | |
Module : Data.Text.Encoding
License : BSD-style
Maintainer :
Portability : portable
using several standard encodings.
To gain access to a much larger family of encodings, use the
<-icu text-icu package>.
$strict
** Controllable error handling
** Stream oriented decoding
$stream
$strict
All of the single-parameter functions for decoding bytestrings
input.
Each function has a variant, whose name is suffixed with -'With',
that gives greater control over the handling of decoding errors.
For instance, 'decodeUtf8' will throw an exception, but
'decodeUtf8With' allows the programmer to determine what to do on a
decoding error.
encoded text.
# DEPRECATED decodeASCII "Use decodeUtf8 instead" #
| Decode a 'ByteString' containing Latin-1 (aka ISO-8859-1) encoded text.
'decodeLatin1' is semantically equivalent to
@Data.Text.pack . Data.ByteString.Char8.unpack@
__NOTE__: The replacement character returned by 'OnDecodeError'
'error' (/since 1.2.3.1/); For earlier versions of @text@ using
those unsupported code points would result in undefined behavior.
TODO: The code currently assumes that the transcoded UTF-16
stream. To justify this assumption one has to assume that the
error handler replacement character also satisfies this
replacement characters in the error handler is to simply change
Another strategy would be to optimistically assume that
non-BMP replacement occurs reallocate the target buffer (or throw
Alternatively, `OnDecodeError` could become a datastructure which
statically encodes the replacement-character range,
e.g. something isomorphic to
replacement-character codepaths. There's multiple ways to address
this with different tradeoffs; but ideally we should optimise for
the optimistic/error-free case.
INLINE[0] decodeUtf8With #
$stream
The 'streamDecodeUtf8' and 'streamDecodeUtf8With' functions accept
a 'ByteString' that represents a possibly incomplete input (e.g. a
given input.
insufficient input.
be assumed to directly follow the string that was passed as
input to the original function, and it will in turn be decoded.
are split up on untidy boundaries: @[\"hi \\xe2\", \"\\x98\",
as we receive each one.
@
ghci> s0
'Some' \"hi \" \"\\xe2\" _
@
@
ghci> s1
'Some' \"\" \"\\xe2\\x98\"
@
We could not give @f0@ enough input to decode anything, so it
the last byte of input, it will make progress.
@
ghci> let s2\@('Some' _ _ f2) = f1 \"\\x83\"
ghci> s2
'Some' \"\\x2603\" \"\" _
@
If given invalid input, an exception will be thrown by the function
or continuation where it is encountered.
| A stream oriented decoding result.
encoded text that is known to be valid.
thrown (either by this function or a continuation) that cannot be
caught in pure code. For more control over the handling of invalid
data, use 'streamDecodeUtf8With'.
encoded text.
We create a slightly larger than necessary buffer to accommodate a
potential surrogate pair started in the last buffer (@undecoded0@), or
replacement characters for each byte in @undecoded0@ if the
We encountered an encoding error
If we can't complete the sequence @undecoded0@ from
the previous chunk, we invalidate the bytes from
@undecoded0@ and retry decoding the current chunk from
the initial state.
We encountered the end of the buffer while decoding
to be valid.
thrown that cannot be caught in pure code. For more control over
the handling of invalid data, use 'decodeUtf8'' or
'decodeUtf8With'.
# INLINE[0] decodeUtf8 #
exception will be returned, otherwise the decoded text.
# INLINE decodeUtf8' #
@since 1.1.0.0
a 'BP.BoundedPrim'.
Use this function is to implement efficient encoders for text-based formats
like JSON or HTML.
@since 1.1.0.0
# INLINE encodeUtf8BuilderEscaped #
manual eta-expansion to ensure inlining works as expected
exception will be thrown. For more control over the handling of
invalid data, use 'decodeUtf16LEWith'.
| Decode text from big endian UTF-16 encoding.
| Decode text from big endian UTF-16 encoding.
exception will be thrown. For more control over the handling of
| Encode text using big endian UTF-16 encoding.
| Decode text from little endian UTF-32 encoding.
| Decode text from little endian UTF-32 encoding.
If the input contains any invalid little endian UTF-32 data, an
exception will be thrown. For more control over the handling of
invalid data, use 'decodeUtf32LEWith'.
| Decode text from big endian UTF-32 encoding.
| Decode text from big endian UTF-32 encoding.
If the input contains any invalid big endian UTF-32 data, an
exception will be thrown. For more control over the handling of
invalid data, use 'decodeUtf32BEWith'.
| Encode text using little endian UTF-32 encoding.
| Encode text using big endian UTF-32 encoding. | # LANGUAGE BangPatterns , CPP , GeneralizedNewtypeDeriving , MagicHash ,
UnliftedFFITypes #
UnliftedFFITypes #-}
# LANGUAGE Trustworthy #
# LANGUAGE TypeApplications #
Copyright : ( c ) 2009 , 2010 , 2011 ,
( c ) 2009 ,
( c ) 2008 , 2009
Functions for converting ' Text ' values to and from ' ByteString ' ,
module Data.Text.Encoding
(
* Decoding ByteStrings to Text
decodeASCII
, decodeLatin1
, decodeUtf8
, decodeUtf16LE
, decodeUtf16BE
, decodeUtf32LE
, decodeUtf32BE
* * failure
, decodeUtf8'
, decodeUtf8With
, decodeUtf8Lenient
, decodeUtf16LEWith
, decodeUtf16BEWith
, decodeUtf32LEWith
, decodeUtf32BEWith
, streamDecodeUtf8
, streamDecodeUtf8With
, Decoding(..)
* Encoding Text to ByteStrings
, encodeUtf8
, encodeUtf16LE
, encodeUtf16BE
, encodeUtf32LE
, encodeUtf32BE
* Encoding Text using ByteString Builders
, encodeUtf8Builder
, encodeUtf8BuilderEscaped
) where
import Control.Monad.ST.Unsafe (unsafeIOToST, unsafeSTToIO)
import Control.Exception (evaluate, try, throwIO, ErrorCall(ErrorCall))
import Control.Monad.ST (runST)
import Data.Bits ((.&.), shiftR)
import Data.ByteString as B
import qualified Data.ByteString.Internal as B
import Data.Foldable (traverse_)
import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode, lenientDecode)
import Data.Text.Internal (Text(..), safe, text)
import Data.Text.Internal.Functions
import Data.Text.Internal.Private (runText)
import Data.Text.Internal.Unsafe.Char (ord, unsafeWrite)
import Data.Text.Show ()
import Data.Text.Unsafe (unsafeDupablePerformIO)
import Data.Word (Word8, Word16, Word32)
import Foreign.C.Types (CSize(CSize))
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr, minusPtr, nullPtr, plusPtr)
import Foreign.Storable (Storable, peek, poke)
import GHC.Base (ByteArray#, MutableByteArray#)
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Internal as B hiding (empty, append)
import qualified Data.ByteString.Builder.Prim as BP
import qualified Data.ByteString.Builder.Prim.Internal as BP
import qualified Data.Text.Array as A
import qualified Data.Text.Internal.Encoding.Fusion as E
import qualified Data.Text.Internal.Encoding.Utf16 as U16
import qualified Data.Text.Internal.Fusion as F
import Data.Text.Internal.ByteStringCompat
#if defined(ASSERTS)
import GHC.Stack (HasCallStack)
#endif
#include "text_cbits.h"
encoded in one of the Unicode Transformation Formats ( UTF ) operate
in a /strict/ mode : each will throw an exception if given invalid
| a ' ByteString ' containing 7 - bit ASCII
decodeASCII :: ByteString -> Text
decodeASCII = decodeUtf8
decodeLatin1 ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Text
decodeLatin1 bs = withBS bs aux where
aux fp len = text a 0 len
where
a = A.run (A.new len >>= unsafeIOToST . go)
go dest = unsafeWithForeignPtr fp $ \ptr -> do
c_decode_latin1 (A.maBA dest) ptr (ptr `plusPtr` len)
return dest
| Decode a ' ByteString ' containing UTF-8 encoded text .
MUST be within the BMP plane ; surrogate code points will
automatically be remapped to the replacement char @U+FFFD@
( /since 0.11.3.0/ ) , whereas code points beyond the BMP will throw an
decodeUtf8With ::
#if defined(ASSERTS)
HasCallStack =>
#endif
OnDecodeError -> ByteString -> Text
decodeUtf8With onErr bs = withBS bs aux
where
aux fp len = runText $ \done -> do
let go dest = unsafeWithForeignPtr fp $ \ptr ->
with (0::CSize) $ \destOffPtr -> do
let end = ptr `plusPtr` len
loop curPtr = do
curPtr' <- c_decode_utf8 (A.maBA dest) destOffPtr curPtr end
if curPtr' == end
then do
n <- peek destOffPtr
unsafeSTToIO (done dest (cSizeToInt n))
else do
x <- peek curPtr'
case onErr desc (Just x) of
Nothing -> loop $ curPtr' `plusPtr` 1
Just c
| c > '\xFFFF' -> throwUnsupportedReplChar
| otherwise -> do
destOff <- peek destOffPtr
w <- unsafeSTToIO $
unsafeWrite dest (cSizeToInt destOff)
(safe c)
poke destOffPtr (destOff + intToCSize w)
loop $ curPtr' `plusPtr` 1
loop ptr
(unsafeIOToST . go) =<< A.new len
where
desc = "Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream"
throwUnsupportedReplChar = throwIO $
ErrorCall "decodeUtf8With: non-BMP replacement characters not supported"
stream is at most twice as long ( in bytes ) as the input UTF-8
invariant , by emitting at most one UTF16 code unit .
One easy way to support the full range of code - points for
the ( over-)allocation to ` A.new ( 2*len ) ` and then shrink back the
` ByteArray # ` to the real size ( recent GHCs have a cheap
` ByteArray # ` resize - primop for that which allow the GC to reclaim
the overallocation ) . However , this would require 4 times as much
( temporary ) storage as the original UTF-8 required .
replacement characters are within the BMP , and if the case of a
an exception , and fallback to a pessimistic codepath , like e.g.
` decodeUtf8With onErr bs = F.unstream ( E.streamUtf8 onErr bs ) ` )
Either ( ... - > Maybe ) ( ... - > Maybe )
And allow to statically switch between the BMP / non - BMP
packet from a network stream ) that may not end on a UTF-8 boundary .
1 . The maximal prefix of ' Text ' that could be decoded from the
2 . The suffix of the ' ByteString ' that could not be decoded due to
3 . A function that accepts another ' ByteString ' . That string will
To help understand the use of these functions , consider the Unicode
string @\"hi & # 9731;\"@. If encoded as UTF-8 , this becomes @\"hi
\\xe2\\x98\\x83\"@ ; the final @\'☃\'@ is encoded as 3 bytes .
Now suppose that we receive this encoded string as 3 packets that
\"\\x83\"]@. We can not decode the entire Unicode string until we
have received all three packets , but we would like to make progress
ghci > let ' _ _ f0 ) = ' streamDecodeUtf8 ' \"hi \\xe2\ "
We use the continuation @f0@ to decode our second packet .
ghci > let s1\@('Some ' _ _ f1 ) = f0 \"\\x98\ "
returned an empty string . Once we feed our second continuation
@since 1.0.0.0
data Decoding = Some Text ByteString (ByteString -> Decoding)
instance Show Decoding where
showsPrec d (Some t bs _) = showParen (d > prec) $
showString "Some " . showsPrec prec' t .
showChar ' ' . showsPrec prec' bs .
showString " _"
where prec = 10; prec' = prec + 1
newtype CodePoint = CodePoint Word32 deriving (Eq, Show, Num, Storable)
newtype DecoderState = DecoderState Word32 deriving (Eq, Show, Num, Storable)
| Decode , in a stream oriented way , a ' ByteString ' containing UTF-8
If the input contains any invalid UTF-8 data , an exception will be
@since 1.0.0.0
streamDecodeUtf8 ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Decoding
streamDecodeUtf8 = streamDecodeUtf8With strictDecode
| Decode , in a stream oriented way , a lazy ' ByteString ' containing UTF-8
@since 1.0.0.0
streamDecodeUtf8With ::
#if defined(ASSERTS)
HasCallStack =>
#endif
OnDecodeError -> ByteString -> Decoding
streamDecodeUtf8With onErr = decodeChunk B.empty 0 0
where
sequence turns out to be invalid . There can be up to three bytes there ,
hence we allocate @len+3@ 16 - bit words .
decodeChunk :: ByteString -> CodePoint -> DecoderState -> ByteString
-> Decoding
decodeChunk undecoded0 codepoint0 state0 bs = withBS bs aux where
aux fp len = runST $ (unsafeIOToST . decodeChunkToBuffer) =<< A.new (len+3)
where
decodeChunkToBuffer :: A.MArray s -> IO Decoding
decodeChunkToBuffer dest = unsafeWithForeignPtr fp $ \ptr ->
with (0::CSize) $ \destOffPtr ->
with codepoint0 $ \codepointPtr ->
with state0 $ \statePtr ->
with nullPtr $ \curPtrPtr ->
let end = ptr `plusPtr` len
loop curPtr = do
prevState <- peek statePtr
poke curPtrPtr curPtr
lastPtr <- c_decode_utf8_with_state (A.maBA dest) destOffPtr
curPtrPtr end codepointPtr statePtr
state <- peek statePtr
case state of
UTF8_REJECT -> do
poke statePtr 0
let skipByte x = case onErr desc (Just x) of
Nothing -> return ()
Just c -> do
destOff <- peek destOffPtr
w <- unsafeSTToIO $
unsafeWrite dest (cSizeToInt destOff) (safe c)
poke destOffPtr (destOff + intToCSize w)
if ptr == lastPtr && prevState /= UTF8_ACCEPT then do
traverse_ skipByte (B.unpack undecoded0 )
loop lastPtr
else do
peek lastPtr >>= skipByte
loop (lastPtr `plusPtr` 1)
_ -> do
n <- peek destOffPtr
codepoint <- peek codepointPtr
chunkText <- unsafeSTToIO $ do
arr <- A.unsafeFreeze dest
return $! text arr 0 (cSizeToInt n)
let left = lastPtr `minusPtr` ptr
!undecoded = case state of
UTF8_ACCEPT -> B.empty
_ | left == 0 && prevState /= UTF8_ACCEPT -> B.append undecoded0 bs
| otherwise -> B.drop left bs
return $ Some chunkText undecoded
(decodeChunk undecoded codepoint state)
in loop ptr
desc = "Data.Text.Internal.Encoding.streamDecodeUtf8With: Invalid UTF-8 stream"
| Decode a ' ByteString ' containing UTF-8 encoded text that is known
If the input contains any invalid UTF-8 data , an exception will be
decodeUtf8 :: ByteString -> Text
decodeUtf8 = decodeUtf8With strictDecode
| Decode a ' ByteString ' containing UTF-8 encoded text .
If the input contains any invalid UTF-8 data , the relevant
decodeUtf8' ::
#if defined(ASSERTS)
HasCallStack =>
#endif
ByteString -> Either UnicodeException Text
decodeUtf8' = unsafeDupablePerformIO . try . evaluate . decodeUtf8With strictDecode
| Decode a ' ByteString ' containing UTF-8 encoded text .
Any invalid input bytes will be replaced with the Unicode replacement
character U+FFFD .
decodeUtf8Lenient :: ByteString -> Text
decodeUtf8Lenient = decodeUtf8With lenientDecode
| Encode text to a ByteString ' B.Builder ' using UTF-8 encoding .
encodeUtf8Builder :: Text -> B.Builder
encodeUtf8Builder = encodeUtf8BuilderEscaped (BP.liftFixedToBounded BP.word8)
| Encode text using UTF-8 encoding and escape the ASCII characters using
TODO : Extend documentation with references to source code in @blaze - html@
or @aeson@ that uses this function .
encodeUtf8BuilderEscaped :: BP.BoundedPrim Word8 -> Text -> B.Builder
encodeUtf8BuilderEscaped be =
\txt -> B.builder (mkBuildstep txt)
where
bound = max 4 $ BP.sizeBound be
mkBuildstep (Text arr off len) !k =
outerLoop off
where
iend = off + len
outerLoop !i0 !br@(B.BufferRange op0 ope)
| i0 >= iend = k br
| outRemaining > 0 = goPartial (i0 + min outRemaining inpRemaining)
TODO : Use a loop with an integrated bound 's check if outRemaining
is smaller than 8 , as this will save on divisions .
| otherwise = return $ B.bufferFull bound op0 (outerLoop i0)
where
outRemaining = (ope `minusPtr` op0) `div` bound
inpRemaining = iend - i0
goPartial !iendTmp = go i0 op0
where
go !i !op
| i < iendTmp = case A.unsafeIndex arr i of
w | w <= 0x7F -> do
BP.runB be (word16ToWord8 w) op >>= go (i + 1)
| w <= 0x7FF -> do
poke8 @Word16 0 $ (w `shiftR` 6) + 0xC0
poke8 @Word16 1 $ (w .&. 0x3f) + 0x80
go (i + 1) (op `plusPtr` 2)
| 0xD800 <= w && w <= 0xDBFF -> do
let c = ord $ U16.chr2 w (A.unsafeIndex arr (i+1))
poke8 @Int 0 $ (c `shiftR` 18) + 0xF0
poke8 @Int 1 $ ((c `shiftR` 12) .&. 0x3F) + 0x80
poke8 @Int 2 $ ((c `shiftR` 6) .&. 0x3F) + 0x80
poke8 @Int 3 $ (c .&. 0x3F) + 0x80
go (i + 2) (op `plusPtr` 4)
| otherwise -> do
poke8 @Word16 0 $ (w `shiftR` 12) + 0xE0
poke8 @Word16 1 $ ((w `shiftR` 6) .&. 0x3F) + 0x80
poke8 @Word16 2 $ (w .&. 0x3F) + 0x80
go (i + 1) (op `plusPtr` 3)
| otherwise =
outerLoop i (B.BufferRange op ope)
where
Take care , a is either above
poke8 :: Integral a => Int -> a -> IO ()
poke8 j v = poke (op `plusPtr` j) (fromIntegral v :: Word8)
| Encode text using UTF-8 encoding .
encodeUtf8 :: Text -> ByteString
encodeUtf8 (Text arr off len)
| len == 0 = B.empty
| otherwise = unsafeDupablePerformIO $ do
see for why is enough
unsafeWithForeignPtr fp $ \ptr ->
with ptr $ \destPtr -> do
c_encode_utf8 destPtr (A.aBA arr) (intToCSize off) (intToCSize len)
newDest <- peek destPtr
let utf8len = newDest `minusPtr` ptr
if utf8len >= len `shiftR` 1
then return (mkBS fp utf8len)
else do
fp' <- B.mallocByteString utf8len
unsafeWithForeignPtr fp' $ \ptr' -> do
B.memcpy ptr' ptr utf8len
return (mkBS fp' utf8len)
| Decode text from little endian UTF-16 encoding .
decodeUtf16LEWith :: OnDecodeError -> ByteString -> Text
decodeUtf16LEWith onErr bs = F.unstream (E.streamUtf16LE onErr bs)
# INLINE decodeUtf16LEWith #
| Decode text from little endian UTF-16 encoding .
If the input contains any invalid little endian UTF-16 data , an
decodeUtf16LE :: ByteString -> Text
decodeUtf16LE = decodeUtf16LEWith strictDecode
# INLINE decodeUtf16LE #
decodeUtf16BEWith :: OnDecodeError -> ByteString -> Text
decodeUtf16BEWith onErr bs = F.unstream (E.streamUtf16BE onErr bs)
# INLINE decodeUtf16BEWith #
If the input contains any invalid big endian UTF-16 data , an
invalid data , use ' decodeUtf16BEWith ' .
decodeUtf16BE :: ByteString -> Text
decodeUtf16BE = decodeUtf16BEWith strictDecode
# INLINE decodeUtf16BE #
| Encode text using little endian UTF-16 encoding .
encodeUtf16LE :: Text -> ByteString
encodeUtf16LE txt = E.unstream (E.restreamUtf16LE (F.stream txt))
# INLINE encodeUtf16LE #
encodeUtf16BE :: Text -> ByteString
encodeUtf16BE txt = E.unstream (E.restreamUtf16BE (F.stream txt))
# INLINE encodeUtf16BE #
decodeUtf32LEWith :: OnDecodeError -> ByteString -> Text
decodeUtf32LEWith onErr bs = F.unstream (E.streamUtf32LE onErr bs)
# INLINE decodeUtf32LEWith #
decodeUtf32LE :: ByteString -> Text
decodeUtf32LE = decodeUtf32LEWith strictDecode
# INLINE decodeUtf32LE #
decodeUtf32BEWith :: OnDecodeError -> ByteString -> Text
decodeUtf32BEWith onErr bs = F.unstream (E.streamUtf32BE onErr bs)
# INLINE decodeUtf32BEWith #
decodeUtf32BE :: ByteString -> Text
decodeUtf32BE = decodeUtf32BEWith strictDecode
# INLINE decodeUtf32BE #
encodeUtf32LE :: Text -> ByteString
encodeUtf32LE txt = E.unstream (E.restreamUtf32LE (F.stream txt))
# INLINE encodeUtf32LE #
encodeUtf32BE :: Text -> ByteString
encodeUtf32BE txt = E.unstream (E.restreamUtf32BE (F.stream txt))
# INLINE encodeUtf32BE #
cSizeToInt :: CSize -> Int
cSizeToInt = fromIntegral
intToCSize :: Int -> CSize
intToCSize = fromIntegral
word16ToWord8 :: Word16 -> Word8
word16ToWord8 = fromIntegral
foreign import ccall unsafe "_hs_text_decode_utf8" c_decode_utf8
:: MutableByteArray# s -> Ptr CSize
-> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "_hs_text_decode_utf8_state" c_decode_utf8_with_state
:: MutableByteArray# s -> Ptr CSize
-> Ptr (Ptr Word8) -> Ptr Word8
-> Ptr CodePoint -> Ptr DecoderState -> IO (Ptr Word8)
foreign import ccall unsafe "_hs_text_decode_latin1" c_decode_latin1
:: MutableByteArray# s -> Ptr Word8 -> Ptr Word8 -> IO ()
foreign import ccall unsafe "_hs_text_encode_utf8" c_encode_utf8
:: Ptr (Ptr Word8) -> ByteArray# -> CSize -> CSize -> IO ()
|
bb067cf9c55f03eace1ccbee384ae6d53da54e2b5c929046836c56ac6e4f799a | arttuka/reagent-material-ui | medical_information_outlined.cljs | (ns reagent-mui.icons.medical-information-outlined
"Imports @mui/icons-material/MedicalInformationOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def medical-information-outlined (create-svg-icon (e "path" #js {"d" "M20 7h-5V4c0-1.1-.9-2-2-2h-2c-1.1 0-2 .9-2 2v3H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm-9-3h2v5h-2V4zm9 16H4V9h5c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2h5v11zm-9-4H9v2H7v-2H5v-2h2v-2h2v2h2v2zm2-1.5V13h6v1.5h-6zm0 3V16h4v1.5h-4z"})
"MedicalInformationOutlined"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/medical_information_outlined.cljs | clojure | (ns reagent-mui.icons.medical-information-outlined
"Imports @mui/icons-material/MedicalInformationOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def medical-information-outlined (create-svg-icon (e "path" #js {"d" "M20 7h-5V4c0-1.1-.9-2-2-2h-2c-1.1 0-2 .9-2 2v3H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm-9-3h2v5h-2V4zm9 16H4V9h5c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2h5v11zm-9-4H9v2H7v-2H5v-2h2v-2h2v2h2v2zm2-1.5V13h6v1.5h-6zm0 3V16h4v1.5h-4z"})
"MedicalInformationOutlined"))
| |
78333cdf0b3536a0d6c586e08b73f7fc9a0de6e166b4eca34d7a38c81d694232 | yangchenyun/learning-sicp | prisoner.scm | ;;
The play - loop procedure takes as its arguments two prisoner 's
;; dilemma strategies, and plays an iterated game of approximately
one hundred rounds . A strategy is a procedure that takes
two arguments : a history of the player 's previous plays and
;; a history of the other player's previous plays. The procedure
;; returns either a "c" for cooperate or a "d" for defect.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (play-loop strat0 strat1)
(define (play-loop-iter strat0 strat1 count history0 history1 limit)
(cond ((= count limit) (print-out-results history0 history1 limit))
(else (let ((result0 (strat0 history0 history1))
(result1 (strat1 history1 history0)))
(play-loop-iter strat0 strat1 (+ count 1)
(extend-history result0 history0)
(extend-history result1 history1)
limit)))))
(play-loop-iter strat0 strat1 0 the-empty-history the-empty-history
(+ 90 (random 21))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; The following procedures are used to compute and print
;; out the players' scores at the end of an iterated game
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (print-out-results history0 history1 number-of-games)
(let ((scores (get-scores history0 history1)))
(newline)
(display "Player 1 Score: ")
(display (* 1.0 (/ (car scores) number-of-games)))
(newline)
(display "Player 2 Score: ")
(display (* 1.0 (/ (cadr scores) number-of-games)))
(newline)))
(define (get-scores history0 history1)
(define (get-scores-helper history0 history1 score0 score1)
(cond ((empty-history? history0)
(list score0 score1))
(else (let ((game (make-play (most-recent-play history0)
(most-recent-play history1))))
(get-scores-helper (rest-of-plays history0)
(rest-of-plays history1)
(+ (get-player-points 0 game) score0)
(+ (get-player-points 1 game) score1))))))
(get-scores-helper history0 history1 0 0))
(define (get-player-points num game)
(list-ref (get-point-list game) num))
(define *game-association-list*
format is that first sublist identifies the players ' choices
with " c " for cooperate and " d " for defect ; and that second sublist
;; specifies payout for each player
'((("c" "c") (3 3))
(("c" "d") (0 5))
(("d" "c") (5 0))
(("d" "d") (1 1))))
(define (get-point-list game)
(cadr (extract-entry game *game-association-list*)))
;; note that you will need to write extract-entry
(define make-play list)
(define the-empty-history '())
(define extend-history cons)
(define empty-history? null?)
(define most-recent-play car)
(define rest-of-plays cdr)
;; A sampler of strategies
(define (NASTY my-history other-history)
"d")
(define (PATSY my-history other-history)
"c")
(define (SPASTIC my-history other-history)
(if (= (random 2) 0)
"c"
"d"))
(define (EGALITARIAN my-history other-history)
(define (count-instances-of test hist)
(cond ((empty-history? hist) 0)
((string=? (most-recent-play hist) test)
(+ (count-instances-of test (rest-of-plays hist)) 1))
(else (count-instances-of test (rest-of-plays hist)))))
(let ((ds (count-instances-of "d" other-history))
(cs (count-instances-of "c" other-history)))
(if (> ds cs) "d" "c")))
(define (EYE-FOR-EYE my-history other-history)
(if (empty-history? my-history)
"c"
(most-recent-play other-history)))
;;;;;;;;;;;;;;;;;;;;;;;;;
;;
code to use in 3 player game
;;
;(define *game-association-list*
( list ( list ( list " c " " c " " c " ) ( list 4 4 4 ) )
( list ( list " c " " c " " d " ) ( list 2 2 5 ) )
( list ( list " c " " d " " c " ) ( list 2 5 2 ) )
( list ( list " d " " c " " c " ) ( list 5 2 2 ) )
( list ( list " c " " d " " d " ) ( list 0 3 3 ) )
( list ( list " d " " c " " d " ) ( list 3 0 3 ) )
( list ( list " d " " d " " c " ) ( list 3 3 0 ) )
; (list (list "d" "d" "d") (list 1 1 1))))
;; in expected-values: #f = don't care
;; X = actual-value needs to be #f or X
;(define (test-entry expected-values actual-values)
; (cond ((null? expected-values) (null? actual-values))
; ((null? actual-values) #f)
; ((or (not (car expected-values))
; (not (car actual-values))
; (= (car expected-values) (car actual-values)))
; (test-entry (cdr expected-values) (cdr actual-values)))
; (else #f)))
;
( define ( is - he - a - fool ? )
; (test-entry (list 1 1 1)
; (get-probability-of-c
( make - history - summary ) ) ) )
;
( define ( could - he - be - a - fool ? )
; (test-entry (list 1 1 1)
; (map (lambda (elt)
( cond ( ( null ? elt ) 1 )
( (= elt 1 ) 1 )
; (else 0)))
( get - probability - of - c ( make - history - summary
; hist1
; hist2)))))
| null | https://raw.githubusercontent.com/yangchenyun/learning-sicp/99a19a06eddc282e0eb364536e297f27c32a9145/practices/projects/project2/prisoner.scm | scheme |
dilemma strategies, and plays an iterated game of approximately
a history of the other player's previous plays. The procedure
returns either a "c" for cooperate or a "d" for defect.
The following procedures are used to compute and print
out the players' scores at the end of an iterated game
and that second sublist
specifies payout for each player
note that you will need to write extract-entry
A sampler of strategies
(define *game-association-list*
(list (list "d" "d" "d") (list 1 1 1))))
in expected-values: #f = don't care
X = actual-value needs to be #f or X
(define (test-entry expected-values actual-values)
(cond ((null? expected-values) (null? actual-values))
((null? actual-values) #f)
((or (not (car expected-values))
(not (car actual-values))
(= (car expected-values) (car actual-values)))
(test-entry (cdr expected-values) (cdr actual-values)))
(else #f)))
(test-entry (list 1 1 1)
(get-probability-of-c
(test-entry (list 1 1 1)
(map (lambda (elt)
(else 0)))
hist1
hist2))))) | The play - loop procedure takes as its arguments two prisoner 's
one hundred rounds . A strategy is a procedure that takes
two arguments : a history of the player 's previous plays and
(define (play-loop strat0 strat1)
(define (play-loop-iter strat0 strat1 count history0 history1 limit)
(cond ((= count limit) (print-out-results history0 history1 limit))
(else (let ((result0 (strat0 history0 history1))
(result1 (strat1 history1 history0)))
(play-loop-iter strat0 strat1 (+ count 1)
(extend-history result0 history0)
(extend-history result1 history1)
limit)))))
(play-loop-iter strat0 strat1 0 the-empty-history the-empty-history
(+ 90 (random 21))))
(define (print-out-results history0 history1 number-of-games)
(let ((scores (get-scores history0 history1)))
(newline)
(display "Player 1 Score: ")
(display (* 1.0 (/ (car scores) number-of-games)))
(newline)
(display "Player 2 Score: ")
(display (* 1.0 (/ (cadr scores) number-of-games)))
(newline)))
(define (get-scores history0 history1)
(define (get-scores-helper history0 history1 score0 score1)
(cond ((empty-history? history0)
(list score0 score1))
(else (let ((game (make-play (most-recent-play history0)
(most-recent-play history1))))
(get-scores-helper (rest-of-plays history0)
(rest-of-plays history1)
(+ (get-player-points 0 game) score0)
(+ (get-player-points 1 game) score1))))))
(get-scores-helper history0 history1 0 0))
(define (get-player-points num game)
(list-ref (get-point-list game) num))
(define *game-association-list*
format is that first sublist identifies the players ' choices
'((("c" "c") (3 3))
(("c" "d") (0 5))
(("d" "c") (5 0))
(("d" "d") (1 1))))
(define (get-point-list game)
(cadr (extract-entry game *game-association-list*)))
(define make-play list)
(define the-empty-history '())
(define extend-history cons)
(define empty-history? null?)
(define most-recent-play car)
(define rest-of-plays cdr)
(define (NASTY my-history other-history)
"d")
(define (PATSY my-history other-history)
"c")
(define (SPASTIC my-history other-history)
(if (= (random 2) 0)
"c"
"d"))
(define (EGALITARIAN my-history other-history)
(define (count-instances-of test hist)
(cond ((empty-history? hist) 0)
((string=? (most-recent-play hist) test)
(+ (count-instances-of test (rest-of-plays hist)) 1))
(else (count-instances-of test (rest-of-plays hist)))))
(let ((ds (count-instances-of "d" other-history))
(cs (count-instances-of "c" other-history)))
(if (> ds cs) "d" "c")))
(define (EYE-FOR-EYE my-history other-history)
(if (empty-history? my-history)
"c"
(most-recent-play other-history)))
code to use in 3 player game
( list ( list ( list " c " " c " " c " ) ( list 4 4 4 ) )
( list ( list " c " " c " " d " ) ( list 2 2 5 ) )
( list ( list " c " " d " " c " ) ( list 2 5 2 ) )
( list ( list " d " " c " " c " ) ( list 5 2 2 ) )
( list ( list " c " " d " " d " ) ( list 0 3 3 ) )
( list ( list " d " " c " " d " ) ( list 3 0 3 ) )
( list ( list " d " " d " " c " ) ( list 3 3 0 ) )
( define ( is - he - a - fool ? )
( make - history - summary ) ) ) )
( define ( could - he - be - a - fool ? )
( cond ( ( null ? elt ) 1 )
( (= elt 1 ) 1 )
( get - probability - of - c ( make - history - summary
|
778a69e88625acfea6a4711560aaad002b4544b65a85a17590a30c8f5f80c498 | Kakadu/fp2022 | result.ml | * Copyright 2022 - 2023 ,
* SPDX - License - Identifier : LGPL-3.0 - or - later
type environment = (Ast.id, value, Base.String.comparator_witness) Base.Map.t
and rec_flag =
| Recursive
| NonRecursive
and value =
* 5
| VString of string (** "apple" *)
| VBool of bool (** true *)
| VChar of char (** 'a' *)
| VUnit (** () *)
* [ 1 ; 2 ; 3 ]
* ( " abc " , 123 , false )
| VFun of Ast.id list * Ast.expr * environment * rec_flag (** fun x -> x * x *)
type error =
[ `UnboundValue of string (** Unbound value *)
| `Unreachable
(** Unreachable code. If this error is thrown then there is a bug in typechecker *)
| `UnsupportedOperation (** Used unsupported operation *)
| `DivisionByZero (** n / 0*)
| `MisusedWildcard (** Wildcard is in the right-hand expression *)
| `PatternMatchingFailed (** The case is not matched *)
| `NonExhaustivePatternMatching (** Pattern-matching is not exhaustive *)
]
let rec pp_value fmt =
let open Format in
let pp_list fmt delimiter =
pp_print_list
~pp_sep:(fun fmt _ -> fprintf fmt delimiter)
(fun fmt value -> pp_value fmt value)
fmt
in
function
| VInt value -> fprintf fmt "%d" value
| VChar value -> fprintf fmt "%C" value
| VBool value -> fprintf fmt "%B" value
| VString value -> fprintf fmt "%S" value
| VUnit -> fprintf fmt "()"
| VList list -> fprintf fmt "[%a]" (fun fmt -> pp_list fmt ", ") list
| VTuple tuple -> fprintf fmt "(%a)" (fun fmt -> pp_list fmt ", ") tuple
| VFun _ -> fprintf fmt "<fun>"
;;
let print_value = Format.printf "%a\n" pp_value
let pp_error fmt (err : error) =
let open Format in
match err with
| `UnboundValue name -> fprintf fmt "Runtime error: unbound value %s." name
| `Unreachable ->
fprintf
fmt
"This code is supposed to be unreachable. If this error is thrown then there is a \
bug in typechecker. "
| `UnsupportedOperation -> fprintf fmt "Runtime error: unsupported operation."
| `DivisionByZero -> fprintf fmt "Runtime error: division by zero."
| `MisusedWildcard ->
fprintf
fmt
"Runtime error: wildcard must not appear on the right-hand side of an expression."
| `PatternMatchingFailed -> fprintf fmt "Runtime error: pattern-matching failed."
| `NonExhaustivePatternMatching ->
fprintf fmt "Runtime error: this pattern-matching is not exhaustive."
;;
let print_error = Format.printf "%a" pp_error
| null | https://raw.githubusercontent.com/Kakadu/fp2022/836230c8130be216d8008c96249b42828b240d7e/SMLEqTypesValRestr/lib/result.ml | ocaml | * "apple"
* true
* 'a'
* ()
* fun x -> x * x
* Unbound value
* Unreachable code. If this error is thrown then there is a bug in typechecker
* Used unsupported operation
* n / 0
* Wildcard is in the right-hand expression
* The case is not matched
* Pattern-matching is not exhaustive | * Copyright 2022 - 2023 ,
* SPDX - License - Identifier : LGPL-3.0 - or - later
type environment = (Ast.id, value, Base.String.comparator_witness) Base.Map.t
and rec_flag =
| Recursive
| NonRecursive
and value =
* 5
* [ 1 ; 2 ; 3 ]
* ( " abc " , 123 , false )
type error =
| `Unreachable
]
let rec pp_value fmt =
let open Format in
let pp_list fmt delimiter =
pp_print_list
~pp_sep:(fun fmt _ -> fprintf fmt delimiter)
(fun fmt value -> pp_value fmt value)
fmt
in
function
| VInt value -> fprintf fmt "%d" value
| VChar value -> fprintf fmt "%C" value
| VBool value -> fprintf fmt "%B" value
| VString value -> fprintf fmt "%S" value
| VUnit -> fprintf fmt "()"
| VList list -> fprintf fmt "[%a]" (fun fmt -> pp_list fmt ", ") list
| VTuple tuple -> fprintf fmt "(%a)" (fun fmt -> pp_list fmt ", ") tuple
| VFun _ -> fprintf fmt "<fun>"
;;
let print_value = Format.printf "%a\n" pp_value
let pp_error fmt (err : error) =
let open Format in
match err with
| `UnboundValue name -> fprintf fmt "Runtime error: unbound value %s." name
| `Unreachable ->
fprintf
fmt
"This code is supposed to be unreachable. If this error is thrown then there is a \
bug in typechecker. "
| `UnsupportedOperation -> fprintf fmt "Runtime error: unsupported operation."
| `DivisionByZero -> fprintf fmt "Runtime error: division by zero."
| `MisusedWildcard ->
fprintf
fmt
"Runtime error: wildcard must not appear on the right-hand side of an expression."
| `PatternMatchingFailed -> fprintf fmt "Runtime error: pattern-matching failed."
| `NonExhaustivePatternMatching ->
fprintf fmt "Runtime error: this pattern-matching is not exhaustive."
;;
let print_error = Format.printf "%a" pp_error
|
f4d1efaff0ebce14417ddfe944afb3b716b42a8e3d0797e7716b39639788c4e4 | CyberCat-Institute/open-game-engine | AndGateMarkovMC.hs | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE LambdaCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
{-# LANGUAGE GADTs #-}
module Examples.Staking.AndGateMarkovMC where
import Debug.Trace
import OpenGames hiding (fromLens,Agent,fromFunctions,discount,nature)
import OpenGames.Engine.IOGames
import OpenGames.Engine.BayesianGames (uniformDist, playDeterministically)
import OpenGames.Preprocessor
import Control.Arrow (Kleisli(..))
import Control.Monad.State hiding (state, void, lift)
import qualified Control.Monad.State as ST
import qualified Data.Vector as V
import Numeric.Probability.Distribution hiding (map, lift, filter)
import System.Random.MWC.CondensedTable
import System.Random
import System.Random.Stateful
TODO change the structure of the continuation iteration
-- DONE What effect happens through the state hack and the discounting? The discounting at least does not seem to make a difference.
--------
-- Types
andGateMarkovTestParams = AndGateMarkovParams {
sampleSize1 = 100,
sampleSize2 = 100,
sampleSize3 = 100,
sampleSizeA = 100,
reward = 1.0,
costOfCapital = 0.05,
minBribe = 0.0,
maxBribe = 5.0,
incrementBribe = 1.0,
maxSuccessfulAttackPayoff = 1000.0,
attackerProbability = 0.001,
penalty = 0.5,
minDeposit = 0.0,
maxDeposit = 10.0,
incrementDeposit = 1,
epsilon = 0.001,
discountFactor = 0.5
}
data AndGateMarkovParams = AndGateMarkovParams {
sampleSize1 :: Int,
sampleSize2 :: Int,
sampleSize3 :: Int,
sampleSizeA :: Int,
reward :: Double,
costOfCapital :: Double,
minBribe :: Double,
maxBribe :: Double,
incrementBribe :: Double,
maxSuccessfulAttackPayoff :: Double,
attackerProbability :: Double,
penalty :: Double,
minDeposit :: Double,
maxDeposit :: Double,
incrementDeposit :: Double,
epsilon :: Double,
discountFactor :: Double
}
data MessageType = Bool | Double
---------------------
Auxilary functions
attackerPayoff :: [Bool] -> Double -> Double -> Double
attackerPayoff bribesAccepted bribe successfulAttackPayoff
| (numBribed == numPlayers) = successfulAttackPayoff - bribe*(fromIntegral numBribed)
| (otherwise) = -bribe*(fromIntegral numBribed)
where numPlayers = length bribesAccepted
numBribed = length (filter id bribesAccepted)
obfuscateAndGate :: [Bool] -> Bool
obfuscateAndGate = and
successfulAttackPayoffDistribution :: Double -> Double -> CondensedTableV Double
successfulAttackPayoffDistribution attackerProbability maxSuccessfulAttackPayoff
| (attackerProbability == 0) = tableFromProbabilities $ V.fromList [(0,0)]
| (attackerProbability == 1) = tableFromProbabilities $ V.fromList [(maxSuccessfulAttackPayoff,1)]
| (otherwise) = tableFromProbabilities $ V.fromList [(0, 1-attackerProbability), (maxSuccessfulAttackPayoff, attackerProbability)]
payoffAndGate :: Double -> Double -> [Double] -> Bool -> [Double]
payoffAndGate penalty reward deposits True
| (sumDeposits > 0) = [deposit*reward/sumDeposits | deposit <- deposits]
| (sumDeposits == 0) = [0 | _ <- deposits]
where sumDeposits = sum deposits
payoffAndGate penalty reward deposits False
= [-penalty*deposit | deposit <- deposits]
andGateTestPrior = do
deposits <- uniformDist [replicate 3 x | x <- [0.0, 1.0 .. 10.0]]
andResults <- uniformDist [True, False]
return (deposits, andResults)
--------
-- Games
depositStagePlayer name sampleSize minDeposit maxDeposit incrementDeposit epsilon = [opengame|
inputs : summaryStatistic, costOfCapital ;
:---:
inputs : summaryStatistic, costOfCapital ;
operation : dependentDecisionIO name sampleSize [minDeposit, minDeposit + incrementDeposit .. maxDeposit] ;
outputs : deposit ;
returns : (-deposit) * costOfCapital ;
:---:
outputs : deposit ;
|]
playingStagePlayer name sampleSize moves = [opengame|
inputs : summaryStatistic, observation, bribe ;
:---:
inputs : summaryStatistic, observation, bribe ;
operation : dependentDecisionIO name sampleSize moves ;
outputs : move ;
returns : payoff + if bribePaid then bribe else 0 ;
:---:
outputs : move ;
returns : payoff, bribePaid ;
|]
stakingRound sampleSizeP1 sampleSizeP2 sampleSizeP3 costOfCapital minDeposit maxDeposit incrementDeposit epsilon = [opengame|
inputs : summaryStatistic ;
:---:
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player1" sampleSizeP1 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit1 ;
returns : ;
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player2" sampleSizeP2 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit2 ;
returns : ;
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player3" sampleSizeP3 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit3 ;
returns : ;
inputs : deposit1,deposit2,deposit3 ;
operation : fromFunctions (\(x,y,z) -> [x,y,z]) id ;
outputs: deposits ;
:---:
outputs: deposits ;
|]
indexLs = (!!)
nothing = 0.0
playingRound :: Int
-> Int
-> Int
-> OpenGame
MonadOptic
MonadContext
('[Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool]
)
('[IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)])
(([Double],Bool), [Double], Double)
()
[Bool]
[(Double, Bool)]
playingRound sampleSizeP1 sampleSizeP2 sampleSizeP3= [opengame|
inputs : (summaryStatistic, deposits, bribe) ;
:---:
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player1" sampleSizeP1 [True, False] ;
outputs : move1 ;
returns : indexLs lsPayBribes 0 ;
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player2" sampleSizeP2 [True, False] ;
outputs : move2 ;
returns : indexLs lsPayBribes 1 ;
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player3" sampleSizeP3 [True, False] ;
outputs : move3 ;
returns : indexLs lsPayBribes 2 ;
inputs : move1,move2,move3 ;
operation : fromFunctions (\(x,y,z) -> [x,y,z]) id ;
outputs: moves ;
:---:
outputs : moves ;
returns : lsPayBribes ;
|]
discountingStage discountFactor = [opengame|
inputs : ;
:---:
operation : discount "Player1" (\x -> x * discountFactor) ;
operation : discount "Player2" (\x -> x * discountFactor) ;
operation : discount "Player3" (\x -> x * discountFactor) ;
operation : discount "Attacker" (\x -> x * discountFactor) ;
:---:
outputs : ;
|]
andGateGame :: AndGateMarkovParams
-> OpenGame
MonadOptic
MonadContext
('[Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV ([Double], Double) Double,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool])
('[IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)])
([Double], Bool)
()
([Double], Bool)
()
andGateGame (AndGateMarkovParams {..} ) = [opengame|
inputs : summaryStatistic ;
:---:
inputs : summaryStatistic ;
operation : stakingRound sampleSize1 sampleSize2 sampleSize3 costOfCapital minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposits ;
operation : nature (successfulAttackPayoffDistribution attackerProbability maxSuccessfulAttackPayoff) ;
outputs : successfulAttackPayoff ;
inputs : deposits, successfulAttackPayoff ;
operation : dependentDecisionIO "Attacker" sampleSizeA [minBribe, minBribe+incrementBribe .. maxBribe];
outputs : bribe ;
returns : attackerPayoff bribesAccepted bribe successfulAttackPayoff ;
inputs : (summaryStatistic, deposits, bribe) ;
operation : playingRound sampleSize1 sampleSize2 sampleSize3;
outputs : moves ;
returns : zip (payoffAndGate penalty reward deposits (obfuscateAndGate moves)) bribesAccepted ;
inputs : moves ;
operation : fromFunctions (map not) id ;
outputs : bribesAccepted ;
operation : discountingStage discountFactor ;
:---:
outputs : (deposits, obfuscateAndGate moves) ;
|]
---------------
-- continuation
-- extract continuation
extractContinuation :: MonadOptic s () s () -> s -> StateT Vector IO ()
extractContinuation (MonadOptic v u) x = do
(z,a) <- ST.lift (v x)
u z ()
-- extract next state (action)
extractNextState :: MonadOptic s () s () -> s -> IO s
extractNextState (MonadOptic v _) x = do
(z,a) <- v x
pure a
extractContinuation2 :: MonadOptic Double () ([Double],Bool) () -> Double -> StateT Vector IO ()
extractContinuation2 (MonadOptic v u) x = do
(z,a) <- ST.lift (v x)
u z ()
-- extract next state (action)
extractNextState2 :: MonadOptic Double () ([Double],Bool) () -> Double -> IO ([Double],Bool)
extractNextState2 (MonadOptic v _) x = do
(z,a) <- v x
pure a
-- Random prior indpendent of previous moves
determineContinuationPayoffs parameters 1 strat action = pure ()
determineContinuationPayoffs parameters iterator strat action = do
extractContinuation executeStrat action
g <- newStdGen
gS <- newIOGenM g
nextInput <- ST.lift $ genFromTable (transformStochasticToProbTable andGateTestPrior) gS
determineContinuationPayoffs parameters (pred iterator) strat nextInput
where executeStrat = play (andGateGame parameters) strat
-- Actual moves affect next moves
determineContinuationPayoffs' parameters 1 strat action = pure ()
determineContinuationPayoffs' parameters iterator strat action = do
extractContinuation executeStrat action
nextInput <- ST.lift $ extractNextState executeStrat action
determineContinuationPayoffs' parameters (pred iterator) strat nextInput
where executeStrat = play (andGateGame parameters) strat
determineContinuationPayoffs3 1 _ = pure ()
determineContinuationPayoffs3 iterator initialAction = do
extractContinuation executeStrat initialAction
nextInput <- ST.lift $ extractNextState executeStrat $ initialAction
determineContinuationPayoffs3 (pred iterator) initialAction
pure ()
where executeStrat = play (andGateGame andGateMarkovTestParams) strategyTuple
-- fix context used for the evaluation
contextCont parameters iterator strat initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs parameters iterator strat action)
contextCont' parameters iterator strat initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs' parameters iterator strat action)
contextCont3 iterator initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs3 iterator action)
-----------
-- Strategy
transformStrat :: Kleisli Stochastic x y -> Kleisli CondensedTableV x y
transformStrat strat = Kleisli (\x ->
let y = runKleisli strat x
ls = decons y
v = V.fromList ls
in tableFromProbabilities v)
transformStochasticToProbTable dist =
let ls = decons dist
v = V.fromList ls
in tableFromProbabilities v
depositStrategy = transformStrat $ Kleisli $ \((_, previousRoundTrue), _) -> playDeterministically $ if previousRoundTrue then 4.6 else 0.0
attackerStrategy = transformStrat $ Kleisli (\(deposits, successfulAttackPayoff) -> if successfulAttackPayoff == maxSuccessfulAttackPayoff andGateMarkovTestParams && sum deposits > 0.0 then playDeterministically 5.0 else playDeterministically 0.0)
signalStrategy = transformStrat $ Kleisli $ \((_, previousRoundTrue), _, bribe) -> playDeterministically $ previousRoundTrue && bribe < 5.0
strategyTuple =
depositStrategy
:- depositStrategy
:- depositStrategy
:- attackerStrategy
:- signalStrategy
:- signalStrategy
:- signalStrategy
:- Nil
-----------------------
-- Equilibrium analysis
andGateMarkovGameEq parameters iterator strat initialAction = evaluate (andGateGame parameters) strat context
where context = contextCont parameters iterator strat initialAction
eqOutput parameters iterator strat initialAction = andGateMarkovGameEq parameters iterator strat initialAction
andGateMarkovGameEq' parameters iterator strat initialAction = evaluate (andGateGame parameters) strat context
where context = contextCont' parameters iterator strat initialAction
eqOutput' parameters iterator strat initialAction = andGateMarkovGameEq' parameters iterator strat initialAction
andGateMarkovGameEq3 iterator initialAction = evaluate (andGateGame andGateMarkovTestParams) strategyTuple context
where context = contextCont3 iterator initialAction
eqOutput3 iterator initialAction = andGateMarkovGameEq3 iterator initialAction
testInitialAction = ([10.0,10.0,10.0],True)
testEq iterator = eqOutput andGateMarkovTestParams iterator strategyTuple testInitialAction
testEq' iterator = eqOutput' andGateMarkovTestParams iterator strategyTuple testInitialAction
testEq3 iterator = eqOutput3 iterator testInitialAction
printOutput :: List
'[IO (DiagnosticsMC Double), IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double), IO (DiagnosticsMC Double),
IO (DiagnosticsMC Bool), IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)]
-> IO ()
printOutput (result1 :- result2 :- result3 :- result4 :- result5 :- result6 :- result7 :- Nil) = do
result1' <- result1
result2' <- result2
result3' <- result3
result4' <- result4
result5' <- result5
result6' <- result6
result7' <- result7
putStrLn "Player1"
print result1'
putStrLn "Player2"
print result2'
putStrLn "Player3"
print result3'
putStrLn "Player4"
print result4'
putStrLn "Player5"
print result5'
putStrLn "Player6"
print result6'
putStrLn "Player7"
print result7'
| null | https://raw.githubusercontent.com/CyberCat-Institute/open-game-engine/86031c42bf13178554c21cd7ab9e9d18f1ca6963/src/Examples/Staking/AndGateMarkovMC.hs | haskell | # LANGUAGE GADTs #
DONE What effect happens through the state hack and the discounting? The discounting at least does not seem to make a difference.
------
Types
-------------------
------
Games
-:
-:
-:
-:
-:
-:
-:
-:
-:
-:
-:
-:
-------------
continuation
extract continuation
extract next state (action)
extract next state (action)
Random prior indpendent of previous moves
Actual moves affect next moves
fix context used for the evaluation
---------
Strategy
---------------------
Equilibrium analysis | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE LambdaCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
module Examples.Staking.AndGateMarkovMC where
import Debug.Trace
import OpenGames hiding (fromLens,Agent,fromFunctions,discount,nature)
import OpenGames.Engine.IOGames
import OpenGames.Engine.BayesianGames (uniformDist, playDeterministically)
import OpenGames.Preprocessor
import Control.Arrow (Kleisli(..))
import Control.Monad.State hiding (state, void, lift)
import qualified Control.Monad.State as ST
import qualified Data.Vector as V
import Numeric.Probability.Distribution hiding (map, lift, filter)
import System.Random.MWC.CondensedTable
import System.Random
import System.Random.Stateful
TODO change the structure of the continuation iteration
andGateMarkovTestParams = AndGateMarkovParams {
sampleSize1 = 100,
sampleSize2 = 100,
sampleSize3 = 100,
sampleSizeA = 100,
reward = 1.0,
costOfCapital = 0.05,
minBribe = 0.0,
maxBribe = 5.0,
incrementBribe = 1.0,
maxSuccessfulAttackPayoff = 1000.0,
attackerProbability = 0.001,
penalty = 0.5,
minDeposit = 0.0,
maxDeposit = 10.0,
incrementDeposit = 1,
epsilon = 0.001,
discountFactor = 0.5
}
data AndGateMarkovParams = AndGateMarkovParams {
sampleSize1 :: Int,
sampleSize2 :: Int,
sampleSize3 :: Int,
sampleSizeA :: Int,
reward :: Double,
costOfCapital :: Double,
minBribe :: Double,
maxBribe :: Double,
incrementBribe :: Double,
maxSuccessfulAttackPayoff :: Double,
attackerProbability :: Double,
penalty :: Double,
minDeposit :: Double,
maxDeposit :: Double,
incrementDeposit :: Double,
epsilon :: Double,
discountFactor :: Double
}
data MessageType = Bool | Double
Auxilary functions
attackerPayoff :: [Bool] -> Double -> Double -> Double
attackerPayoff bribesAccepted bribe successfulAttackPayoff
| (numBribed == numPlayers) = successfulAttackPayoff - bribe*(fromIntegral numBribed)
| (otherwise) = -bribe*(fromIntegral numBribed)
where numPlayers = length bribesAccepted
numBribed = length (filter id bribesAccepted)
obfuscateAndGate :: [Bool] -> Bool
obfuscateAndGate = and
successfulAttackPayoffDistribution :: Double -> Double -> CondensedTableV Double
successfulAttackPayoffDistribution attackerProbability maxSuccessfulAttackPayoff
| (attackerProbability == 0) = tableFromProbabilities $ V.fromList [(0,0)]
| (attackerProbability == 1) = tableFromProbabilities $ V.fromList [(maxSuccessfulAttackPayoff,1)]
| (otherwise) = tableFromProbabilities $ V.fromList [(0, 1-attackerProbability), (maxSuccessfulAttackPayoff, attackerProbability)]
payoffAndGate :: Double -> Double -> [Double] -> Bool -> [Double]
payoffAndGate penalty reward deposits True
| (sumDeposits > 0) = [deposit*reward/sumDeposits | deposit <- deposits]
| (sumDeposits == 0) = [0 | _ <- deposits]
where sumDeposits = sum deposits
payoffAndGate penalty reward deposits False
= [-penalty*deposit | deposit <- deposits]
andGateTestPrior = do
deposits <- uniformDist [replicate 3 x | x <- [0.0, 1.0 .. 10.0]]
andResults <- uniformDist [True, False]
return (deposits, andResults)
depositStagePlayer name sampleSize minDeposit maxDeposit incrementDeposit epsilon = [opengame|
inputs : summaryStatistic, costOfCapital ;
inputs : summaryStatistic, costOfCapital ;
operation : dependentDecisionIO name sampleSize [minDeposit, minDeposit + incrementDeposit .. maxDeposit] ;
outputs : deposit ;
returns : (-deposit) * costOfCapital ;
outputs : deposit ;
|]
playingStagePlayer name sampleSize moves = [opengame|
inputs : summaryStatistic, observation, bribe ;
inputs : summaryStatistic, observation, bribe ;
operation : dependentDecisionIO name sampleSize moves ;
outputs : move ;
returns : payoff + if bribePaid then bribe else 0 ;
outputs : move ;
returns : payoff, bribePaid ;
|]
stakingRound sampleSizeP1 sampleSizeP2 sampleSizeP3 costOfCapital minDeposit maxDeposit incrementDeposit epsilon = [opengame|
inputs : summaryStatistic ;
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player1" sampleSizeP1 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit1 ;
returns : ;
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player2" sampleSizeP2 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit2 ;
returns : ;
inputs : (summaryStatistic, costOfCapital) ;
feedback : ;
operation : depositStagePlayer "Player3" sampleSizeP3 minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposit3 ;
returns : ;
inputs : deposit1,deposit2,deposit3 ;
operation : fromFunctions (\(x,y,z) -> [x,y,z]) id ;
outputs: deposits ;
outputs: deposits ;
|]
indexLs = (!!)
nothing = 0.0
playingRound :: Int
-> Int
-> Int
-> OpenGame
MonadOptic
MonadContext
('[Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double],Bool), [Double], Double) Bool]
)
('[IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)])
(([Double],Bool), [Double], Double)
()
[Bool]
[(Double, Bool)]
playingRound sampleSizeP1 sampleSizeP2 sampleSizeP3= [opengame|
inputs : (summaryStatistic, deposits, bribe) ;
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player1" sampleSizeP1 [True, False] ;
outputs : move1 ;
returns : indexLs lsPayBribes 0 ;
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player2" sampleSizeP2 [True, False] ;
outputs : move2 ;
returns : indexLs lsPayBribes 1 ;
inputs : (summaryStatistic, deposits, bribe) ;
feedback : ;
operation : playingStagePlayer "Player3" sampleSizeP3 [True, False] ;
outputs : move3 ;
returns : indexLs lsPayBribes 2 ;
inputs : move1,move2,move3 ;
operation : fromFunctions (\(x,y,z) -> [x,y,z]) id ;
outputs: moves ;
outputs : moves ;
returns : lsPayBribes ;
|]
discountingStage discountFactor = [opengame|
inputs : ;
operation : discount "Player1" (\x -> x * discountFactor) ;
operation : discount "Player2" (\x -> x * discountFactor) ;
operation : discount "Player3" (\x -> x * discountFactor) ;
operation : discount "Attacker" (\x -> x * discountFactor) ;
outputs : ;
|]
andGateGame :: AndGateMarkovParams
-> OpenGame
MonadOptic
MonadContext
('[Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV (([Double], Bool), Double) Double,
Kleisli CondensedTableV ([Double], Double) Double,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool,
Kleisli CondensedTableV (([Double], Bool), [Double], Double) Bool])
('[IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)])
([Double], Bool)
()
([Double], Bool)
()
andGateGame (AndGateMarkovParams {..} ) = [opengame|
inputs : summaryStatistic ;
inputs : summaryStatistic ;
operation : stakingRound sampleSize1 sampleSize2 sampleSize3 costOfCapital minDeposit maxDeposit incrementDeposit epsilon ;
outputs : deposits ;
operation : nature (successfulAttackPayoffDistribution attackerProbability maxSuccessfulAttackPayoff) ;
outputs : successfulAttackPayoff ;
inputs : deposits, successfulAttackPayoff ;
operation : dependentDecisionIO "Attacker" sampleSizeA [minBribe, minBribe+incrementBribe .. maxBribe];
outputs : bribe ;
returns : attackerPayoff bribesAccepted bribe successfulAttackPayoff ;
inputs : (summaryStatistic, deposits, bribe) ;
operation : playingRound sampleSize1 sampleSize2 sampleSize3;
outputs : moves ;
returns : zip (payoffAndGate penalty reward deposits (obfuscateAndGate moves)) bribesAccepted ;
inputs : moves ;
operation : fromFunctions (map not) id ;
outputs : bribesAccepted ;
operation : discountingStage discountFactor ;
outputs : (deposits, obfuscateAndGate moves) ;
|]
extractContinuation :: MonadOptic s () s () -> s -> StateT Vector IO ()
extractContinuation (MonadOptic v u) x = do
(z,a) <- ST.lift (v x)
u z ()
extractNextState :: MonadOptic s () s () -> s -> IO s
extractNextState (MonadOptic v _) x = do
(z,a) <- v x
pure a
extractContinuation2 :: MonadOptic Double () ([Double],Bool) () -> Double -> StateT Vector IO ()
extractContinuation2 (MonadOptic v u) x = do
(z,a) <- ST.lift (v x)
u z ()
extractNextState2 :: MonadOptic Double () ([Double],Bool) () -> Double -> IO ([Double],Bool)
extractNextState2 (MonadOptic v _) x = do
(z,a) <- v x
pure a
determineContinuationPayoffs parameters 1 strat action = pure ()
determineContinuationPayoffs parameters iterator strat action = do
extractContinuation executeStrat action
g <- newStdGen
gS <- newIOGenM g
nextInput <- ST.lift $ genFromTable (transformStochasticToProbTable andGateTestPrior) gS
determineContinuationPayoffs parameters (pred iterator) strat nextInput
where executeStrat = play (andGateGame parameters) strat
determineContinuationPayoffs' parameters 1 strat action = pure ()
determineContinuationPayoffs' parameters iterator strat action = do
extractContinuation executeStrat action
nextInput <- ST.lift $ extractNextState executeStrat action
determineContinuationPayoffs' parameters (pred iterator) strat nextInput
where executeStrat = play (andGateGame parameters) strat
determineContinuationPayoffs3 1 _ = pure ()
determineContinuationPayoffs3 iterator initialAction = do
extractContinuation executeStrat initialAction
nextInput <- ST.lift $ extractNextState executeStrat $ initialAction
determineContinuationPayoffs3 (pred iterator) initialAction
pure ()
where executeStrat = play (andGateGame andGateMarkovTestParams) strategyTuple
contextCont parameters iterator strat initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs parameters iterator strat action)
contextCont' parameters iterator strat initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs' parameters iterator strat action)
contextCont3 iterator initialAction = MonadContext (pure ((),initialAction)) (\_ action -> determineContinuationPayoffs3 iterator action)
transformStrat :: Kleisli Stochastic x y -> Kleisli CondensedTableV x y
transformStrat strat = Kleisli (\x ->
let y = runKleisli strat x
ls = decons y
v = V.fromList ls
in tableFromProbabilities v)
transformStochasticToProbTable dist =
let ls = decons dist
v = V.fromList ls
in tableFromProbabilities v
depositStrategy = transformStrat $ Kleisli $ \((_, previousRoundTrue), _) -> playDeterministically $ if previousRoundTrue then 4.6 else 0.0
attackerStrategy = transformStrat $ Kleisli (\(deposits, successfulAttackPayoff) -> if successfulAttackPayoff == maxSuccessfulAttackPayoff andGateMarkovTestParams && sum deposits > 0.0 then playDeterministically 5.0 else playDeterministically 0.0)
signalStrategy = transformStrat $ Kleisli $ \((_, previousRoundTrue), _, bribe) -> playDeterministically $ previousRoundTrue && bribe < 5.0
strategyTuple =
depositStrategy
:- depositStrategy
:- depositStrategy
:- attackerStrategy
:- signalStrategy
:- signalStrategy
:- signalStrategy
:- Nil
andGateMarkovGameEq parameters iterator strat initialAction = evaluate (andGateGame parameters) strat context
where context = contextCont parameters iterator strat initialAction
eqOutput parameters iterator strat initialAction = andGateMarkovGameEq parameters iterator strat initialAction
andGateMarkovGameEq' parameters iterator strat initialAction = evaluate (andGateGame parameters) strat context
where context = contextCont' parameters iterator strat initialAction
eqOutput' parameters iterator strat initialAction = andGateMarkovGameEq' parameters iterator strat initialAction
andGateMarkovGameEq3 iterator initialAction = evaluate (andGateGame andGateMarkovTestParams) strategyTuple context
where context = contextCont3 iterator initialAction
eqOutput3 iterator initialAction = andGateMarkovGameEq3 iterator initialAction
testInitialAction = ([10.0,10.0,10.0],True)
testEq iterator = eqOutput andGateMarkovTestParams iterator strategyTuple testInitialAction
testEq' iterator = eqOutput' andGateMarkovTestParams iterator strategyTuple testInitialAction
testEq3 iterator = eqOutput3 iterator testInitialAction
printOutput :: List
'[IO (DiagnosticsMC Double), IO (DiagnosticsMC Double),
IO (DiagnosticsMC Double), IO (DiagnosticsMC Double),
IO (DiagnosticsMC Bool), IO (DiagnosticsMC Bool),
IO (DiagnosticsMC Bool)]
-> IO ()
printOutput (result1 :- result2 :- result3 :- result4 :- result5 :- result6 :- result7 :- Nil) = do
result1' <- result1
result2' <- result2
result3' <- result3
result4' <- result4
result5' <- result5
result6' <- result6
result7' <- result7
putStrLn "Player1"
print result1'
putStrLn "Player2"
print result2'
putStrLn "Player3"
print result3'
putStrLn "Player4"
print result4'
putStrLn "Player5"
print result5'
putStrLn "Player6"
print result6'
putStrLn "Player7"
print result7'
|
9ee9f44909f6312a59843a197fc6dfc4b723ea1651fe21f0cb21f9dcdf178654 | sadiqj/ocaml-esp32 | types.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. *)
(* *)
(**************************************************************************)
(** {0 Representation of types and declarations} *)
* [ Types ] defines the representation of types and declarations ( that is , the
content of module signatures ) .
CMI files are made of marshalled types .
content of module signatures).
CMI files are made of marshalled types.
*)
* exposes basic definitions shared both by Parsetree and Types .
open Asttypes
* Type expressions for the core language .
The [ type_desc ] variant defines all the possible type expressions one can
find in OCaml . [ type_expr ] wraps this with some annotations .
The [ level ] field tracks the level of polymorphism associated to a type ,
guiding the generalization algorithm .
Put shortly , when referring to a type in a given environment , both the type
and the environment have a level . If the type has an higher level , then it
can be considered fully polymorphic ( type variables will be printed as
[ ' a ] ) , otherwise it 'll be weakly polymorphic , or non generalized ( type
variables printed as [ ' _ a ] ) .
See [ ] for more information .
Note about [ type_declaration ] : one should not make the confusion between
[ type_expr ] and [ type_declaration ] .
[ type_declaration ] refers specifically to the [ type ] construct in OCaml
language , where you create and name a new type or type alias .
[ type_expr ] is used when you refer to existing types , e.g. when annotating
the expected type of a value .
Also , as the type system of OCaml is generative , a [ type_declaration ] can
have the side - effect of introducing a new type constructor , different from
all other known types .
Whereas [ type_expr ] is a pure construct which allows referring to existing
types .
Note on mutability : TBD .
The [type_desc] variant defines all the possible type expressions one can
find in OCaml. [type_expr] wraps this with some annotations.
The [level] field tracks the level of polymorphism associated to a type,
guiding the generalization algorithm.
Put shortly, when referring to a type in a given environment, both the type
and the environment have a level. If the type has an higher level, then it
can be considered fully polymorphic (type variables will be printed as
['a]), otherwise it'll be weakly polymorphic, or non generalized (type
variables printed as ['_a]).
See [] for more information.
Note about [type_declaration]: one should not make the confusion between
[type_expr] and [type_declaration].
[type_declaration] refers specifically to the [type] construct in OCaml
language, where you create and name a new type or type alias.
[type_expr] is used when you refer to existing types, e.g. when annotating
the expected type of a value.
Also, as the type system of OCaml is generative, a [type_declaration] can
have the side-effect of introducing a new type constructor, different from
all other known types.
Whereas [type_expr] is a pure construct which allows referring to existing
types.
Note on mutability: TBD.
*)
type type_expr =
{ mutable desc: type_desc;
mutable level: int;
id: int }
and type_desc =
| Tvar of string option
(** [Tvar (Some "a")] ==> ['a] or ['_a]
[Tvar None] ==> [_] *)
| Tarrow of arg_label * type_expr * type_expr * commutable
* [ ( Nolabel , e1 , e2 , c ) ] = = > [ e1 - > e2 ]
[ ( Labelled " l " , e1 , e2 , c ) ] = = > [ l : e1 - > e2 ]
[ ( Optional " l " , e1 , e2 , c ) ] = = > [ ? l : e1 - > e2 ]
See [ commutable ] for the last argument .
[Tarrow (Labelled "l", e1, e2, c)] ==> [l:e1 -> e2]
[Tarrow (Optional "l", e1, e2, c)] ==> [?l:e1 -> e2]
See [commutable] for the last argument. *)
| Ttuple of type_expr list
* [ [ t1; ... ;tn ] ] = = > [ ( t1 * ... * tn ) ]
| Tconstr of Path.t * type_expr list * abbrev_memo ref
* [ Tconstr ( ` A.B.t ' , [ t1; ... ;tn ] , _ ) ] = = > [ ( t1, ... ,tn ) A.B.t ]
The last parameter keep tracks of known expansions , see [ abbrev_memo ] .
The last parameter keep tracks of known expansions, see [abbrev_memo]. *)
| Tobject of type_expr * (Path.t * type_expr list) option ref
* [ Tobject ( ` f1 : t1; ... ;fn : tn ' , ` None ' ) ] = = > [ < f1 : t1 ; ... ; fn : tn > ]
f1 , fn are represented as a linked list of types using and
constructors .
[ Tobject ( _ , ` Some ( ` A.ct ' , [ t1; ... ;tn ] ' ) ] = = > [ ( t1 , ... , tn ) A.ct ] .
where A.ct is the type of some class .
There are also special cases for so - called " class - types " , cf . [ ]
and [ Ctype.set_object_name ] :
[ Tobject ( Tfield(_,_, ... (Tfield(_,_,rv ) ... ) ,
Some(`A.#ct ` , [ rv;t1; ... ;tn ] ) ]
= = > [ ( t1 , ... , tn ) # A.ct ]
[ Tobject ( _ , Some(`A.#ct ` , [ Tnil;t1; ... ;tn ] ) ] = = > [ ( t1 , ... , tn ) A.ct ]
where [ rv ] is the hidden row variable .
f1, fn are represented as a linked list of types using Tfield and Tnil
constructors.
[Tobject (_, `Some (`A.ct', [t1;...;tn]')] ==> [(t1, ..., tn) A.ct].
where A.ct is the type of some class.
There are also special cases for so-called "class-types", cf. [Typeclass]
and [Ctype.set_object_name]:
[Tobject (Tfield(_,_,...(Tfield(_,_,rv)...),
Some(`A.#ct`, [rv;t1;...;tn])]
==> [(t1, ..., tn) #A.ct]
[Tobject (_, Some(`A.#ct`, [Tnil;t1;...;tn])] ==> [(t1, ..., tn) A.ct]
where [rv] is the hidden row variable.
*)
| Tfield of string * field_kind * type_expr * type_expr
* [ ( " foo " , , t , ts ) ] = = > [ < ... ; foo : t ; ts > ]
| Tnil
* [ ] = = > [ < ... ; > ]
| Tlink of type_expr
(** Indirection used by unification engine. *)
| Tsubst of type_expr (* for copying *)
(** [Tsubst] is used temporarily to store information in low-level
functions manipulating representation of types, such as
instantiation or copy.
This constructor should not appear outside of these cases. *)
| Tvariant of row_desc
(** Representation of polymorphic variants, see [row_desc]. *)
| Tunivar of string option
(** Occurrence of a type variable introduced by a
forall quantifier / [Tpoly]. *)
| Tpoly of type_expr * type_expr list
(** [Tpoly (ty,tyl)] ==> ['a1... 'an. ty],
where 'a1 ... 'an are names given to types in tyl
and occurrences of those types in ty. *)
| Tpackage of Path.t * Longident.t list * type_expr list
* Type of a first - class module ( a.k.a package ) .
* [ ` X | ` Y ] ( row_closed = true )
[ < ` X | ` Y ] ( row_closed = true )
[ > ` X | ` Y ] ( row_closed = false )
[ < ` X | ` Y > ` X ] ( row_closed = true )
type t = [ > ` X ] as ' a ( row_more = Tvar a )
type t = private [ > ` X ] ( row_more = Tconstr ( t#row , [ ] , ref Mnil )
And for :
let f = function ` X - > ` X - > | ` Y - > ` X
the type of " f " will be a [ Tarrow ] whose lhs will ( basically ) be :
Tvariant { row_fields = [ ( " X " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ( " Y " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ] ;
row_more = _ ;
_ } ;
_ } ;
_
}
[< `X | `Y ] (row_closed = true)
[> `X | `Y ] (row_closed = false)
[< `X | `Y > `X ] (row_closed = true)
type t = [> `X ] as 'a (row_more = Tvar a)
type t = private [> `X ] (row_more = Tconstr (t#row, [], ref Mnil)
And for:
let f = function `X -> `X -> | `Y -> `X
the type of "f" will be a [Tarrow] whose lhs will (basically) be:
Tvariant { row_fields = [("X", _)];
row_more =
Tvariant { row_fields = [("Y", _)];
row_more =
Tvariant { row_fields = [];
row_more = _;
_ };
_ };
_
}
*)
and row_desc =
{ row_fields: (label * row_field) list;
row_more: type_expr;
row_bound: unit; (* kept for compatibility *)
row_closed: bool;
row_fixed: bool;
row_name: (Path.t * type_expr list) option }
and row_field =
Rpresent of type_expr option
| Reither of bool * type_expr list * bool * row_field option ref
(* 1st true denotes a constant constructor *)
2nd true denotes a tag in a pattern matching , and
is erased later
is erased later *)
| Rabsent
(** [abbrev_memo] allows one to keep track of different expansions of a type
alias. This is done for performance purposes.
For instance, when defining [type 'a pair = 'a * 'a], when one refers to an
['a pair], it is just a shortcut for the ['a * 'a] type.
This expansion will be stored in the [abbrev_memo] of the corresponding
[Tconstr] node.
In practice, [abbrev_memo] behaves like list of expansions with a mutable
tail.
Note on marshalling: [abbrev_memo] must not appear in saved types.
[Btype], with [cleanup_abbrev] and [memo], takes care of tracking and
removing abbreviations.
*)
and abbrev_memo =
| Mnil (** No known abbreviation *)
| Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
* Found one abbreviation .
A valid abbreviation should be at least as visible and reachable by the
same path .
The first expression is the abbreviation and the second the expansion .
A valid abbreviation should be at least as visible and reachable by the
same path.
The first expression is the abbreviation and the second the expansion. *)
| Mlink of abbrev_memo ref
(** Abbreviations can be found after this indirection *)
and field_kind =
Fvar of field_kind option ref
| Fpresent
| Fabsent
* [ commutable ] is a flag appended to every arrow type .
When typing an application , if the type of the functional is
known , its type is instantiated with [ ] arrows , otherwise as
[ Clink ( ref Cunknown ) ] .
When the type is not known , the application will be used to infer
the actual type . This is fragile in presence of labels where
there is no principal type .
Two incompatible applications relying on [ Cunknown ] arrows will
trigger an error .
let f g =
g ~a :() ~b :() ;
g ~b :() ~a :() ;
Error : This function is applied to arguments
in an order different from other calls .
This is only allowed when the real type is known .
When typing an application, if the type of the functional is
known, its type is instantiated with [Cok] arrows, otherwise as
[Clink (ref Cunknown)].
When the type is not known, the application will be used to infer
the actual type. This is fragile in presence of labels where
there is no principal type.
Two incompatible applications relying on [Cunknown] arrows will
trigger an error.
let f g =
g ~a:() ~b:();
g ~b:() ~a:();
Error: This function is applied to arguments
in an order different from other calls.
This is only allowed when the real type is known.
*)
and commutable =
Cok
| Cunknown
| Clink of commutable ref
module TypeOps : sig
type t = type_expr
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
(* Maps of methods and instance variables *)
module Meths : Map.S with type key = string
module Vars : Map.S with type key = string
(* Value descriptions *)
type value_description =
{ val_type: type_expr; (* Type of the value *)
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
Val_reg (* Regular value *)
| Val_prim of Primitive.description (* Primitive *)
| Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
| Val_self of (Ident.t * type_expr) Meths.t ref *
(Ident.t * mutable_flag * virtual_flag * type_expr) Vars.t ref *
string * type_expr
(* Self *)
| Val_anc of (string * Ident.t) list * string
(* Ancestor *)
Unbound variable
(* Variance *)
module Variance : sig
type t
type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
val null : t (* no occurrence *)
val full : t (* strictly invariant *)
val covariant : t (* strictly covariant *)
val may_inv : t (* maybe invariant *)
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
val conjugate : t -> t (* exchange positive and negative *)
val get_upper : t -> bool * bool (* may_pos, may_neg *)
pos , neg , inv ,
end
(* Type definitions *)
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
(* covariant, contravariant, weakly contravariant, injective *)
type_newtype_level: (int * int) option;
(* definition level * expansion level *)
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_immediate: bool; (* true iff type should not be a pointer *)
type_unboxed: unboxed_status;
}
and type_kind =
Type_abstract
| Type_record of label_declaration list * record_representation
| Type_variant of constructor_declaration list
| Type_open
and record_representation =
Record_regular (* All fields are boxed / tagged *)
| Record_float (* All fields are floats *)
| Record_unboxed of bool (* Unboxed single-field record, inlined or not *)
Inlined record
Inlined record under extension
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
and unboxed_status = private
This type must be private in order to ensure perfect sharing of the
four possible values . Otherwise , ocamlc.byte and ocamlc.opt produce
different executables .
four possible values. Otherwise, ocamlc.byte and ocamlc.opt produce
different executables. *)
{
unboxed: bool;
default: bool; (* True for unannotated unboxable types. *)
}
val unboxed_false_default_false : unboxed_status
val unboxed_false_default_true : unboxed_status
val unboxed_true_default_false : unboxed_status
val unboxed_true_default_true : unboxed_status
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
}
and type_transparence =
Type_public (* unrestricted expansion *)
| Type_new (* "new" type *)
| Type_private (* private type *)
(* Type expressions for the class language *)
module Concr : Set.S with type elt = string
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
and class_signature =
{ csig_self: type_expr;
csig_vars:
(Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
csig_concr: Concr.t;
csig_inher: (Path.t * type_expr list) list }
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
}
(* Type expressions for the module language *)
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of Ident.t * module_type option * module_type
| Mty_alias of alias_presence * Path.t
and alias_presence =
| Mta_present
| Mta_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * value_description
| Sig_type of Ident.t * type_declaration * rec_status
| Sig_typext of Ident.t * extension_constructor * ext_status
| Sig_module of Ident.t * module_declaration * rec_status
| Sig_modtype of Ident.t * modtype_declaration
| Sig_class of Ident.t * class_declaration * rec_status
| Sig_class_type of Ident.t * class_type_declaration * rec_status
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
}
and modtype_declaration =
{
mtd_type: module_type option; (* None: abstract *)
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
Text_first (* first constructor in an extension *)
not first constructor in an extension
| Text_exception
(* Constructor and record label descriptions inserted held in typing
environments *)
type constructor_description =
{ cstr_name: string; (* Constructor name *)
cstr_res: type_expr; (* Type of the result *)
cstr_existentials: type_expr list; (* list of existentials *)
cstr_args: type_expr list; (* Type of the arguments *)
cstr_arity: int; (* Number of arguments *)
cstr_tag: constructor_tag; (* Tag for heap blocks *)
cstr_consts: int; (* Number of constant constructors *)
cstr_nonconsts: int; (* Number of non-const constructors *)
Number of non generalized
Constrained return type ?
cstr_private: private_flag; (* Read-only constructor? *)
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
}
and constructor_tag =
Cstr_constant of int (* Constant constructor (an int) *)
| Cstr_block of int (* Regular constructor (a block) *)
Constructor of an unboxed type
| Cstr_extension of Path.t * bool (* Extension constructor
true if a constant false if a block*)
val equal_tag : constructor_tag -> constructor_tag -> bool
type label_description =
{ lbl_name: string; (* Short name *)
lbl_res: type_expr; (* Type of the result *)
lbl_arg: type_expr; (* Type of the argument *)
lbl_mut: mutable_flag; (* Is this a mutable field? *)
lbl_pos: int; (* Position in block *)
lbl_all: label_description array; (* All the labels in this type *)
lbl_repres: record_representation; (* Representation for this record *)
lbl_private: private_flag; (* Read-only field? *)
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
}
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/typing/types.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.
************************************************************************
* {0 Representation of types and declarations}
* [Tvar (Some "a")] ==> ['a] or ['_a]
[Tvar None] ==> [_]
* Indirection used by unification engine.
for copying
* [Tsubst] is used temporarily to store information in low-level
functions manipulating representation of types, such as
instantiation or copy.
This constructor should not appear outside of these cases.
* Representation of polymorphic variants, see [row_desc].
* Occurrence of a type variable introduced by a
forall quantifier / [Tpoly].
* [Tpoly (ty,tyl)] ==> ['a1... 'an. ty],
where 'a1 ... 'an are names given to types in tyl
and occurrences of those types in ty.
kept for compatibility
1st true denotes a constant constructor
* [abbrev_memo] allows one to keep track of different expansions of a type
alias. This is done for performance purposes.
For instance, when defining [type 'a pair = 'a * 'a], when one refers to an
['a pair], it is just a shortcut for the ['a * 'a] type.
This expansion will be stored in the [abbrev_memo] of the corresponding
[Tconstr] node.
In practice, [abbrev_memo] behaves like list of expansions with a mutable
tail.
Note on marshalling: [abbrev_memo] must not appear in saved types.
[Btype], with [cleanup_abbrev] and [memo], takes care of tracking and
removing abbreviations.
* No known abbreviation
* Abbreviations can be found after this indirection
Maps of methods and instance variables
Value descriptions
Type of the value
Regular value
Primitive
Instance variable (mutable ?)
Self
Ancestor
Variance
no occurrence
strictly invariant
strictly covariant
maybe invariant
exchange positive and negative
may_pos, may_neg
Type definitions
covariant, contravariant, weakly contravariant, injective
definition level * expansion level
true iff type should not be a pointer
All fields are boxed / tagged
All fields are floats
Unboxed single-field record, inlined or not
True for unannotated unboxable types.
unrestricted expansion
"new" type
private type
Type expressions for the class language
Type expressions for the module language
None: abstract
first constructor in an extension
Constructor and record label descriptions inserted held in typing
environments
Constructor name
Type of the result
list of existentials
Type of the arguments
Number of arguments
Tag for heap blocks
Number of constant constructors
Number of non-const constructors
Read-only constructor?
Constant constructor (an int)
Regular constructor (a block)
Extension constructor
true if a constant false if a block
Short name
Type of the result
Type of the argument
Is this a mutable field?
Position in block
All the labels in this type
Representation for this record
Read-only field? | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* [ Types ] defines the representation of types and declarations ( that is , the
content of module signatures ) .
CMI files are made of marshalled types .
content of module signatures).
CMI files are made of marshalled types.
*)
* exposes basic definitions shared both by Parsetree and Types .
open Asttypes
* Type expressions for the core language .
The [ type_desc ] variant defines all the possible type expressions one can
find in OCaml . [ type_expr ] wraps this with some annotations .
The [ level ] field tracks the level of polymorphism associated to a type ,
guiding the generalization algorithm .
Put shortly , when referring to a type in a given environment , both the type
and the environment have a level . If the type has an higher level , then it
can be considered fully polymorphic ( type variables will be printed as
[ ' a ] ) , otherwise it 'll be weakly polymorphic , or non generalized ( type
variables printed as [ ' _ a ] ) .
See [ ] for more information .
Note about [ type_declaration ] : one should not make the confusion between
[ type_expr ] and [ type_declaration ] .
[ type_declaration ] refers specifically to the [ type ] construct in OCaml
language , where you create and name a new type or type alias .
[ type_expr ] is used when you refer to existing types , e.g. when annotating
the expected type of a value .
Also , as the type system of OCaml is generative , a [ type_declaration ] can
have the side - effect of introducing a new type constructor , different from
all other known types .
Whereas [ type_expr ] is a pure construct which allows referring to existing
types .
Note on mutability : TBD .
The [type_desc] variant defines all the possible type expressions one can
find in OCaml. [type_expr] wraps this with some annotations.
The [level] field tracks the level of polymorphism associated to a type,
guiding the generalization algorithm.
Put shortly, when referring to a type in a given environment, both the type
and the environment have a level. If the type has an higher level, then it
can be considered fully polymorphic (type variables will be printed as
['a]), otherwise it'll be weakly polymorphic, or non generalized (type
variables printed as ['_a]).
See [] for more information.
Note about [type_declaration]: one should not make the confusion between
[type_expr] and [type_declaration].
[type_declaration] refers specifically to the [type] construct in OCaml
language, where you create and name a new type or type alias.
[type_expr] is used when you refer to existing types, e.g. when annotating
the expected type of a value.
Also, as the type system of OCaml is generative, a [type_declaration] can
have the side-effect of introducing a new type constructor, different from
all other known types.
Whereas [type_expr] is a pure construct which allows referring to existing
types.
Note on mutability: TBD.
*)
type type_expr =
{ mutable desc: type_desc;
mutable level: int;
id: int }
and type_desc =
| Tvar of string option
| Tarrow of arg_label * type_expr * type_expr * commutable
* [ ( Nolabel , e1 , e2 , c ) ] = = > [ e1 - > e2 ]
[ ( Labelled " l " , e1 , e2 , c ) ] = = > [ l : e1 - > e2 ]
[ ( Optional " l " , e1 , e2 , c ) ] = = > [ ? l : e1 - > e2 ]
See [ commutable ] for the last argument .
[Tarrow (Labelled "l", e1, e2, c)] ==> [l:e1 -> e2]
[Tarrow (Optional "l", e1, e2, c)] ==> [?l:e1 -> e2]
See [commutable] for the last argument. *)
| Ttuple of type_expr list
* [ [ t1; ... ;tn ] ] = = > [ ( t1 * ... * tn ) ]
| Tconstr of Path.t * type_expr list * abbrev_memo ref
* [ Tconstr ( ` A.B.t ' , [ t1; ... ;tn ] , _ ) ] = = > [ ( t1, ... ,tn ) A.B.t ]
The last parameter keep tracks of known expansions , see [ abbrev_memo ] .
The last parameter keep tracks of known expansions, see [abbrev_memo]. *)
| Tobject of type_expr * (Path.t * type_expr list) option ref
* [ Tobject ( ` f1 : t1; ... ;fn : tn ' , ` None ' ) ] = = > [ < f1 : t1 ; ... ; fn : tn > ]
f1 , fn are represented as a linked list of types using and
constructors .
[ Tobject ( _ , ` Some ( ` A.ct ' , [ t1; ... ;tn ] ' ) ] = = > [ ( t1 , ... , tn ) A.ct ] .
where A.ct is the type of some class .
There are also special cases for so - called " class - types " , cf . [ ]
and [ Ctype.set_object_name ] :
[ Tobject ( Tfield(_,_, ... (Tfield(_,_,rv ) ... ) ,
Some(`A.#ct ` , [ rv;t1; ... ;tn ] ) ]
= = > [ ( t1 , ... , tn ) # A.ct ]
[ Tobject ( _ , Some(`A.#ct ` , [ Tnil;t1; ... ;tn ] ) ] = = > [ ( t1 , ... , tn ) A.ct ]
where [ rv ] is the hidden row variable .
f1, fn are represented as a linked list of types using Tfield and Tnil
constructors.
[Tobject (_, `Some (`A.ct', [t1;...;tn]')] ==> [(t1, ..., tn) A.ct].
where A.ct is the type of some class.
There are also special cases for so-called "class-types", cf. [Typeclass]
and [Ctype.set_object_name]:
[Tobject (Tfield(_,_,...(Tfield(_,_,rv)...),
Some(`A.#ct`, [rv;t1;...;tn])]
==> [(t1, ..., tn) #A.ct]
[Tobject (_, Some(`A.#ct`, [Tnil;t1;...;tn])] ==> [(t1, ..., tn) A.ct]
where [rv] is the hidden row variable.
*)
| Tfield of string * field_kind * type_expr * type_expr
* [ ( " foo " , , t , ts ) ] = = > [ < ... ; foo : t ; ts > ]
| Tnil
* [ ] = = > [ < ... ; > ]
| Tlink of type_expr
| Tvariant of row_desc
| Tunivar of string option
| Tpoly of type_expr * type_expr list
| Tpackage of Path.t * Longident.t list * type_expr list
* Type of a first - class module ( a.k.a package ) .
* [ ` X | ` Y ] ( row_closed = true )
[ < ` X | ` Y ] ( row_closed = true )
[ > ` X | ` Y ] ( row_closed = false )
[ < ` X | ` Y > ` X ] ( row_closed = true )
type t = [ > ` X ] as ' a ( row_more = Tvar a )
type t = private [ > ` X ] ( row_more = Tconstr ( t#row , [ ] , ref Mnil )
And for :
let f = function ` X - > ` X - > | ` Y - > ` X
the type of " f " will be a [ Tarrow ] whose lhs will ( basically ) be :
Tvariant { row_fields = [ ( " X " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ( " Y " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ] ;
row_more = _ ;
_ } ;
_ } ;
_
}
[< `X | `Y ] (row_closed = true)
[> `X | `Y ] (row_closed = false)
[< `X | `Y > `X ] (row_closed = true)
type t = [> `X ] as 'a (row_more = Tvar a)
type t = private [> `X ] (row_more = Tconstr (t#row, [], ref Mnil)
And for:
let f = function `X -> `X -> | `Y -> `X
the type of "f" will be a [Tarrow] whose lhs will (basically) be:
Tvariant { row_fields = [("X", _)];
row_more =
Tvariant { row_fields = [("Y", _)];
row_more =
Tvariant { row_fields = [];
row_more = _;
_ };
_ };
_
}
*)
and row_desc =
{ row_fields: (label * row_field) list;
row_more: type_expr;
row_closed: bool;
row_fixed: bool;
row_name: (Path.t * type_expr list) option }
and row_field =
Rpresent of type_expr option
| Reither of bool * type_expr list * bool * row_field option ref
2nd true denotes a tag in a pattern matching , and
is erased later
is erased later *)
| Rabsent
and abbrev_memo =
| Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
* Found one abbreviation .
A valid abbreviation should be at least as visible and reachable by the
same path .
The first expression is the abbreviation and the second the expansion .
A valid abbreviation should be at least as visible and reachable by the
same path.
The first expression is the abbreviation and the second the expansion. *)
| Mlink of abbrev_memo ref
and field_kind =
Fvar of field_kind option ref
| Fpresent
| Fabsent
* [ commutable ] is a flag appended to every arrow type .
When typing an application , if the type of the functional is
known , its type is instantiated with [ ] arrows , otherwise as
[ Clink ( ref Cunknown ) ] .
When the type is not known , the application will be used to infer
the actual type . This is fragile in presence of labels where
there is no principal type .
Two incompatible applications relying on [ Cunknown ] arrows will
trigger an error .
let f g =
g ~a :() ~b :() ;
g ~b :() ~a :() ;
Error : This function is applied to arguments
in an order different from other calls .
This is only allowed when the real type is known .
When typing an application, if the type of the functional is
known, its type is instantiated with [Cok] arrows, otherwise as
[Clink (ref Cunknown)].
When the type is not known, the application will be used to infer
the actual type. This is fragile in presence of labels where
there is no principal type.
Two incompatible applications relying on [Cunknown] arrows will
trigger an error.
let f g =
g ~a:() ~b:();
g ~b:() ~a:();
Error: This function is applied to arguments
in an order different from other calls.
This is only allowed when the real type is known.
*)
and commutable =
Cok
| Cunknown
| Clink of commutable ref
module TypeOps : sig
type t = type_expr
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module Meths : Map.S with type key = string
module Vars : Map.S with type key = string
type value_description =
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
| Val_self of (Ident.t * type_expr) Meths.t ref *
(Ident.t * mutable_flag * virtual_flag * type_expr) Vars.t ref *
string * type_expr
| Val_anc of (string * Ident.t) list * string
Unbound variable
module Variance : sig
type t
type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
pos , neg , inv ,
end
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
type_newtype_level: (int * int) option;
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_unboxed: unboxed_status;
}
and type_kind =
Type_abstract
| Type_record of label_declaration list * record_representation
| Type_variant of constructor_declaration list
| Type_open
and record_representation =
Inlined record
Inlined record under extension
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
and unboxed_status = private
This type must be private in order to ensure perfect sharing of the
four possible values . Otherwise , ocamlc.byte and ocamlc.opt produce
different executables .
four possible values. Otherwise, ocamlc.byte and ocamlc.opt produce
different executables. *)
{
unboxed: bool;
}
val unboxed_false_default_false : unboxed_status
val unboxed_false_default_true : unboxed_status
val unboxed_true_default_false : unboxed_status
val unboxed_true_default_true : unboxed_status
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
}
and type_transparence =
module Concr : Set.S with type elt = string
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
and class_signature =
{ csig_self: type_expr;
csig_vars:
(Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
csig_concr: Concr.t;
csig_inher: (Path.t * type_expr list) list }
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
}
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of Ident.t * module_type option * module_type
| Mty_alias of alias_presence * Path.t
and alias_presence =
| Mta_present
| Mta_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * value_description
| Sig_type of Ident.t * type_declaration * rec_status
| Sig_typext of Ident.t * extension_constructor * ext_status
| Sig_module of Ident.t * module_declaration * rec_status
| Sig_modtype of Ident.t * modtype_declaration
| Sig_class of Ident.t * class_declaration * rec_status
| Sig_class_type of Ident.t * class_type_declaration * rec_status
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
}
and modtype_declaration =
{
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
not first constructor in an extension
| Text_exception
type constructor_description =
Number of non generalized
Constrained return type ?
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
}
and constructor_tag =
Constructor of an unboxed type
val equal_tag : constructor_tag -> constructor_tag -> bool
type label_description =
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
}
|
b07a15415cbded9c29a71bdeaede6c55e9e4e96339cbf7159e4e384d3a431c2f | ocsigen/js_of_ocaml | print_runtime.ml | Js_of_ocaml compiler
* /
* Copyright ( C ) 2020 Hugo Heuzard
*
* This program 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 , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2020 Hugo Heuzard
*
* This program 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, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open! Js_of_ocaml_compiler.Stdlib
open Js_of_ocaml_compiler
let f () =
let output = stdout in
let new_line () = output_string output "\n" in
List.iter Js_of_ocaml_compiler_runtime_files.runtime ~f:(fun x ->
output_string output (Printf.sprintf "//# 1 %S" (Builtins.File.name x));
new_line ();
output_string output (Builtins.File.content x);
new_line ())
let info =
Info.make
~name:"print-standard-runtime"
~doc:"Print standard runtime to stdout"
~description:"js_of_ocaml-print-standard-runtime dump the standard runtime to stdout."
let command =
let t = Cmdliner.Term.(const f $ const ()) in
Cmdliner.Cmd.v info t
| null | https://raw.githubusercontent.com/ocsigen/js_of_ocaml/6e8200a6f31c2ccfba67fdd1d5db84dd893261ae/compiler/bin-js_of_ocaml/print_runtime.ml | ocaml | Js_of_ocaml compiler
* /
* Copyright ( C ) 2020 Hugo Heuzard
*
* This program 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 , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2020 Hugo Heuzard
*
* This program 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, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open! Js_of_ocaml_compiler.Stdlib
open Js_of_ocaml_compiler
let f () =
let output = stdout in
let new_line () = output_string output "\n" in
List.iter Js_of_ocaml_compiler_runtime_files.runtime ~f:(fun x ->
output_string output (Printf.sprintf "//# 1 %S" (Builtins.File.name x));
new_line ();
output_string output (Builtins.File.content x);
new_line ())
let info =
Info.make
~name:"print-standard-runtime"
~doc:"Print standard runtime to stdout"
~description:"js_of_ocaml-print-standard-runtime dump the standard runtime to stdout."
let command =
let t = Cmdliner.Term.(const f $ const ()) in
Cmdliner.Cmd.v info t
| |
b0b50c8e35cadb0aa98cca3bba12e89925fae5f9037c1f9697a63c9ca6529c99 | Eventuria/demonstration-gsd | WriteModelSpec.hs | # LANGUAGE QuasiQuotes #
# LANGUAGE InstanceSigs , TypeApplications #
module Eventuria.GSD.Write.Model.WriteModel.WriteModelSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Data.Aeson
import Eventuria.GSD.Write.Model.WriteModel.PropertyTesting.WriteModel ()
import Eventuria.GSD.Write.Model.WriteModel
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Gsd write Model" $ do
it "can be marshalled and unmarshalled"
$ property
$ \gsdState -> ((decode . encode) gsdState) == (Just (gsdState) :: Maybe (GsdWriteModel))
| null | https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/test/Eventuria/GSD/Write/Model/WriteModel/WriteModelSpec.hs | haskell | # LANGUAGE QuasiQuotes #
# LANGUAGE InstanceSigs , TypeApplications #
module Eventuria.GSD.Write.Model.WriteModel.WriteModelSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Data.Aeson
import Eventuria.GSD.Write.Model.WriteModel.PropertyTesting.WriteModel ()
import Eventuria.GSD.Write.Model.WriteModel
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Gsd write Model" $ do
it "can be marshalled and unmarshalled"
$ property
$ \gsdState -> ((decode . encode) gsdState) == (Just (gsdState) :: Maybe (GsdWriteModel))
| |
485b84b6d0329eee56e20179bc38bc4993acae91fac5d68bbb26eea0b3f6a38b | bef/erlswf | swfdt.erl | -module(swfdt).
-compile(export_all).
-include("swfdt.hrl").
-export([
ui16/1,
sb/1, sb/2,
encodedu32/1,
string/1,
rect/1,
matrix/1
]).
%%
%% primitive datatypes
%%
@doc decode 16 - bit unsigned integer
%% @spec ui16(binary()) -> {integer(), binary()}
ui16(<<X:16/unsigned-integer-little, Rest/binary>>) ->
{X, Rest}.
%% @doc decode signed-bit value (aka. sign extension)
@spec sb(bitstring ( ) ) - > integer ( )
sb(<<>>) -> <<>>; %% empty value (this should rarely occur)
sb(<<0:1, X/bitstring>>) -> %% positive value
Size = bit_size(X),
<<Value:Size/unsigned-integer-big>> = X,
Value;
sb(<<1:1, X/bitstring>>) -> %% negative value
Size = bit_size(X),
<<Value:64/signed-integer-big>> = <<16#ffffffffffffffff:(64-Size), X/bitstring>>,
Value.
sb(Bitstring, Count) ->
<<B:Count/bitstring, Rest/bitstring>> = Bitstring,
{sb(B), Rest}.
@doc decode 1 - 5 bit variable length u32
@spec encodedu32(binary ( ) ) - > { int ( ) , binary ( ) }
encodedu32(B) ->
encodedu32(B, 0, <<>>).
encodedu32(<<0:1, X:7/bitstring, Rest/binary>>, _Count, Acc) ->
BitValue = <<X/bitstring, Acc/bitstring>>,
Size = bit_size(BitValue),
<<Value35:Size/unsigned-integer-big>> = BitValue,
35bit - > 32bit
{Value, Rest};
encodedu32(<<1:1, X:7/bitstring, Rest/binary>>, Count, Acc) when Count < 4 ->
encodedu32(Rest, Count + 1, <<X/bitstring, Acc/bitstring>>).
%% @doc null-terminated string
%% @spec string(binary()) -> {string(), binary()}
string(S) -> string(S, []).
string(<<>>, Acc) -> string(<<0>>, Acc); %% not nerminated by 0 ?
string(<<0,R/binary>>, Acc) -> {list_to_binary(lists:reverse(Acc)), R};
string(<<A,R/binary>>, Acc) -> string(R, [A|Acc]).
%%
%% meta types and helpers
%%
condfun(0, _Fun, B) -> {none, B};
condfun(1, Fun, B) -> Fun(B).
%% @doc traverse B Count times using Fun
%% @spec metaarray(any(), integer(), fun()) -> {[any()], any()}
metaarray(B, Count, Fun) ->
metaarray(B, Count, Fun, []).
metaarray(B, 0, _Fun, Acc) ->
{lists:reverse(Acc), B};
metaarray(B, Count, Fun, Acc) ->
{Element, Rest} = Fun(B),
metaarray(Rest, Count - 1, Fun, [Element|Acc]).
%% @doc align bits to a byte by cutting off bits at the beginning
%% @spec bytealign(bitstring()) -> binary()
bytealign(Bitstring) ->
Padding = bit_size(Bitstring) rem 8,
<<_:Padding, B/binary>> = Bitstring,
B.
%%
%% data types
%%
rect(<<S:5/unsigned-integer,
Xmin:S/integer-signed-big,
Xmax:S/integer-signed-big,
Ymin:S/integer-signed-big,
Ymax:S/integer-signed-big,
B/bitstring>>) ->
{#rect{xmin=Xmin, xmax=Xmax, ymin=Ymin, ymax=Ymax}, bytealign(B)}.
%% @doc decode matrix into scale/rotate/translate tuples (bytealigned)
%% @spec matrix(binary()) -> {sbtuple(), sbtuple(), sbtuple()}
%% where sbtuple() = {float(), float()}
matrix(X) ->
{Scale, R1} = matrixsr(X),
{Rotate, R2} = matrixsr(R1),
{Translate, R3} = matrixtranslate(R2),
{{Scale, Rotate, Translate}, bytealign(R3)}.
matrixsr(<<0:1, B/bitstring>>) -> {{}, B}; %% scale/rotate
matrixsr(<<1:1, N:5, A:N/bitstring, B:N/bitstring, R/bitstring>>) ->
{{sb(A), sb(B)}, R}.
matrixtranslate(<<N:5, A:N/bitstring, B:N/bitstring, R/bitstring>>) ->
{{sb(A), sb(B)}, R}.
assets(B) ->
assets(B, []).
assets(<<>>, Acc) -> lists:reverse(Acc);
assets(<<CharID:16/unsigned-integer-little, B/binary>>, Acc) ->
{S, R} = string(B),
assets(R, [{CharID, S}|Acc]).
stringpool(B) ->
stringpool(B, []).
stringpool(<<>>, Acc) ->
lists:reverse(Acc);
stringpool(B, Acc) ->
{S, R} = string(B),
stringpool(R, [S|Acc]).
cstringpool(B, Count) ->
metaarray(B, Count, fun(X) -> {S, R} = string(X), {S, R} end).
registerparampool(B, Count) ->
metaarray(B, Count, fun(<<Register, X/binary>>) ->
{S, R} = string(X),
{{Register, S}, R}
end).
soundinfoenveloperecords(B, Count) ->
metaarray(B, Count, fun(<<Pos44:32/unsigned-integer-little,
LeftLevel:16/unsigned-integer-little,
RightLevel:16/unsigned-integer-little, R/binary>>) ->
{{Pos44, LeftLevel, RightLevel}, R}
end).
soundinfo(<<_Reserved:2, %% always 0
SyncStop:1,
SyncNoMultiple:1,
HasEnvelope:1,
HasLoops:1,
HasOutPoint:1,
HasInPoint:1,
B/binary>>) ->
InPointSize = 32 * HasInPoint,
<<InPoint:InPointSize/unsigned-integer-little, R1/binary>> = B,
OutPointSize = 32 * HasOutPoint,
<<OutPoint:OutPointSize/unsigned-integer-little, R2/binary>> = R1,
LoopsSize = 16 * HasLoops,
<<LoopCount:LoopsSize/unsigned-integer-little, R3/binary>> = R2,
EnvPointsSize = 8 * HasEnvelope,
<<EnvPoints:EnvPointsSize, R4/binary>> = R3,
{ER, _} = soundinfoenveloperecords(R4, EnvPoints),
{soundinfo, [
{syncStop, SyncStop},
{syncNoMultiple, SyncNoMultiple},
{inPoint, InPoint},
{outPoint, OutPoint},
{loopCount, LoopCount},
{envelopeRecords, ER}]}.
stylearray(B, Fun) ->
{SCount, SBin} = case B of
<<16#ff, Count:16/unsigned-integer-little, SB/binary>> ->
{Count, SB};
<<Count, SB/binary>> ->
{Count, SB}
end,
metaarray(SBin, SCount, Fun).
fillstylearray(Type, Bin) ->
Fun = fun(<<0, R, G, B, B1/binary>>) -> %% solid fill
{{rgb, R, G, B}, B1};
linear / radial gradient fill
{Matrix, B2} = matrix(B1),
{Gradient, B3} = gradient(Type, B2),
{{Matrix, Gradient}, B3};
(<<FSType, B1/binary>>) when FSType =:= 16#13 -> %% focal radial gradient fill
{FG, B2} = focalgradient(Type, B1),
{FG, B2};
(<<FSType, BitmapID:16/unsigned-integer-little, B1/binary>>) when FSType >= 16#40, FSType =< 16#43 -> %% bitmap fill
{Matrix, B2} = matrix(B1),
{{BitmapID, Matrix}, B2}%;
( < < FSType , / binary > > ) - >
debug("~p , nonesense ~ n " , [ FSType ] ) ,
{ FSType , nonesense , }
end,
stylearray(Bin, Fun).
gradient(Type, <<SpreadMode:2, InterpolationMode:2, NumGradients:4, B/binary>>) ->
{GradRecords, R} = gradrecords(Type, B, NumGradients),
{{SpreadMode, InterpolationMode, GradRecords}, R}.
gradrecords(Type, Bin, Count) ->
Fun = case Type of
shape1 -> fun(<<Ratio, R, G, B, Rest/binary>>) -> {{ratio_rgb, {Ratio, R, G, B}}, Rest} end
end,
metaarray(Bin, Count, Fun).
focalgradient(Type, B) ->
{gradient, {S, I, G}, <<FocalPoint, R/binary>>} = gradient(Type, B),
{focalgradient, {S, I, G, FocalPoint}, R}.
linestylearray(Type, Bin) ->
LineStyleRGB = fun(<<Width:16/unsigned-integer-little, R, G, B, Rest/binary>>) -> {{Width, {rgb, R, G, B}}, Rest} end,
Fun = case Type of
shape1 -> LineStyleRGB
end,
stylearray(Bin, Fun).
buttonrecord(<<0:2, %% reserved
_HasBlendMode:1,
_HasFilterList:1,
StateHitTest:1,
StateDown:1,
StateOver:1,
StateUp:1,
CharacterID:16/unsigned-integer-little,
PlaceDepth:16/unsigned-integer-little,
B/binary>>) ->
{PlaceMatrix, Rest} = matrix(B),
{buttonrecord, [{stateHitTest, StateHitTest},
{stateDown, StateDown},
{stateOver, StateOver},
{stateUp, StateUp},
{characterID, CharacterID},
{placeDepth, PlaceDepth},
{placeMatrix, PlaceMatrix}], Rest}.
% buttonrecord2(<<0:2,
HasBlendMode:1 ,
% HasFilterList:1,
% _/bitstring>> = B) ->
{ buttonrecord , BR , R1 } = buttonrecord(B ) ,
{ cxformwithalpha , CX , R2 } = cxformwithalpha(R1 ) ,
{ filterlist , FL , R3 } = filterlistcond(HasFilterList , R2 ) ,
{ blendmode , BM , R4 } = case HasBlendMode of
% 0 -> {blendmode, none, R3};
1 - > < < BlendMode , R5 / binary > > = R3 , { blendmode , BlendMode , R5 }
% end,
{ buttonrecord , [ { cxFormWithAlpha , CX } , { filterList , FL } , { blendMode , BM}|BR ] , R4 } .
records(B, Fun) ->
records(B, Fun, []).
records(<<0, R/binary>>, _Fun, Acc) ->
{lists:reverse(Acc), R};
records(<<>>, _Fun, Acc) -> %% unconventional end of block
{lists:reverse(Acc), <<>>};
records(B, Fun, Acc) ->
{BR, Rest} = Fun(B),
records(Rest, [BR|Acc]).
buttonrecords(B) ->
records(B, fun(X) ->
{buttonrecord, BR, Rest} = buttonrecord(X),
{BR, Rest}
end).
%buttonrecords2(B) ->
records(B , fun(X ) - >
{ buttonrecord , BR , Rest } = buttonrecord2(X ) ,
% {BR, Rest}
% end).
%
cxform(<<HasAddTerms:1, HasMultTerms:1, N:4, BS/bitstring>>) ->
{MT, BS1} = case HasMultTerms of
0 -> {#cxform{}, BS};
1 -> <<R:N/bitstring, G:N/bitstring, B:N/bitstring, R1/bitstring>> = BS, {#cxform{redmult=sb(R), greenmult=sb(G), bluemult=sb(B)}, R1}
end,
{AT, BS2} = case HasAddTerms of
0 -> {MT, BS1};
1 -> <<Ra:N/bitstring, Ga:N/bitstring, Ba:N/bitstring, R2/bitstring>> = BS1, {MT#cxform{redadd=sb(Ra), greenadd=sb(Ga), blueadd=sb(Ba)}, R2}
end,
{AT, bytealign(BS2)}.
cxformwithalpha(<<HasAddTerms:1, HasMultTerms:1, N:4, BS/bitstring>>) ->
{MT, BS1} = case HasMultTerms of
0 -> {#cxformwa{}, BS};
1 -> <<R:N/bitstring, G:N/bitstring, B:N/bitstring, A:N/bitstring, R1/bitstring>> = BS, {#cxformwa{redmult=sb(R), greenmult=sb(G), bluemult=sb(B), alphamult=sb(A)}, R1}
end,
{AT, BS2} = case HasAddTerms of
0 -> {MT, BS1};
1 -> <<Ra:N/bitstring, Ga:N/bitstring, Ba:N/bitstring, Aa:N/bitstring, R2/bitstring>> = BS1, {MT#cxformwa{redadd=sb(Ra), greenadd=sb(Ga), blueadd=sb(Ba), alphaadd=sb(Aa)}, R2}
end,
{AT, bytealign(BS2)}.
%filterlistcond(0, B) -> {filterlist, none, B};
%filterlistcond(1, B) -> filterlist(B).
%
%filterlist(<<N, B/binary>>) ->
% metaarray(B, N, fun filter/1).
%
%filter(<<0,
% R, G, B, A,
BlurX:32 / bitstring ,
BlurY:32 / bitstring ,
/ bitstring ,
% Distance:32/bitstring,
% Strength:16/bitstring,
% InnerShadow:1,
Knockout:1 ,
% CompositeSource:1,
Passes:5 ,
% Rest/binary>>) ->
% {{dropShadowFilter,
% [{id, 0},
% {dropShadowColor, {rgba, R, G, B, A}},
% {blurX, BlurX},
% {blurY, BlurY},
% {angle, Angle},
% {distance, Distance},
% {strength, Strength},
% {innerShadow, InnerShadow},
% {knockout, Knockout},
{ compositeSource , CompositeSource } ,
% {passes, Passes}]},
% Rest};
%filter(<<Id, Rest/binary>>) ->
{ { , [ { i d , I d } ] } , Rest } .
style(<<NumFillBits:4 , , B / binary > > ) - >
% {foo, B}.
shaperecords(B ) - >
% stylerecords(B, []).
shaperecords(<<0:1 , 0:5 , _ : 2 , Rest / binary > > , Acc ) - > % % end shape record
{ lists : reverse(Acc ) , Rest } ;
shaperecords ( < < > > , Acc ) - > % % abrupt end of stylerecords
{ lists : reverse(Acc ) , < < > > } ;
shaperecords(B , Acc ) - >
{ SR , R } = stylerecord(B ) ,
stylerecords(R , [ SR|Acc ] ) .
shaperecord(<<0:1 , % % type flag
% StateNewStyles:1,
StateLineStyle:1 ,
StateFillStyle1:1 ,
% StateFillStyle0:1,
% StateMoveTo:1,
% B/binary>>) -> %% change shape record
% {Move, R1} = case StateMoveTo of
1 - >
< < N:5 , DX : N / bitstring , DY : N / bitstring , R / bitstring > > = B ,
{ { DX , DY } , R } ;
% 0 -> {none, B}
% end,
% {FS0, R2} = case StateFillStyle0 of
1 - >
% <<...>>,
% {foo, B}.
%textrecords(Params, B) ->
% textrecords(Params, B, []).
textrecords(_Params , < < 0:1,_:7 , B / binary > > , Acc ) - >
{ textrecords , lists : reverse(Acc ) , B } ;
textrecords({GB , AB , IsDefineText2 } , B , Acc ) - >
{ textrecord , TR , R } = textrecord(B , IsDefineText2 , GB , AB ) ,
% textrecords(GB, AB, R, [TR|Acc]).
%
textrecordfield(fontID , 1 , < < FontID:16 / unsigned - integer - little , B / binary > > ) - > { FontID , B } ;
textrecordfield({textColor , 0 } , 1 , B ) - >
{ rgb , RGB , Rest } = rgb(B ) ,
{ { rgb , RGB } , Rest } ;
textrecordfield({textColor , 1 } , 1 , B ) - >
{ argb , ARGB , Rest } = argb(B ) ,
{ { argb , ARGB } , Rest } ;
textrecordfield(offset , 1 , < < Offset:16 / signed - integer - little , B / binary > > ) - > { Offset , B } ;
%textrecordfield(offset, 0, B) -> {0, B};
textrecordfield(textHeight , 1 , < < / unsigned - integer - little , B / binary > > ) - > { Height , B } ;
%textrecordfield(_Name, 0 = _Defined, B) -> {none, B}.
%
textrecord(<<_TextRecordType:1 , % % always 1
_ StyleFlagsReserved:3 , % % always 0
StyleFlagsHasFont:1 ,
% StyleFlagsHasColor:1,
% StyleFlagsHasXOffset:1,
StyleFlagsHasYOffset:1 ,
B / binary > > , IsDefineText2 , GlyphBits , AdvanceBits ) - >
{ FontID , R1 } = textrecordfield(fontID , StyleFlagsHasFont , B ) ,
{ TextColor , R2 } = textrecordfield({textColor , IsDefineText2 } , StyleFlagsHasColor , R1 ) ,
{ XOffset , R3 } = textrecordfield(offset , StyleFlagsHasXOffset , R2 ) ,
% {YOffset, R4} = textrecordfield(offset, StyleFlagsHasYOffset, R3),
{ TextHeight , < < GlyphCount , R5 / binary > > } = textrecordfield(textHeight , StyleFlagsHasFont , R4 ) ,
% glyphs, %% ????
{ textrecord , [
{ fontID , } ,
{ textColor , TextColor } ,
{ xOffset , } ,
% {yOffset, YOffset},
{ textHeight , TextHeight } ] , Rest } .
clipactions(<<0:16, %% reserved
B/binary>>) ->
{unimplemented, B}.
rgb(<<R, G, B, Rest/binary>>) -> {{rgb, R, G, B}, Rest}.
rgba(<<R, G, B, A, Rest/binary>>) -> {{rgba, R, G, B, A}, Rest}.
argb(<<A, R, G, B, Rest/binary>>) -> {{argb, A, R, G, B}, Rest}.
buttoncondactions(B) ->
buttoncondactions(B, []).
buttoncondactions(<<Size:16/unsigned-integer-little, R/binary>> = B, Acc) ->
Acc2 = [buttoncondaction(R)|Acc],
<<_Skip:Size/binary, NextB/binary>> = B,
case Size of
0 -> lists:reverse(Acc2);
_ -> buttoncondactions(NextB, Acc2)
end.
buttoncondaction(<<Conditions:16, R/binary>>) ->
{actions, Actions, _} = swfaction:actionrecords(R),
{buttoncondaction, Actions, Conditions}.
| null | https://raw.githubusercontent.com/bef/erlswf/1397591d012aaa020f9ffc0ecd5436e65814e668/src/swfdt.erl | erlang |
primitive datatypes
@spec ui16(binary()) -> {integer(), binary()}
@doc decode signed-bit value (aka. sign extension)
empty value (this should rarely occur)
positive value
negative value
@doc null-terminated string
@spec string(binary()) -> {string(), binary()}
not nerminated by 0 ?
meta types and helpers
@doc traverse B Count times using Fun
@spec metaarray(any(), integer(), fun()) -> {[any()], any()}
@doc align bits to a byte by cutting off bits at the beginning
@spec bytealign(bitstring()) -> binary()
data types
@doc decode matrix into scale/rotate/translate tuples (bytealigned)
@spec matrix(binary()) -> {sbtuple(), sbtuple(), sbtuple()}
where sbtuple() = {float(), float()}
scale/rotate
always 0
solid fill
focal radial gradient fill
bitmap fill
;
reserved
buttonrecord2(<<0:2,
HasFilterList:1,
_/bitstring>> = B) ->
0 -> {blendmode, none, R3};
end,
unconventional end of block
buttonrecords2(B) ->
{BR, Rest}
end).
filterlistcond(0, B) -> {filterlist, none, B};
filterlistcond(1, B) -> filterlist(B).
filterlist(<<N, B/binary>>) ->
metaarray(B, N, fun filter/1).
filter(<<0,
R, G, B, A,
Distance:32/bitstring,
Strength:16/bitstring,
InnerShadow:1,
CompositeSource:1,
Rest/binary>>) ->
{{dropShadowFilter,
[{id, 0},
{dropShadowColor, {rgba, R, G, B, A}},
{blurX, BlurX},
{blurY, BlurY},
{angle, Angle},
{distance, Distance},
{strength, Strength},
{innerShadow, InnerShadow},
{knockout, Knockout},
{passes, Passes}]},
Rest};
filter(<<Id, Rest/binary>>) ->
{foo, B}.
stylerecords(B, []).
% end shape record
% abrupt end of stylerecords
% type flag
StateNewStyles:1,
StateFillStyle0:1,
StateMoveTo:1,
B/binary>>) -> %% change shape record
{Move, R1} = case StateMoveTo of
0 -> {none, B}
end,
{FS0, R2} = case StateFillStyle0 of
<<...>>,
{foo, B}.
textrecords(Params, B) ->
textrecords(Params, B, []).
textrecords(GB, AB, R, [TR|Acc]).
textrecordfield(offset, 0, B) -> {0, B};
textrecordfield(_Name, 0 = _Defined, B) -> {none, B}.
% always 1
% always 0
StyleFlagsHasColor:1,
StyleFlagsHasXOffset:1,
{YOffset, R4} = textrecordfield(offset, StyleFlagsHasYOffset, R3),
glyphs, %% ????
{yOffset, YOffset},
reserved | -module(swfdt).
-compile(export_all).
-include("swfdt.hrl").
-export([
ui16/1,
sb/1, sb/2,
encodedu32/1,
string/1,
rect/1,
matrix/1
]).
@doc decode 16 - bit unsigned integer
ui16(<<X:16/unsigned-integer-little, Rest/binary>>) ->
{X, Rest}.
@spec sb(bitstring ( ) ) - > integer ( )
Size = bit_size(X),
<<Value:Size/unsigned-integer-big>> = X,
Value;
Size = bit_size(X),
<<Value:64/signed-integer-big>> = <<16#ffffffffffffffff:(64-Size), X/bitstring>>,
Value.
sb(Bitstring, Count) ->
<<B:Count/bitstring, Rest/bitstring>> = Bitstring,
{sb(B), Rest}.
@doc decode 1 - 5 bit variable length u32
@spec encodedu32(binary ( ) ) - > { int ( ) , binary ( ) }
encodedu32(B) ->
encodedu32(B, 0, <<>>).
encodedu32(<<0:1, X:7/bitstring, Rest/binary>>, _Count, Acc) ->
BitValue = <<X/bitstring, Acc/bitstring>>,
Size = bit_size(BitValue),
<<Value35:Size/unsigned-integer-big>> = BitValue,
35bit - > 32bit
{Value, Rest};
encodedu32(<<1:1, X:7/bitstring, Rest/binary>>, Count, Acc) when Count < 4 ->
encodedu32(Rest, Count + 1, <<X/bitstring, Acc/bitstring>>).
string(S) -> string(S, []).
string(<<0,R/binary>>, Acc) -> {list_to_binary(lists:reverse(Acc)), R};
string(<<A,R/binary>>, Acc) -> string(R, [A|Acc]).
condfun(0, _Fun, B) -> {none, B};
condfun(1, Fun, B) -> Fun(B).
metaarray(B, Count, Fun) ->
metaarray(B, Count, Fun, []).
metaarray(B, 0, _Fun, Acc) ->
{lists:reverse(Acc), B};
metaarray(B, Count, Fun, Acc) ->
{Element, Rest} = Fun(B),
metaarray(Rest, Count - 1, Fun, [Element|Acc]).
bytealign(Bitstring) ->
Padding = bit_size(Bitstring) rem 8,
<<_:Padding, B/binary>> = Bitstring,
B.
rect(<<S:5/unsigned-integer,
Xmin:S/integer-signed-big,
Xmax:S/integer-signed-big,
Ymin:S/integer-signed-big,
Ymax:S/integer-signed-big,
B/bitstring>>) ->
{#rect{xmin=Xmin, xmax=Xmax, ymin=Ymin, ymax=Ymax}, bytealign(B)}.
matrix(X) ->
{Scale, R1} = matrixsr(X),
{Rotate, R2} = matrixsr(R1),
{Translate, R3} = matrixtranslate(R2),
{{Scale, Rotate, Translate}, bytealign(R3)}.
matrixsr(<<1:1, N:5, A:N/bitstring, B:N/bitstring, R/bitstring>>) ->
{{sb(A), sb(B)}, R}.
matrixtranslate(<<N:5, A:N/bitstring, B:N/bitstring, R/bitstring>>) ->
{{sb(A), sb(B)}, R}.
assets(B) ->
assets(B, []).
assets(<<>>, Acc) -> lists:reverse(Acc);
assets(<<CharID:16/unsigned-integer-little, B/binary>>, Acc) ->
{S, R} = string(B),
assets(R, [{CharID, S}|Acc]).
stringpool(B) ->
stringpool(B, []).
stringpool(<<>>, Acc) ->
lists:reverse(Acc);
stringpool(B, Acc) ->
{S, R} = string(B),
stringpool(R, [S|Acc]).
cstringpool(B, Count) ->
metaarray(B, Count, fun(X) -> {S, R} = string(X), {S, R} end).
registerparampool(B, Count) ->
metaarray(B, Count, fun(<<Register, X/binary>>) ->
{S, R} = string(X),
{{Register, S}, R}
end).
soundinfoenveloperecords(B, Count) ->
metaarray(B, Count, fun(<<Pos44:32/unsigned-integer-little,
LeftLevel:16/unsigned-integer-little,
RightLevel:16/unsigned-integer-little, R/binary>>) ->
{{Pos44, LeftLevel, RightLevel}, R}
end).
SyncStop:1,
SyncNoMultiple:1,
HasEnvelope:1,
HasLoops:1,
HasOutPoint:1,
HasInPoint:1,
B/binary>>) ->
InPointSize = 32 * HasInPoint,
<<InPoint:InPointSize/unsigned-integer-little, R1/binary>> = B,
OutPointSize = 32 * HasOutPoint,
<<OutPoint:OutPointSize/unsigned-integer-little, R2/binary>> = R1,
LoopsSize = 16 * HasLoops,
<<LoopCount:LoopsSize/unsigned-integer-little, R3/binary>> = R2,
EnvPointsSize = 8 * HasEnvelope,
<<EnvPoints:EnvPointsSize, R4/binary>> = R3,
{ER, _} = soundinfoenveloperecords(R4, EnvPoints),
{soundinfo, [
{syncStop, SyncStop},
{syncNoMultiple, SyncNoMultiple},
{inPoint, InPoint},
{outPoint, OutPoint},
{loopCount, LoopCount},
{envelopeRecords, ER}]}.
stylearray(B, Fun) ->
{SCount, SBin} = case B of
<<16#ff, Count:16/unsigned-integer-little, SB/binary>> ->
{Count, SB};
<<Count, SB/binary>> ->
{Count, SB}
end,
metaarray(SBin, SCount, Fun).
fillstylearray(Type, Bin) ->
{{rgb, R, G, B}, B1};
linear / radial gradient fill
{Matrix, B2} = matrix(B1),
{Gradient, B3} = gradient(Type, B2),
{{Matrix, Gradient}, B3};
{FG, B2} = focalgradient(Type, B1),
{FG, B2};
{Matrix, B2} = matrix(B1),
( < < FSType , / binary > > ) - >
debug("~p , nonesense ~ n " , [ FSType ] ) ,
{ FSType , nonesense , }
end,
stylearray(Bin, Fun).
gradient(Type, <<SpreadMode:2, InterpolationMode:2, NumGradients:4, B/binary>>) ->
{GradRecords, R} = gradrecords(Type, B, NumGradients),
{{SpreadMode, InterpolationMode, GradRecords}, R}.
gradrecords(Type, Bin, Count) ->
Fun = case Type of
shape1 -> fun(<<Ratio, R, G, B, Rest/binary>>) -> {{ratio_rgb, {Ratio, R, G, B}}, Rest} end
end,
metaarray(Bin, Count, Fun).
focalgradient(Type, B) ->
{gradient, {S, I, G}, <<FocalPoint, R/binary>>} = gradient(Type, B),
{focalgradient, {S, I, G, FocalPoint}, R}.
linestylearray(Type, Bin) ->
LineStyleRGB = fun(<<Width:16/unsigned-integer-little, R, G, B, Rest/binary>>) -> {{Width, {rgb, R, G, B}}, Rest} end,
Fun = case Type of
shape1 -> LineStyleRGB
end,
stylearray(Bin, Fun).
_HasBlendMode:1,
_HasFilterList:1,
StateHitTest:1,
StateDown:1,
StateOver:1,
StateUp:1,
CharacterID:16/unsigned-integer-little,
PlaceDepth:16/unsigned-integer-little,
B/binary>>) ->
{PlaceMatrix, Rest} = matrix(B),
{buttonrecord, [{stateHitTest, StateHitTest},
{stateDown, StateDown},
{stateOver, StateOver},
{stateUp, StateUp},
{characterID, CharacterID},
{placeDepth, PlaceDepth},
{placeMatrix, PlaceMatrix}], Rest}.
HasBlendMode:1 ,
{ buttonrecord , BR , R1 } = buttonrecord(B ) ,
{ cxformwithalpha , CX , R2 } = cxformwithalpha(R1 ) ,
{ filterlist , FL , R3 } = filterlistcond(HasFilterList , R2 ) ,
{ blendmode , BM , R4 } = case HasBlendMode of
1 - > < < BlendMode , R5 / binary > > = R3 , { blendmode , BlendMode , R5 }
{ buttonrecord , [ { cxFormWithAlpha , CX } , { filterList , FL } , { blendMode , BM}|BR ] , R4 } .
records(B, Fun) ->
records(B, Fun, []).
records(<<0, R/binary>>, _Fun, Acc) ->
{lists:reverse(Acc), R};
{lists:reverse(Acc), <<>>};
records(B, Fun, Acc) ->
{BR, Rest} = Fun(B),
records(Rest, [BR|Acc]).
buttonrecords(B) ->
records(B, fun(X) ->
{buttonrecord, BR, Rest} = buttonrecord(X),
{BR, Rest}
end).
records(B , fun(X ) - >
{ buttonrecord , BR , Rest } = buttonrecord2(X ) ,
cxform(<<HasAddTerms:1, HasMultTerms:1, N:4, BS/bitstring>>) ->
{MT, BS1} = case HasMultTerms of
0 -> {#cxform{}, BS};
1 -> <<R:N/bitstring, G:N/bitstring, B:N/bitstring, R1/bitstring>> = BS, {#cxform{redmult=sb(R), greenmult=sb(G), bluemult=sb(B)}, R1}
end,
{AT, BS2} = case HasAddTerms of
0 -> {MT, BS1};
1 -> <<Ra:N/bitstring, Ga:N/bitstring, Ba:N/bitstring, R2/bitstring>> = BS1, {MT#cxform{redadd=sb(Ra), greenadd=sb(Ga), blueadd=sb(Ba)}, R2}
end,
{AT, bytealign(BS2)}.
cxformwithalpha(<<HasAddTerms:1, HasMultTerms:1, N:4, BS/bitstring>>) ->
{MT, BS1} = case HasMultTerms of
0 -> {#cxformwa{}, BS};
1 -> <<R:N/bitstring, G:N/bitstring, B:N/bitstring, A:N/bitstring, R1/bitstring>> = BS, {#cxformwa{redmult=sb(R), greenmult=sb(G), bluemult=sb(B), alphamult=sb(A)}, R1}
end,
{AT, BS2} = case HasAddTerms of
0 -> {MT, BS1};
1 -> <<Ra:N/bitstring, Ga:N/bitstring, Ba:N/bitstring, Aa:N/bitstring, R2/bitstring>> = BS1, {MT#cxformwa{redadd=sb(Ra), greenadd=sb(Ga), blueadd=sb(Ba), alphaadd=sb(Aa)}, R2}
end,
{AT, bytealign(BS2)}.
BlurX:32 / bitstring ,
BlurY:32 / bitstring ,
/ bitstring ,
Knockout:1 ,
Passes:5 ,
{ compositeSource , CompositeSource } ,
{ { , [ { i d , I d } ] } , Rest } .
style(<<NumFillBits:4 , , B / binary > > ) - >
shaperecords(B ) - >
{ lists : reverse(Acc ) , Rest } ;
{ lists : reverse(Acc ) , < < > > } ;
shaperecords(B , Acc ) - >
{ SR , R } = stylerecord(B ) ,
stylerecords(R , [ SR|Acc ] ) .
StateLineStyle:1 ,
StateFillStyle1:1 ,
1 - >
< < N:5 , DX : N / bitstring , DY : N / bitstring , R / bitstring > > = B ,
{ { DX , DY } , R } ;
1 - >
textrecords(_Params , < < 0:1,_:7 , B / binary > > , Acc ) - >
{ textrecords , lists : reverse(Acc ) , B } ;
textrecords({GB , AB , IsDefineText2 } , B , Acc ) - >
{ textrecord , TR , R } = textrecord(B , IsDefineText2 , GB , AB ) ,
textrecordfield(fontID , 1 , < < FontID:16 / unsigned - integer - little , B / binary > > ) - > { FontID , B } ;
textrecordfield({textColor , 0 } , 1 , B ) - >
{ rgb , RGB , Rest } = rgb(B ) ,
{ { rgb , RGB } , Rest } ;
textrecordfield({textColor , 1 } , 1 , B ) - >
{ argb , ARGB , Rest } = argb(B ) ,
{ { argb , ARGB } , Rest } ;
textrecordfield(offset , 1 , < < Offset:16 / signed - integer - little , B / binary > > ) - > { Offset , B } ;
textrecordfield(textHeight , 1 , < < / unsigned - integer - little , B / binary > > ) - > { Height , B } ;
StyleFlagsHasFont:1 ,
StyleFlagsHasYOffset:1 ,
B / binary > > , IsDefineText2 , GlyphBits , AdvanceBits ) - >
{ FontID , R1 } = textrecordfield(fontID , StyleFlagsHasFont , B ) ,
{ TextColor , R2 } = textrecordfield({textColor , IsDefineText2 } , StyleFlagsHasColor , R1 ) ,
{ XOffset , R3 } = textrecordfield(offset , StyleFlagsHasXOffset , R2 ) ,
{ TextHeight , < < GlyphCount , R5 / binary > > } = textrecordfield(textHeight , StyleFlagsHasFont , R4 ) ,
{ textrecord , [
{ fontID , } ,
{ textColor , TextColor } ,
{ xOffset , } ,
{ textHeight , TextHeight } ] , Rest } .
B/binary>>) ->
{unimplemented, B}.
rgb(<<R, G, B, Rest/binary>>) -> {{rgb, R, G, B}, Rest}.
rgba(<<R, G, B, A, Rest/binary>>) -> {{rgba, R, G, B, A}, Rest}.
argb(<<A, R, G, B, Rest/binary>>) -> {{argb, A, R, G, B}, Rest}.
buttoncondactions(B) ->
buttoncondactions(B, []).
buttoncondactions(<<Size:16/unsigned-integer-little, R/binary>> = B, Acc) ->
Acc2 = [buttoncondaction(R)|Acc],
<<_Skip:Size/binary, NextB/binary>> = B,
case Size of
0 -> lists:reverse(Acc2);
_ -> buttoncondactions(NextB, Acc2)
end.
buttoncondaction(<<Conditions:16, R/binary>>) ->
{actions, Actions, _} = swfaction:actionrecords(R),
{buttoncondaction, Actions, Conditions}.
|
704947deae93f25efad1a8f99c0ab56dcb991b0b003b3acf593a0f68941eca69 | ucsd-progsys/liquidhaskell | BadDataConType2.hs | {-@ LIQUID "--expect-error-containing=different numbers of fields for `BadDataConType2.C`" @-}
module BadDataConType2 where
{-@ data T = C { fldX :: Int } @-}
data T = C { fldX :: Int, fldY :: Int }
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/BadDataConType2.hs | haskell | @ LIQUID "--expect-error-containing=different numbers of fields for `BadDataConType2.C`" @
@ data T = C { fldX :: Int } @ | module BadDataConType2 where
data T = C { fldX :: Int, fldY :: Int }
|
2a3ddce5513adafc368ccf63656304a004e487fba6f176dec15a98e6c66e6103 | jbclements/RSound | paste-util.rkt | #lang racket/base
(require "rsound.rkt"
"private/s16vector-add.rkt"
ffi/unsafe
ffi/vector)
;; almost-safe (tm) utilities for copying sounds.
;; if you don't lie about the target buffer and its length,
;; you'll be safe.
(provide zero-buffer!
rs-copy-add!
rs-copy-mult-add!)
(define frame-size (* CHANNELS s16-size))
(define (frames->bytes f) (* frame-size f))
;; given a cpointer and a length in frames,
fill it with zeros .
(define (zero-buffer! buf len)
(memset buf 0 (frames->bytes len)))
;; given a target cpointer and an offset in frames
;; and a source rsound and an offset in frames
;; and a number of frames to copy and the length
;; of the target buffer in frames, check that we're not
;; reading or writing off the end of either buffer
;; and then do a copy-and-add.
(define (rs-copy-add! tgt tgt-offset
src src-offset
copy-frames buf-frames)
(unless (cpointer? tgt)
(raise-type-error 'rs-copy-add! "cpointer" 0 tgt tgt-offset
src src-offset
copy-frames buf-frames))
(unless (<= 0 tgt-offset (+ tgt-offset copy-frames) buf-frames)
(error 'rs-copy-add! "tgt bounds violation, must have (0 <= ~s <= ~s <= ~s)"
tgt-offset (+ tgt-offset copy-frames) buf-frames))
(unless (<= 0 src-offset (+ src-offset copy-frames)(rs-frames src))
(error 'rs-copy-add! "src bounds violation, must have (0 <= ~s <= ~s <= ~s)"
src-offset
(+ src-offset copy-frames)
(rs-frames src)))
(define tgt-ptr (ptr-add tgt (frames->bytes tgt-offset)))
(define src-real-offset (+ src-offset (rsound-start src)))
(define src-ptr (ptr-add (s16vector->cpointer (rsound-data src))
(frames->bytes src-real-offset)))
(s16buffer-add!/c tgt-ptr src-ptr (* CHANNELS copy-frames)))
;; same as prior function, but multiply by 'factor' before adding.
(define (rs-copy-mult-add! tgt tgt-offset
src src-offset
copy-frames buf-frames
factor)
(unless (cpointer? tgt)
(raise-type-error 'rs-copy-add! "cpointer" 0 tgt tgt-offset
src src-offset
copy-frames buf-frames))
(unless (<= 0 tgt-offset (+ tgt-offset copy-frames) buf-frames)
(error 'rs-copy-add! "tgt bounds violation, must have (0 <= ~s <= ~s <= ~s)"
tgt-offset (+ tgt-offset copy-frames) buf-frames))
(unless (<= 0 src-offset (+ src-offset copy-frames)(rs-frames src))
(error 'rs-copy-add! "src bounds violation, must have (0 <= ~s <= ~s <= ~s)"
src-offset
(+ src-offset copy-frames)
(rs-frames src)))
(unless (real? factor)
(raise-argument-error 'rs-copy-mult-add! "nonnegative number" 6
tgt tgt-offset src src-offset copy-frames buf-frames factor))
(define tgt-ptr (ptr-add tgt (frames->bytes tgt-offset)))
(define src-real-offset (+ src-offset (rsound-start src)))
(define src-ptr (ptr-add (s16vector->cpointer (rsound-data src))
(frames->bytes src-real-offset)))
(s16buffer-mult-add!/c tgt-ptr src-ptr (* CHANNELS copy-frames) factor)) | null | https://raw.githubusercontent.com/jbclements/RSound/c699db1ffae4cf0185c46bdc059d7879d40614ce/rsound/paste-util.rkt | racket | almost-safe (tm) utilities for copying sounds.
if you don't lie about the target buffer and its length,
you'll be safe.
given a cpointer and a length in frames,
given a target cpointer and an offset in frames
and a source rsound and an offset in frames
and a number of frames to copy and the length
of the target buffer in frames, check that we're not
reading or writing off the end of either buffer
and then do a copy-and-add.
same as prior function, but multiply by 'factor' before adding. | #lang racket/base
(require "rsound.rkt"
"private/s16vector-add.rkt"
ffi/unsafe
ffi/vector)
(provide zero-buffer!
rs-copy-add!
rs-copy-mult-add!)
(define frame-size (* CHANNELS s16-size))
(define (frames->bytes f) (* frame-size f))
fill it with zeros .
(define (zero-buffer! buf len)
(memset buf 0 (frames->bytes len)))
(define (rs-copy-add! tgt tgt-offset
src src-offset
copy-frames buf-frames)
(unless (cpointer? tgt)
(raise-type-error 'rs-copy-add! "cpointer" 0 tgt tgt-offset
src src-offset
copy-frames buf-frames))
(unless (<= 0 tgt-offset (+ tgt-offset copy-frames) buf-frames)
(error 'rs-copy-add! "tgt bounds violation, must have (0 <= ~s <= ~s <= ~s)"
tgt-offset (+ tgt-offset copy-frames) buf-frames))
(unless (<= 0 src-offset (+ src-offset copy-frames)(rs-frames src))
(error 'rs-copy-add! "src bounds violation, must have (0 <= ~s <= ~s <= ~s)"
src-offset
(+ src-offset copy-frames)
(rs-frames src)))
(define tgt-ptr (ptr-add tgt (frames->bytes tgt-offset)))
(define src-real-offset (+ src-offset (rsound-start src)))
(define src-ptr (ptr-add (s16vector->cpointer (rsound-data src))
(frames->bytes src-real-offset)))
(s16buffer-add!/c tgt-ptr src-ptr (* CHANNELS copy-frames)))
(define (rs-copy-mult-add! tgt tgt-offset
src src-offset
copy-frames buf-frames
factor)
(unless (cpointer? tgt)
(raise-type-error 'rs-copy-add! "cpointer" 0 tgt tgt-offset
src src-offset
copy-frames buf-frames))
(unless (<= 0 tgt-offset (+ tgt-offset copy-frames) buf-frames)
(error 'rs-copy-add! "tgt bounds violation, must have (0 <= ~s <= ~s <= ~s)"
tgt-offset (+ tgt-offset copy-frames) buf-frames))
(unless (<= 0 src-offset (+ src-offset copy-frames)(rs-frames src))
(error 'rs-copy-add! "src bounds violation, must have (0 <= ~s <= ~s <= ~s)"
src-offset
(+ src-offset copy-frames)
(rs-frames src)))
(unless (real? factor)
(raise-argument-error 'rs-copy-mult-add! "nonnegative number" 6
tgt tgt-offset src src-offset copy-frames buf-frames factor))
(define tgt-ptr (ptr-add tgt (frames->bytes tgt-offset)))
(define src-real-offset (+ src-offset (rsound-start src)))
(define src-ptr (ptr-add (s16vector->cpointer (rsound-data src))
(frames->bytes src-real-offset)))
(s16buffer-mult-add!/c tgt-ptr src-ptr (* CHANNELS copy-frames) factor)) |
a25aca1b8d3cd06c881006e05f557ed95a9dd890824f6ba5a9e97c3afb2a11d2 | etarasov/iptadmin | Render.hs | {-# LANGUAGE OverloadedStrings #-}
module IptAdmin.EditForm.Render where
import Data.Monoid
import Data.Set (member)
import Data.String
import IptAdmin.EditForm.Class
import IptAdmin.EditForm.Types
import Iptables.Types
import Text.Blaze
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
checkBox :: String -> Bool -> Markup
checkBox name on = do
let chBox = H.input ! A.type_ "checkbox"
! A.id (fromString name)
! A.name (fromString name)
! A.value "on"
if on then chBox ! A.checked "checked"
else chBox
printMesTd :: ResMessage -> Markup
printMesTd rm = H.td $ fromString $ case rm of
RMError mes -> mes
RMSucc mes -> "ok " ++ mes
RMIgnore -> "ignored"
maybeListToListMaybe :: Maybe [a] -> [Maybe a]
maybeListToListMaybe (Just list) = map Just list
maybeListToListMaybe Nothing = repeat Nothing
editFormHtml :: EditForm a => (String,String,Int,[String]) -> a -> Maybe [ResMessage] -> Markup
editFormHtml (tableName, chainName, rulePos, userChainNames) form errorListMay =
let entryList = toEntryList form
mesListMay = maybeListToListMaybe errorListMay
in
H.div ! A.class_ "editForm" $
H.form ! A.id "editform" ! A.method "post" $ do
H.input ! A.type_ "hidden" ! A.name "table" ! A.value (fromString tableName)
H.input ! A.type_ "hidden" ! A.name "chain" ! A.value (fromString chainName)
H.input ! A.type_ "hidden" ! A.name "rulePos" ! A.value (fromString $ show rulePos)
H.table ! A.class_ "editForm" $ do
H.tr $ do
H.th "Option"
H.th "Not"
H.th "Parameter"
maybe mempty (\_-> H.th "Message") errorListMay
mapM_ (renderFormEntry userChainNames) $ zip entryList mesListMay
renderFormEntry :: [String] -> (FormEntry, Maybe ResMessage) -> Markup
renderFormEntry _ (FESrc en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "sourceEnable"
$ "Source"
H.br
checkBox "sourceEnable" en
H.td $ do
H.label ! A.for "sourceInv"
$ "!"
checkBox "sourceInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "source" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEDst en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "destinationEnable"
$ "Destination"
H.br
checkBox "destinationEnable" en
H.td $ do
H.label ! A.for "destinationInv"
$ "!"
checkBox "destinationInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "destination" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEProt en inv prot, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "protocolEnable"
$ "Protocol"
H.br
checkBox "protocolEnable" en
H.td $ do
H.label ! A.for "protocolInv"
$ "!"
checkBox "protocolInv" inv
H.td $
H.select ! A.id "protocol" ! A.name "protocol" $ do
let tcpOpt = H.option ! A.value "tcp" $ "TCP"
let udpOpt = H.option ! A.value "udp" $ "UDP"
let icmpOpt = H.option ! A.value "icmp" $ "ICMP"
case prot of
FTCP -> do
tcpOpt ! A.selected "selected"
udpOpt >> icmpOpt
FUDP -> do
tcpOpt
udpOpt ! A.selected "selected"
icmpOpt
FICMP -> do
tcpOpt >> udpOpt
icmpOpt ! A.selected "selected"
maybe mempty printMesTd resMesMay
renderFormEntry _ (FESPort en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "sportEnable"
$ "Source port"
H.br
checkBox "sportEnable" en
H.td $ do
H.label ! A.for "sportInv"
$ "!"
checkBox "sportInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "sport" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEDPort en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "dportEnable"
$ "Destination port"
H.br
checkBox "dportEnable" en
H.td $ do
H.label ! A.for "dportInv"
$ "!"
checkBox "dportInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "dport" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEInput en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "inputEnable"
$ "Input interface"
H.br
checkBox "inputEnable" en
H.td $ do
H.label ! A.for "inputInv"
$ "!"
checkBox "inputInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "input" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEOutput en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "outputEnable"
$ "Output interface"
H.br
checkBox "outputEnable" en
H.td $ do
H.label ! A.for "outputInv"
$ "!"
checkBox "outputInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "output" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEState en stateSet, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "stateEnable"
$ "State"
H.br
checkBox "stateEnable" en
H.td ""
H.td $ do
checkBox "stateNew" $ CStNew `member` stateSet
H.label ! A.for "stateNew"
$ "New"
H.br
checkBox "stateEstablished" $ CStEstablished `member` stateSet
H.label ! A.for "stateEstablished"
$ "Established"
H.br
checkBox "stateRelated" $ CStRelated `member` stateSet
H.label ! A.for "stateRelated"
$ "Related"
H.br
checkBox "stateInvalid" $ CStInvalid `member` stateSet
H.label ! A.for "stateInvalid"
$ "Invalid"
H.br
checkBox "stateUntracked" $ CStUntracked `member` stateSet
H.label ! A.for "stateUntracked"
$ "Untracked"
H.br
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FEFiltTar filtTar rejectType userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
H.tr $ do
H.td ! A.class_ "target" $ do
let acceptRadio = H.input ! A.id "accept" ! A.type_ "radio" ! A.name "target" ! A.value "accept"
case filtTar of
FAccept -> acceptRadio ! A.checked "checked"
_ -> acceptRadio
H.label ! A.for "accept"
$ "Acccept"
H.td ! A.class_ "targetParam" $ ""
H.tr $ do
H.td ! A.class_ "target" $ do
let dropRadio = H.input ! A.type_ "radio" ! A.id "drop" ! A.name "target" ! A.value "drop"
case filtTar of
FDrop -> dropRadio ! A.checked "checked"
_ -> dropRadio
H.label ! A.for "drop"
$ "Drop"
H.td ! A.class_ "targetParam" $ ""
H.tr $ do
H.td ! A.class_ "target" $ do
let rejectRadio = H.input ! A.type_ "radio" ! A.id "reject" ! A.name "target" ! A.value "reject"
case filtTar of
FReject -> rejectRadio ! A.checked "checked"
_ -> rejectRadio
H.label ! A.for "reject"
$ "Reject"
H.td ! A.class_ "targetParam" $
H.select ! A.id "rejectType" ! A.name "rejectType" $
let
netUnrOpt = H.option ! A.value "icmp-net-unreachable" $ "Icmp-net-unreachable"
netUnrOptSel = if rejectType == RTNetUnreachable then netUnrOpt ! A.selected "selected"
else netUnrOpt
hostUnrOpt = H.option ! A.value "icmp-host-unreachable" $ "Icmp-host-unreachable"
hostUnrOptSel = if rejectType == RTHostUnreachable then hostUnrOpt ! A.selected "selected"
else hostUnrOpt
portUnrOpt = H.option ! A.value "icmp-port-unreachable" $ "Icmp-port-unreachable"
portUnrOptSel = if rejectType == RTPortUnreachable then portUnrOpt ! A.selected "selected"
else portUnrOpt
protoUnrOpt = H.option ! A.value "icmp-proto-unreachable" $ "Icmp-proto-unreachable"
protoUnrOptSel = if rejectType == RTProtoUnreachable then protoUnrOpt ! A.selected "selected"
else protoUnrOpt
netProhOpt = H.option ! A.value "icmp-net-prohibited" $ "Icmp-net-prohibited"
netProhOptSel = if rejectType == RTNetProhibited then netProhOpt ! A.selected "selected"
else netProhOpt
hostProhOpt = H.option ! A.value "icmp-host-prohibited" $ "Icmp-host-prohibited"
hostProhOptSel = if rejectType == RTHostProhibited then hostProhOpt ! A.selected "selected"
else hostProhOpt
admProhOpt = H.option ! A.value "icmp-admin-prohibited" $ "Icmp-admin-prohibited"
admProhOptSel = if rejectType == RTAdminProhibited then admProhOpt ! A.selected "selected"
else admProhOpt
tcpResetOpt = H.option ! A.value "tcp-reset" $ "Tcp-reset"
tcpResetOptSel = if rejectType == RTTcpReset then tcpResetOpt ! A.selected "selected"
else tcpResetOpt
in
netUnrOptSel
>> hostUnrOptSel
>> portUnrOptSel
>> protoUnrOptSel
>> netProhOptSel
>> hostProhOptSel
>> admProhOptSel
>> tcpResetOptSel
if not $ null userChainNames
then
let checked = case filtTar of
FFUserChain -> True
_ -> False
in renderUserChain checked userChainNames userChain
else mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatPrerOutTar natPrerTar dnataddr dnatrand dnatpersist redirport redirrand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natPrerTar of
FDNat -> True
_ -> False
renderDNat checked dnataddr dnatrand dnatpersist
let checked' = case natPrerTar of
FRedirect -> True
_ -> False
renderRedirect checked' redirport redirrand
if not $ null userChainNames
then
let checked'' = case natPrerTar of
FNPrerUserChain -> True
_ -> False
in renderUserChain checked'' userChainNames userChain
else mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatPostrTar natPostrTar snataddr snatrand snatpersist masqport masqrand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natPostrTar of
FMasq -> True
_ -> False
renderMasq checked masqport masqrand
let checked' = case natPostrTar of
FSNat -> True
_ -> False
renderSNat checked' snataddr snatrand snatpersist
if not $ null userChainNames
then
let checked'' = case natPostrTar of
FNPostrUserChain -> True
_ -> False
in renderUserChain checked'' userChainNames userChain
else
mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatUserTar natUserTar dnatAddr dnatRand dnatPersist redirPort redirRand snatAddr snatRand snatPersist masqPort masqRand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natUserTar of
FUDNat -> True
_ -> False
renderDNat checked dnatAddr dnatRand dnatPersist
let checked' = case natUserTar of
FURedirect -> True
_ -> False
renderRedirect checked' redirPort redirRand
let checked'' = case natUserTar of
FUSNat -> True
_ -> False
renderSNat checked'' snatAddr snatRand snatPersist
let checked''' = case natUserTar of
FUMasq -> True
_ -> False
renderMasq checked''' masqPort masqRand
if not $ null userChainNames
then
let checked'''' = case natUserTar of
FNUserUserChain -> True
_ -> False
in renderUserChain checked'''' userChainNames userChain
else
mempty
maybe mempty printMesTd resMesMay
renderFormEntry _ a = H.tr $ fromString $ "Unknown form entry: " ++ show a
renderDNat :: Bool -> String -> Bool -> Bool -> Markup
renderDNat checked dnatAddr dnatRand dnatPersist =
H.tr $ do
H.td ! A.class_ "target" $ do
let dnatRadio = H.input ! A.type_ "radio" ! A.id "dnat" ! A.name "target" ! A.value "dnat"
if checked then dnatRadio ! A.checked "checked"
else dnatRadio
H.label ! A.for "dnat"
$ "Destination Nat"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "dnataddress"
$ "dnat address:"
H.input ! A.type_ "text" ! A.id "dnataddress" ! A.name "dnataddress" ! A.value (fromString dnatAddr) >> H.br
H.label ! A.for "dnatrandom"
$ "random:"
checkBox "dnatrandom" dnatRand >> H.br
H.label ! A.for "dnatpersistent"
$ "persistent:"
checkBox "dnatpersistent" dnatPersist >> H.br
renderRedirect :: Bool -> String -> Bool -> Markup
renderRedirect checked redirPort redirRand =
H.tr $ do
H.td ! A.class_ "target" $ do
let redirRadio = H.input ! A.type_ "radio" ! A.id "redirect" ! A.name "target" ! A.value "redirect"
if checked then redirRadio ! A.checked "checked"
else redirRadio
H.label ! A.for "redirect"
$ "Redirect"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "redirport"
$ "port:"
H.input ! A.type_ "text" ! A.id "redirport" ! A.name "redirport" ! A.value (fromString redirPort) >> H.br
H.label ! A.for "redirrandom"
$ "random:"
checkBox "redirrandom" redirRand
renderSNat :: Bool -> String -> Bool -> Bool -> Markup
renderSNat checked snatAddr snatRand snatPersist =
H.tr $ do
H.td ! A.class_ "target" $ do
let snatRadio = H.input ! A.type_ "radio" ! A.id "snat" ! A.name "target" ! A.value "snat"
if checked then snatRadio ! A.checked "checked"
else snatRadio
H.label ! A.for "snat"
$ "Source Nat"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "snataddress"
$ "snat address:"
H.input ! A.type_ "text" ! A.id "snataddress" ! A.name "snataddress" ! A.value (fromString snatAddr) >> H.br
H.label ! A.for "snatrandom"
$ "random:"
checkBox "snatrandom" snatRand >> H.br
H.label ! A.for "snatpersistent"
$ "persistent:"
checkBox "snatpersistent" snatPersist >> H.br
renderMasq :: Bool -> String -> Bool -> Markup
renderMasq checked masqPort masqRand =
H.tr $ do
H.td ! A.class_ "target" $ do
let masqRadio = H.input ! A.type_ "radio" ! A.id "masquerade" ! A.name "target" ! A.value "masquerade"
if checked then masqRadio ! A.checked "checked"
else masqRadio
H.label ! A.for "masquerade"
$ "Masquerade"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "masqport"
$ "port:"
H.input ! A.type_ "text" ! A.id "masqport" ! A.name "masqport" ! A.value (fromString masqPort) >> H.br
H.label ! A.for "masqrandom"
$ "random:"
checkBox "masqrandom" masqRand
renderUserChain :: Bool -> [String] -> String -> Markup
renderUserChain checked allChains chain =
H.tr $ do
H.td ! A.class_ "target" $ do
let userChainRadio = H.input ! A.type_ "radio" ! A.id "userChain" ! A.name "target" ! A.value "userChain"
if checked then userChainRadio ! A.checked "checked"
else userChainRadio
H.label ! A.for "userChain"
$ "User chain"
H.td ! A.class_ "targetParam" $
H.select ! A.id "userChain" ! A.name "userChain" $
mapM_ (renderOption chain) allChains
where
renderOption :: String -> String -> Markup
renderOption selName optName = do
let opt = H.option ! A.value (fromString optName) $ fromString optName
let optSel = if optName == selName then opt ! A.selected "selected"
else opt
optSel
| null | https://raw.githubusercontent.com/etarasov/iptadmin/ceaca3424a0b2891da4d5d91eaf516a3566f2885/src/IptAdmin/EditForm/Render.hs | haskell | # LANGUAGE OverloadedStrings # |
module IptAdmin.EditForm.Render where
import Data.Monoid
import Data.Set (member)
import Data.String
import IptAdmin.EditForm.Class
import IptAdmin.EditForm.Types
import Iptables.Types
import Text.Blaze
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
checkBox :: String -> Bool -> Markup
checkBox name on = do
let chBox = H.input ! A.type_ "checkbox"
! A.id (fromString name)
! A.name (fromString name)
! A.value "on"
if on then chBox ! A.checked "checked"
else chBox
printMesTd :: ResMessage -> Markup
printMesTd rm = H.td $ fromString $ case rm of
RMError mes -> mes
RMSucc mes -> "ok " ++ mes
RMIgnore -> "ignored"
maybeListToListMaybe :: Maybe [a] -> [Maybe a]
maybeListToListMaybe (Just list) = map Just list
maybeListToListMaybe Nothing = repeat Nothing
editFormHtml :: EditForm a => (String,String,Int,[String]) -> a -> Maybe [ResMessage] -> Markup
editFormHtml (tableName, chainName, rulePos, userChainNames) form errorListMay =
let entryList = toEntryList form
mesListMay = maybeListToListMaybe errorListMay
in
H.div ! A.class_ "editForm" $
H.form ! A.id "editform" ! A.method "post" $ do
H.input ! A.type_ "hidden" ! A.name "table" ! A.value (fromString tableName)
H.input ! A.type_ "hidden" ! A.name "chain" ! A.value (fromString chainName)
H.input ! A.type_ "hidden" ! A.name "rulePos" ! A.value (fromString $ show rulePos)
H.table ! A.class_ "editForm" $ do
H.tr $ do
H.th "Option"
H.th "Not"
H.th "Parameter"
maybe mempty (\_-> H.th "Message") errorListMay
mapM_ (renderFormEntry userChainNames) $ zip entryList mesListMay
renderFormEntry :: [String] -> (FormEntry, Maybe ResMessage) -> Markup
renderFormEntry _ (FESrc en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "sourceEnable"
$ "Source"
H.br
checkBox "sourceEnable" en
H.td $ do
H.label ! A.for "sourceInv"
$ "!"
checkBox "sourceInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "source" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEDst en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "destinationEnable"
$ "Destination"
H.br
checkBox "destinationEnable" en
H.td $ do
H.label ! A.for "destinationInv"
$ "!"
checkBox "destinationInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "destination" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEProt en inv prot, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "protocolEnable"
$ "Protocol"
H.br
checkBox "protocolEnable" en
H.td $ do
H.label ! A.for "protocolInv"
$ "!"
checkBox "protocolInv" inv
H.td $
H.select ! A.id "protocol" ! A.name "protocol" $ do
let tcpOpt = H.option ! A.value "tcp" $ "TCP"
let udpOpt = H.option ! A.value "udp" $ "UDP"
let icmpOpt = H.option ! A.value "icmp" $ "ICMP"
case prot of
FTCP -> do
tcpOpt ! A.selected "selected"
udpOpt >> icmpOpt
FUDP -> do
tcpOpt
udpOpt ! A.selected "selected"
icmpOpt
FICMP -> do
tcpOpt >> udpOpt
icmpOpt ! A.selected "selected"
maybe mempty printMesTd resMesMay
renderFormEntry _ (FESPort en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "sportEnable"
$ "Source port"
H.br
checkBox "sportEnable" en
H.td $ do
H.label ! A.for "sportInv"
$ "!"
checkBox "sportInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "sport" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEDPort en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "dportEnable"
$ "Destination port"
H.br
checkBox "dportEnable" en
H.td $ do
H.label ! A.for "dportInv"
$ "!"
checkBox "dportInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "dport" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEInput en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "inputEnable"
$ "Input interface"
H.br
checkBox "inputEnable" en
H.td $ do
H.label ! A.for "inputInv"
$ "!"
checkBox "inputInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "input" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEOutput en inv str, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "outputEnable"
$ "Output interface"
H.br
checkBox "outputEnable" en
H.td $ do
H.label ! A.for "outputInv"
$ "!"
checkBox "outputInv" inv
H.td $
H.input ! A.type_ "text" ! A.name "output" ! A.value (fromString str)
maybe mempty printMesTd resMesMay
renderFormEntry _ (FEState en stateSet, resMesMay) =
H.tr $ do
H.td $ do
H.label ! A.for "stateEnable"
$ "State"
H.br
checkBox "stateEnable" en
H.td ""
H.td $ do
checkBox "stateNew" $ CStNew `member` stateSet
H.label ! A.for "stateNew"
$ "New"
H.br
checkBox "stateEstablished" $ CStEstablished `member` stateSet
H.label ! A.for "stateEstablished"
$ "Established"
H.br
checkBox "stateRelated" $ CStRelated `member` stateSet
H.label ! A.for "stateRelated"
$ "Related"
H.br
checkBox "stateInvalid" $ CStInvalid `member` stateSet
H.label ! A.for "stateInvalid"
$ "Invalid"
H.br
checkBox "stateUntracked" $ CStUntracked `member` stateSet
H.label ! A.for "stateUntracked"
$ "Untracked"
H.br
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FEFiltTar filtTar rejectType userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
H.tr $ do
H.td ! A.class_ "target" $ do
let acceptRadio = H.input ! A.id "accept" ! A.type_ "radio" ! A.name "target" ! A.value "accept"
case filtTar of
FAccept -> acceptRadio ! A.checked "checked"
_ -> acceptRadio
H.label ! A.for "accept"
$ "Acccept"
H.td ! A.class_ "targetParam" $ ""
H.tr $ do
H.td ! A.class_ "target" $ do
let dropRadio = H.input ! A.type_ "radio" ! A.id "drop" ! A.name "target" ! A.value "drop"
case filtTar of
FDrop -> dropRadio ! A.checked "checked"
_ -> dropRadio
H.label ! A.for "drop"
$ "Drop"
H.td ! A.class_ "targetParam" $ ""
H.tr $ do
H.td ! A.class_ "target" $ do
let rejectRadio = H.input ! A.type_ "radio" ! A.id "reject" ! A.name "target" ! A.value "reject"
case filtTar of
FReject -> rejectRadio ! A.checked "checked"
_ -> rejectRadio
H.label ! A.for "reject"
$ "Reject"
H.td ! A.class_ "targetParam" $
H.select ! A.id "rejectType" ! A.name "rejectType" $
let
netUnrOpt = H.option ! A.value "icmp-net-unreachable" $ "Icmp-net-unreachable"
netUnrOptSel = if rejectType == RTNetUnreachable then netUnrOpt ! A.selected "selected"
else netUnrOpt
hostUnrOpt = H.option ! A.value "icmp-host-unreachable" $ "Icmp-host-unreachable"
hostUnrOptSel = if rejectType == RTHostUnreachable then hostUnrOpt ! A.selected "selected"
else hostUnrOpt
portUnrOpt = H.option ! A.value "icmp-port-unreachable" $ "Icmp-port-unreachable"
portUnrOptSel = if rejectType == RTPortUnreachable then portUnrOpt ! A.selected "selected"
else portUnrOpt
protoUnrOpt = H.option ! A.value "icmp-proto-unreachable" $ "Icmp-proto-unreachable"
protoUnrOptSel = if rejectType == RTProtoUnreachable then protoUnrOpt ! A.selected "selected"
else protoUnrOpt
netProhOpt = H.option ! A.value "icmp-net-prohibited" $ "Icmp-net-prohibited"
netProhOptSel = if rejectType == RTNetProhibited then netProhOpt ! A.selected "selected"
else netProhOpt
hostProhOpt = H.option ! A.value "icmp-host-prohibited" $ "Icmp-host-prohibited"
hostProhOptSel = if rejectType == RTHostProhibited then hostProhOpt ! A.selected "selected"
else hostProhOpt
admProhOpt = H.option ! A.value "icmp-admin-prohibited" $ "Icmp-admin-prohibited"
admProhOptSel = if rejectType == RTAdminProhibited then admProhOpt ! A.selected "selected"
else admProhOpt
tcpResetOpt = H.option ! A.value "tcp-reset" $ "Tcp-reset"
tcpResetOptSel = if rejectType == RTTcpReset then tcpResetOpt ! A.selected "selected"
else tcpResetOpt
in
netUnrOptSel
>> hostUnrOptSel
>> portUnrOptSel
>> protoUnrOptSel
>> netProhOptSel
>> hostProhOptSel
>> admProhOptSel
>> tcpResetOptSel
if not $ null userChainNames
then
let checked = case filtTar of
FFUserChain -> True
_ -> False
in renderUserChain checked userChainNames userChain
else mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatPrerOutTar natPrerTar dnataddr dnatrand dnatpersist redirport redirrand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natPrerTar of
FDNat -> True
_ -> False
renderDNat checked dnataddr dnatrand dnatpersist
let checked' = case natPrerTar of
FRedirect -> True
_ -> False
renderRedirect checked' redirport redirrand
if not $ null userChainNames
then
let checked'' = case natPrerTar of
FNPrerUserChain -> True
_ -> False
in renderUserChain checked'' userChainNames userChain
else mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatPostrTar natPostrTar snataddr snatrand snatpersist masqport masqrand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natPostrTar of
FMasq -> True
_ -> False
renderMasq checked masqport masqrand
let checked' = case natPostrTar of
FSNat -> True
_ -> False
renderSNat checked' snataddr snatrand snatpersist
if not $ null userChainNames
then
let checked'' = case natPostrTar of
FNPostrUserChain -> True
_ -> False
in renderUserChain checked'' userChainNames userChain
else
mempty
maybe mempty printMesTd resMesMay
renderFormEntry userChainNames (FENatUserTar natUserTar dnatAddr dnatRand dnatPersist redirPort redirRand snatAddr snatRand snatPersist masqPort masqRand userChain, resMesMay) =
H.tr $ do
H.td ! A.colspan "3" ! A.class_ "inline" $
H.table ! A.class_ "inline" $ do
H.tr $ do
H.th ! A.class_ "target" $ "Target"
H.th ! A.class_ "targetParam" $ "Parameters"
let checked = case natUserTar of
FUDNat -> True
_ -> False
renderDNat checked dnatAddr dnatRand dnatPersist
let checked' = case natUserTar of
FURedirect -> True
_ -> False
renderRedirect checked' redirPort redirRand
let checked'' = case natUserTar of
FUSNat -> True
_ -> False
renderSNat checked'' snatAddr snatRand snatPersist
let checked''' = case natUserTar of
FUMasq -> True
_ -> False
renderMasq checked''' masqPort masqRand
if not $ null userChainNames
then
let checked'''' = case natUserTar of
FNUserUserChain -> True
_ -> False
in renderUserChain checked'''' userChainNames userChain
else
mempty
maybe mempty printMesTd resMesMay
renderFormEntry _ a = H.tr $ fromString $ "Unknown form entry: " ++ show a
renderDNat :: Bool -> String -> Bool -> Bool -> Markup
renderDNat checked dnatAddr dnatRand dnatPersist =
H.tr $ do
H.td ! A.class_ "target" $ do
let dnatRadio = H.input ! A.type_ "radio" ! A.id "dnat" ! A.name "target" ! A.value "dnat"
if checked then dnatRadio ! A.checked "checked"
else dnatRadio
H.label ! A.for "dnat"
$ "Destination Nat"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "dnataddress"
$ "dnat address:"
H.input ! A.type_ "text" ! A.id "dnataddress" ! A.name "dnataddress" ! A.value (fromString dnatAddr) >> H.br
H.label ! A.for "dnatrandom"
$ "random:"
checkBox "dnatrandom" dnatRand >> H.br
H.label ! A.for "dnatpersistent"
$ "persistent:"
checkBox "dnatpersistent" dnatPersist >> H.br
renderRedirect :: Bool -> String -> Bool -> Markup
renderRedirect checked redirPort redirRand =
H.tr $ do
H.td ! A.class_ "target" $ do
let redirRadio = H.input ! A.type_ "radio" ! A.id "redirect" ! A.name "target" ! A.value "redirect"
if checked then redirRadio ! A.checked "checked"
else redirRadio
H.label ! A.for "redirect"
$ "Redirect"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "redirport"
$ "port:"
H.input ! A.type_ "text" ! A.id "redirport" ! A.name "redirport" ! A.value (fromString redirPort) >> H.br
H.label ! A.for "redirrandom"
$ "random:"
checkBox "redirrandom" redirRand
renderSNat :: Bool -> String -> Bool -> Bool -> Markup
renderSNat checked snatAddr snatRand snatPersist =
H.tr $ do
H.td ! A.class_ "target" $ do
let snatRadio = H.input ! A.type_ "radio" ! A.id "snat" ! A.name "target" ! A.value "snat"
if checked then snatRadio ! A.checked "checked"
else snatRadio
H.label ! A.for "snat"
$ "Source Nat"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "snataddress"
$ "snat address:"
H.input ! A.type_ "text" ! A.id "snataddress" ! A.name "snataddress" ! A.value (fromString snatAddr) >> H.br
H.label ! A.for "snatrandom"
$ "random:"
checkBox "snatrandom" snatRand >> H.br
H.label ! A.for "snatpersistent"
$ "persistent:"
checkBox "snatpersistent" snatPersist >> H.br
renderMasq :: Bool -> String -> Bool -> Markup
renderMasq checked masqPort masqRand =
H.tr $ do
H.td ! A.class_ "target" $ do
let masqRadio = H.input ! A.type_ "radio" ! A.id "masquerade" ! A.name "target" ! A.value "masquerade"
if checked then masqRadio ! A.checked "checked"
else masqRadio
H.label ! A.for "masquerade"
$ "Masquerade"
H.td ! A.class_ "targetParam" $ do
H.label ! A.for "masqport"
$ "port:"
H.input ! A.type_ "text" ! A.id "masqport" ! A.name "masqport" ! A.value (fromString masqPort) >> H.br
H.label ! A.for "masqrandom"
$ "random:"
checkBox "masqrandom" masqRand
renderUserChain :: Bool -> [String] -> String -> Markup
renderUserChain checked allChains chain =
H.tr $ do
H.td ! A.class_ "target" $ do
let userChainRadio = H.input ! A.type_ "radio" ! A.id "userChain" ! A.name "target" ! A.value "userChain"
if checked then userChainRadio ! A.checked "checked"
else userChainRadio
H.label ! A.for "userChain"
$ "User chain"
H.td ! A.class_ "targetParam" $
H.select ! A.id "userChain" ! A.name "userChain" $
mapM_ (renderOption chain) allChains
where
renderOption :: String -> String -> Markup
renderOption selName optName = do
let opt = H.option ! A.value (fromString optName) $ fromString optName
let optSel = if optName == selName then opt ! A.selected "selected"
else opt
optSel
|
430ce955c23e01d8835f712867624b1f3c36026b62846be4fc28a428c476a311 | thheller/shadow-cljs | explore_support.clj | (ns shadow.remote.runtime.explore-support
(:require
[shadow.debug :refer (?> ?-> ?->>)]
[shadow.remote.runtime.api :as p]
[shadow.remote.runtime.shared :as shared]
[shadow.remote.runtime.obj-support :as obj-support]
))
(defn namespaces [{:keys [runtime] :as svc} msg]
(shared/reply runtime msg
{:op :explore/namespaces-result
:namespaces (->> (all-ns)
(map #(.getName ^clojure.lang.Namespace %))
(sort-by name)
(vec))}))
(defn namespace-vars [{:keys [runtime] :as svc} {:keys [ns] :as msg}]
(shared/reply runtime msg
{:op :explore/namespace-vars-result
:vars (->> (ns-publics ns)
(keys)
(sort-by name)
(vec))}))
(defn describe-ns [{:keys [runtime] :as svc} {:keys [ns] :as msg}]
(shared/reply runtime msg
{:op :explore/describe-ns-result
:description (meta (find-ns ns))}))
(defn describe-var [{:keys [runtime] :as svc} {:keys [var] :as msg}]
(let [var (find-var var)
m (meta var)]
(shared/reply runtime msg
{:op :explore/describe-var-result
:description (dissoc m :ns :name)})))
(defn start [runtime obj-support]
(let [svc
{:runtime runtime
:obj-support obj-support}]
(p/add-extension runtime
::ext
{:ops
{:explore/namespaces #(namespaces svc %)
:explore/namespace-vars #(namespace-vars svc %)
:explore/describe-var #(describe-var svc %)
:explore/describe-ns #(describe-ns svc %)}})
svc))
(defn stop [{:keys [runtime] :as svc}]
(p/del-extension runtime ::ext))
| null | https://raw.githubusercontent.com/thheller/shadow-cljs/1708acb21bcdae244b50293d17633ce35a78a467/src/main/shadow/remote/runtime/explore_support.clj | clojure | (ns shadow.remote.runtime.explore-support
(:require
[shadow.debug :refer (?> ?-> ?->>)]
[shadow.remote.runtime.api :as p]
[shadow.remote.runtime.shared :as shared]
[shadow.remote.runtime.obj-support :as obj-support]
))
(defn namespaces [{:keys [runtime] :as svc} msg]
(shared/reply runtime msg
{:op :explore/namespaces-result
:namespaces (->> (all-ns)
(map #(.getName ^clojure.lang.Namespace %))
(sort-by name)
(vec))}))
(defn namespace-vars [{:keys [runtime] :as svc} {:keys [ns] :as msg}]
(shared/reply runtime msg
{:op :explore/namespace-vars-result
:vars (->> (ns-publics ns)
(keys)
(sort-by name)
(vec))}))
(defn describe-ns [{:keys [runtime] :as svc} {:keys [ns] :as msg}]
(shared/reply runtime msg
{:op :explore/describe-ns-result
:description (meta (find-ns ns))}))
(defn describe-var [{:keys [runtime] :as svc} {:keys [var] :as msg}]
(let [var (find-var var)
m (meta var)]
(shared/reply runtime msg
{:op :explore/describe-var-result
:description (dissoc m :ns :name)})))
(defn start [runtime obj-support]
(let [svc
{:runtime runtime
:obj-support obj-support}]
(p/add-extension runtime
::ext
{:ops
{:explore/namespaces #(namespaces svc %)
:explore/namespace-vars #(namespace-vars svc %)
:explore/describe-var #(describe-var svc %)
:explore/describe-ns #(describe-ns svc %)}})
svc))
(defn stop [{:keys [runtime] :as svc}]
(p/del-extension runtime ::ext))
| |
4c750184e76d31b5e0f9dbda675d896c0f2d8a1bc2391d5da8c3c2d5d2960c48 | PJK/haskell-pattern-matching | Types.hs | module OptParse.Types where
-- | Kept throughout the program
data Settings = Settings
{ setsCommand :: Command
, setsDebug :: Bool
} deriving (Show, Eq)
-- | Command-line arguments
data Arguments = Arguments
{ argsDebug :: Bool
} deriving (Show, Eq)
-- | Configuration, from config file
data Configuration = Configuration
deriving (Show, Eq)
data Command
= Analyze FilePath
| AnalyzeEvaluatedness FilePath
| DumpResults FilePath
deriving (Show, Eq)
| null | https://raw.githubusercontent.com/PJK/haskell-pattern-matching/7ef4a45731beba92ee01614ae563df65be36e8ba/src/OptParse/Types.hs | haskell | | Kept throughout the program
| Command-line arguments
| Configuration, from config file | module OptParse.Types where
data Settings = Settings
{ setsCommand :: Command
, setsDebug :: Bool
} deriving (Show, Eq)
data Arguments = Arguments
{ argsDebug :: Bool
} deriving (Show, Eq)
data Configuration = Configuration
deriving (Show, Eq)
data Command
= Analyze FilePath
| AnalyzeEvaluatedness FilePath
| DumpResults FilePath
deriving (Show, Eq)
|
c022569b9338bc29d88a3c5a71a750d4f82cddd1cb31ff82293e0e6279446bf4 | evilmartians/foundry | fy_topnum.ml | let big_int_of_string = Big_int.big_int_of_string
let string_to_big_int = Big_int.big_int_of_string
let print_big_int ppf b =
Format.fprintf ppf "@[%sI@]@." (Big_int.string_of_big_int b)
let print_num ppf b =
Format.fprintf ppf "@[Num %s@]@." (Num.string_of_num b)
module I = struct
open Big_int
let (+) = add_big_int
let (-) = sub_big_int
let ( * ) = mult_big_int
let (/) = div_big_int
end
module R = struct
open Num
let (+) = add_num
let (-) = sub_num
let ( * ) = mult_num
let (/) = div_num
let int_of_int = Num.num_of_int
external int_to_int : int -> int = "%identity"
let big_int_of_string = Num.num_of_string
let string_to_big_int = Big_int.big_int_of_string
end
let init () =
Num.init ();
Big_int.init ()
| null | https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/vendor/ocaml-num/fy_topnum.ml | ocaml | let big_int_of_string = Big_int.big_int_of_string
let string_to_big_int = Big_int.big_int_of_string
let print_big_int ppf b =
Format.fprintf ppf "@[%sI@]@." (Big_int.string_of_big_int b)
let print_num ppf b =
Format.fprintf ppf "@[Num %s@]@." (Num.string_of_num b)
module I = struct
open Big_int
let (+) = add_big_int
let (-) = sub_big_int
let ( * ) = mult_big_int
let (/) = div_big_int
end
module R = struct
open Num
let (+) = add_num
let (-) = sub_num
let ( * ) = mult_num
let (/) = div_num
let int_of_int = Num.num_of_int
external int_to_int : int -> int = "%identity"
let big_int_of_string = Num.num_of_string
let string_to_big_int = Big_int.big_int_of_string
end
let init () =
Num.init ();
Big_int.init ()
| |
0fd7c4157ad96c6181fe06b65871a67697c809444d3fff49ae6c833f5b8abe1a | AdRoll/mero | mero_wrk_tcp_txt.erl | Copyright ( c ) 2014 , AdRoll
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions are met:
%%
%% * Redistributions of source code must retain the above copyright notice, this
%% list of conditions and the following disclaimer.
%%
%% * Redistributions in binary form must reproduce the above copyright notice,
%% this list of conditions and the following disclaimer in the documentation
%% and/or other materials provided with the distribution.
%%
%% * Neither the name of the {organization} nor the names of its
%% contributors may be used to endorse or promote products derived from
%% this software without specific prior written permission.
%%
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
%% OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%
-module(mero_wrk_tcp_txt).
%% The usage of throw here is intentional and it's correctly used for non-local returns.
-elvis([{elvis_style, no_throw, disable}]).
-include_lib("mero/include/mero.hrl").
-behaviour(mero_pool).
%%% Start/stop functions
-export([connect/3, controlling_process/2, transaction/3, close/2]).
-record(client, {socket, event_callback}).
-define(SOCKET_OPTIONS,
[binary, {packet, raw}, {active, false}, {reuseaddr, true}, {nodelay, true}]).
%%%=============================================================================
%%% External functions
%%%=============================================================================
%% API functions
connect(Host, Port, CallbackInfo) ->
?LOG_EVENT(CallbackInfo, [socket, connecting]),
case gen_tcp:connect(Host, Port, ?SOCKET_OPTIONS) of
{ok, Socket} ->
?LOG_EVENT(CallbackInfo, [socket, connect, ok]),
{ok, #client{socket = Socket, event_callback = CallbackInfo}};
{error, Reason} ->
?LOG_EVENT(CallbackInfo, [socket, connect, error, {reason, Reason}]),
{error, Reason}
end.
controlling_process(Client, Pid) ->
case gen_tcp:controlling_process(Client#client.socket, Pid) of
ok ->
ok;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback,
[socket, controlling_process, error, {reason, Reason}]),
{error, Reason}
end.
transaction(Client, increment_counter, [Key, Value, Initial, ExpTime, TimeLimit]) ->
First attempt
case send_receive(Client, {?MEMCACHE_INCREMENT, {Key, Value}}, TimeLimit) of
{error, not_found} ->
%% Key does not exist, create the key
case send_receive(Client, {?MEMCACHE_ADD, {Key, Initial, ExpTime}}, TimeLimit) of
{ok, stored} ->
{Client, {ok, to_integer(Initial)}};
{error, not_stored} ->
%% Key was already created by other thread,
Second attempt ( just in case of someone added right at that time )
case send_receive(Client, {?MEMCACHE_INCREMENT, {Key, Value}}, TimeLimit) of
{error, Reason} ->
{error, Reason};
{ok, NValue} ->
{Client, {ok, to_integer(NValue)}}
end;
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason};
{ok, NValue} ->
{Client, {ok, to_integer(NValue)}}
end;
transaction(Client, delete, [Key, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_DELETE, {Key}}, TimeLimit) of
{ok, deleted} ->
{Client, ok};
{error, not_found} ->
{Client, {error, not_found}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, mdelete, [Keys, TimeLimit]) ->
Resp =
mero_util:foreach(fun(Key) ->
case send_receive(Client, {?MEMCACHE_DELETE, {Key}}, TimeLimit) of
{ok, deleted} ->
continue;
{error, not_found} ->
continue;
{error, Reason} ->
{break, {error, Reason}}
end
end,
Keys),
{Client, Resp};
transaction(Client, add, [Key, Value, ExpTime, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_ADD, {Key, Value, ExpTime}}, TimeLimit) of
{ok, stored} ->
{Client, ok};
{error, not_stored} ->
{Client, {error, not_stored}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, get, [Key, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_GET, {[Key]}}, TimeLimit) of
{ok, [Found]} ->
{Client, Found};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, set, [Key, Value, ExpTime, TimeLimit, CAS]) ->
case send_receive(Client, {?MEMCACHE_SET, {Key, Value, ExpTime, CAS}}, TimeLimit) of
{ok, stored} ->
{Client, ok};
{error, already_exists} ->
{Client, {error, already_exists}};
{error, not_found} ->
{Client, {error, not_found}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, flush_all, [TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_FLUSH_ALL, {}}, TimeLimit) of
{ok, ok} ->
{Client, ok};
{error, Reason} ->
{error, Reason}
end;
mset / madd are currently only supported by the binary protocol implementation .
transaction(Client, async_mset, _) ->
{Client, {error, unsupported_operation}};
transaction(Client, async_madd, _) ->
{Client, {error, unsupported_operation}};
transaction(Client, async_mget, [Keys]) ->
case async_mget(Client, Keys) of
{error, Reason} ->
{error, Reason};
{ok, ok} ->
{Client, ok}
end;
transaction(Client, async_delete, [Keys]) ->
case async_delete(Client, Keys) of
{error, Reason} ->
{error, Reason};
{ok, ok} ->
{Client, ok}
end;
transaction(_Client, async_increment, [_Keys]) ->
{error, not_supportable}; %% txt incr doesn't support initial etc
transaction(Client, async_blank_response, [_Keys, _Timeout]) ->
{Client, [ok]};
transaction(Client, async_mget_response, [Keys, Timeout]) ->
case async_mget_response(Client, Keys, Timeout) of
{error, Reason} ->
{error, Reason};
{ok, {ok, FoundItems}} ->
FoundKeys = [Key || #mero_item{key = Key} <- FoundItems],
NotFoundKeys = lists:subtract(Keys, FoundKeys),
Result =
[#mero_item{key = Key, value = undefined} || Key <- NotFoundKeys] ++ FoundItems,
{Client, Result}
end.
close(Client, Reason) ->
?LOG_EVENT(Client#client.event_callback, [closing_socket, {reason, Reason}]),
gen_tcp:close(Client#client.socket).
%%%=============================================================================
Internal functions
%%%=============================================================================
send_receive(Client, {_Op, _Args} = Cmd, TimeLimit) ->
try
Data = pack(Cmd),
ok = send(Client, Data),
receive_response(Client, Cmd, TimeLimit, <<>>, [])
catch
{failed, Reason} ->
{error, Reason}
end.
pack({?MEMCACHE_DELETE, {Key}}) when is_binary(Key) ->
[<<"delete ">>, Key, <<"\r\n">>];
pack({?MEMCACHE_DELETEQ, {Key}}) when is_binary(Key) ->
[<<"delete ">>, Key, <<" noreply ">>, <<"\r\n">>];
pack({?MEMCACHE_ADD, {Key, Initial, ExpTime}}) ->
NBytes = integer_to_binary(size(Initial)),
[<<"add ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_SET, {Key, Initial, ExpTime, undefined}}) ->
NBytes = integer_to_binary(size(Initial)),
[<<"set ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_SET, {Key, Initial, ExpTime, CAS}}) when is_integer(CAS) ->
note : CAS should only be supplied if setting a value after looking it up . if the
%% value has changed since we looked it up, the result of a cas command will be EXISTS
%% (otherwise STORED).
NBytes = integer_to_binary(size(Initial)),
[<<"cas ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<" ">>,
integer_to_binary(CAS),
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_INCREMENT, {Key, Value}}) ->
[<<"incr ">>, Key, <<" ">>, Value, <<"\r\n">>];
pack({?MEMCACHE_FLUSH_ALL, {}}) ->
[<<"flush_all\r\n">>];
pack({?MEMCACHE_GET, {Keys}}) when is_list(Keys) ->
Query = lists:foldr(fun(Key, Acc) -> [Key, <<" ">> | Acc] end, [], Keys),
[<<"gets ">>, Query, <<"\r\n">>].
send(Client, Data) ->
case gen_tcp:send(Client#client.socket, Data) of
ok ->
ok;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback, [socket, send, error, {reason, Reason}]),
throw({failed, Reason})
end.
receive_response(Client, Cmd, TimeLimit, AccBinary, AccResult) ->
case gen_tcp_recv(Client, 0, TimeLimit) of
{ok, Data} ->
NAcc = <<AccBinary/binary, Data/binary>>,
case parse_reply(Client, Cmd, NAcc, TimeLimit, AccResult) of
{ok, Atom, []} when (Atom == stored) or (Atom == deleted) or (Atom == ok) ->
{ok, Atom};
{ok, Binary} when is_binary(Binary) ->
{ok, Binary};
{ok, finished, Result} ->
{ok, Result};
{ok, NBuffer, NewCmd, NAccResult} ->
receive_response(Client, NewCmd, TimeLimit, NBuffer, NAccResult);
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback,
[socket, rcv, error, {reason, Reason}]),
throw({failed, Reason})
end;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback, [socket, rcv, error, {reason, Reason}]),
throw({failed, Reason})
end.
process_result({?MEMCACHE_GET, {Keys}}, finished, Result) ->
Result ++ [#mero_item{key = Key} || Key <- Keys];
process_result(_Cmd, _Status, Result) ->
Result.
This is so extremely shitty that I will do the binary prototol no matter what :(
parse_reply(Client, Cmd, Buffer, TimeLimit, AccResult) ->
case split_command(Buffer) of
{error, incomplete} ->
{ok, Buffer, Cmd, AccResult};
{Command, BinaryRest} ->
case {Cmd, parse_command(Command)} of
{_, {ok, Status}} when is_atom(Status) ->
{ok, Status, process_result(Cmd, Status, AccResult)};
{{?MEMCACHE_GET, {Keys}}, {ok, {value, Key, Bytes, CAS}}} ->
case parse_value(Client, Key, Bytes, CAS, TimeLimit, BinaryRest) of
{ok, Item, NewBinaryRest} ->
parse_reply(Client,
{?MEMCACHE_GET, {lists:delete(Key, Keys)}},
NewBinaryRest,
TimeLimit,
[Item | AccResult]);
{error, Reason} ->
{error, Reason}
end;
{_, {ok, Binary}} when is_binary(Binary) ->
{ok, Binary};
{_, {error, Reason}} ->
{error, Reason}
end
end.
parse_value(Client, Key, Bytes, CAS, TimeLimit, Buffer) ->
case Buffer of
<<Value:Bytes/binary, "\r\n", RestAfterValue/binary>> ->
{ok,
#mero_item{key = Key,
value = Value,
cas = CAS},
RestAfterValue};
_ when size(Buffer) < Bytes + size(<<"\r\n">>) ->
case gen_tcp_recv(Client, 0, TimeLimit) of
{ok, Data} ->
parse_value(Client, Key, Bytes, CAS, TimeLimit, <<Buffer/binary, Data/binary>>);
{error, Reason} ->
{error, Reason}
end;
_ ->
{error, invalid_value_size}
end.
split_command(Buffer) ->
case binary:split(Buffer, [<<"\r\n">>], []) of
[Line, RemainBuffer] ->
{binary:split(Line, [<<" ">>], [global, trim]), RemainBuffer};
[_UncompletedLine] ->
{error, incomplete}
end.
parse_command([<<"ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"CLIENT_ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"SERVER_ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"EXISTS">>]) ->
{error, already_exists};
parse_command([<<"NOT_FOUND">>]) ->
{error, not_found};
parse_command([<<"NOT_STORED">>]) ->
{error, not_stored};
parse_command([<<"END">>]) ->
{ok, finished};
parse_command([<<"STORED">>]) ->
{ok, stored};
parse_command([<<"DELETED">>]) ->
{ok, deleted};
parse_command([<<"VALUE">>, Key, _Flag, Bytes]) ->
{ok, {value, Key, list_to_integer(binary_to_list(Bytes)), undefined}};
parse_command([<<"VALUE">>, Key, _Flag, Bytes, CAS]) ->
{ok, {value, Key, list_to_integer(binary_to_list(Bytes)), binary_to_integer(CAS)}};
parse_command([<<"OK">>]) ->
{ok, ok};
parse_command([<<"VERSION">> | Version]) ->
{ok, Version};
parse_command([Value]) ->
{ok, Value};
parse_command(Line) ->
{error, {unknown, Line}}.
gen_tcp_recv(Client, Bytes, TimeLimit) ->
Timeout = mero_conf:millis_to(TimeLimit),
case Timeout of
0 ->
{error, timeout};
Timeout ->
gen_tcp:recv(Client#client.socket, Bytes, Timeout)
end.
to_integer(Value) when is_integer(Value) ->
Value;
to_integer(Value) when is_binary(Value) ->
binary_to_integer(Value).
async_mget(Client, Keys) ->
try
Data = pack({?MEMCACHE_GET, {Keys}}),
{ok, send(Client, Data)}
catch
{failed, Reason} ->
{error, Reason}
end.
async_delete(Client, Keys) ->
try
{ok, lists:foreach(fun(K) -> send(Client, pack({?MEMCACHE_DELETEQ, {K}})) end, Keys)}
catch
{failed, Reason} ->
{error, Reason}
end.
async_mget_response(Client, Keys, TimeLimit) ->
try
{ok, receive_response(Client, {?MEMCACHE_GET, {Keys}}, TimeLimit, <<>>, [])}
catch
{failed, Reason} ->
{error, Reason}
end.
| null | https://raw.githubusercontent.com/AdRoll/mero/33808a908f3f37a9af85c9e9bac7f11e26cc05a0/src/mero_wrk_tcp_txt.erl | erlang | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
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.
The usage of throw here is intentional and it's correctly used for non-local returns.
Start/stop functions
=============================================================================
External functions
=============================================================================
API functions
Key does not exist, create the key
Key was already created by other thread,
txt incr doesn't support initial etc
=============================================================================
=============================================================================
value has changed since we looked it up, the result of a cas command will be EXISTS
(otherwise STORED). | Copyright ( c ) 2014 , AdRoll
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR 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 ,
-module(mero_wrk_tcp_txt).
-elvis([{elvis_style, no_throw, disable}]).
-include_lib("mero/include/mero.hrl").
-behaviour(mero_pool).
-export([connect/3, controlling_process/2, transaction/3, close/2]).
-record(client, {socket, event_callback}).
-define(SOCKET_OPTIONS,
[binary, {packet, raw}, {active, false}, {reuseaddr, true}, {nodelay, true}]).
connect(Host, Port, CallbackInfo) ->
?LOG_EVENT(CallbackInfo, [socket, connecting]),
case gen_tcp:connect(Host, Port, ?SOCKET_OPTIONS) of
{ok, Socket} ->
?LOG_EVENT(CallbackInfo, [socket, connect, ok]),
{ok, #client{socket = Socket, event_callback = CallbackInfo}};
{error, Reason} ->
?LOG_EVENT(CallbackInfo, [socket, connect, error, {reason, Reason}]),
{error, Reason}
end.
controlling_process(Client, Pid) ->
case gen_tcp:controlling_process(Client#client.socket, Pid) of
ok ->
ok;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback,
[socket, controlling_process, error, {reason, Reason}]),
{error, Reason}
end.
transaction(Client, increment_counter, [Key, Value, Initial, ExpTime, TimeLimit]) ->
First attempt
case send_receive(Client, {?MEMCACHE_INCREMENT, {Key, Value}}, TimeLimit) of
{error, not_found} ->
case send_receive(Client, {?MEMCACHE_ADD, {Key, Initial, ExpTime}}, TimeLimit) of
{ok, stored} ->
{Client, {ok, to_integer(Initial)}};
{error, not_stored} ->
Second attempt ( just in case of someone added right at that time )
case send_receive(Client, {?MEMCACHE_INCREMENT, {Key, Value}}, TimeLimit) of
{error, Reason} ->
{error, Reason};
{ok, NValue} ->
{Client, {ok, to_integer(NValue)}}
end;
{error, Reason} ->
{error, Reason}
end;
{error, Reason} ->
{error, Reason};
{ok, NValue} ->
{Client, {ok, to_integer(NValue)}}
end;
transaction(Client, delete, [Key, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_DELETE, {Key}}, TimeLimit) of
{ok, deleted} ->
{Client, ok};
{error, not_found} ->
{Client, {error, not_found}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, mdelete, [Keys, TimeLimit]) ->
Resp =
mero_util:foreach(fun(Key) ->
case send_receive(Client, {?MEMCACHE_DELETE, {Key}}, TimeLimit) of
{ok, deleted} ->
continue;
{error, not_found} ->
continue;
{error, Reason} ->
{break, {error, Reason}}
end
end,
Keys),
{Client, Resp};
transaction(Client, add, [Key, Value, ExpTime, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_ADD, {Key, Value, ExpTime}}, TimeLimit) of
{ok, stored} ->
{Client, ok};
{error, not_stored} ->
{Client, {error, not_stored}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, get, [Key, TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_GET, {[Key]}}, TimeLimit) of
{ok, [Found]} ->
{Client, Found};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, set, [Key, Value, ExpTime, TimeLimit, CAS]) ->
case send_receive(Client, {?MEMCACHE_SET, {Key, Value, ExpTime, CAS}}, TimeLimit) of
{ok, stored} ->
{Client, ok};
{error, already_exists} ->
{Client, {error, already_exists}};
{error, not_found} ->
{Client, {error, not_found}};
{error, Reason} ->
{error, Reason}
end;
transaction(Client, flush_all, [TimeLimit]) ->
case send_receive(Client, {?MEMCACHE_FLUSH_ALL, {}}, TimeLimit) of
{ok, ok} ->
{Client, ok};
{error, Reason} ->
{error, Reason}
end;
mset / madd are currently only supported by the binary protocol implementation .
transaction(Client, async_mset, _) ->
{Client, {error, unsupported_operation}};
transaction(Client, async_madd, _) ->
{Client, {error, unsupported_operation}};
transaction(Client, async_mget, [Keys]) ->
case async_mget(Client, Keys) of
{error, Reason} ->
{error, Reason};
{ok, ok} ->
{Client, ok}
end;
transaction(Client, async_delete, [Keys]) ->
case async_delete(Client, Keys) of
{error, Reason} ->
{error, Reason};
{ok, ok} ->
{Client, ok}
end;
transaction(_Client, async_increment, [_Keys]) ->
transaction(Client, async_blank_response, [_Keys, _Timeout]) ->
{Client, [ok]};
transaction(Client, async_mget_response, [Keys, Timeout]) ->
case async_mget_response(Client, Keys, Timeout) of
{error, Reason} ->
{error, Reason};
{ok, {ok, FoundItems}} ->
FoundKeys = [Key || #mero_item{key = Key} <- FoundItems],
NotFoundKeys = lists:subtract(Keys, FoundKeys),
Result =
[#mero_item{key = Key, value = undefined} || Key <- NotFoundKeys] ++ FoundItems,
{Client, Result}
end.
close(Client, Reason) ->
?LOG_EVENT(Client#client.event_callback, [closing_socket, {reason, Reason}]),
gen_tcp:close(Client#client.socket).
Internal functions
send_receive(Client, {_Op, _Args} = Cmd, TimeLimit) ->
try
Data = pack(Cmd),
ok = send(Client, Data),
receive_response(Client, Cmd, TimeLimit, <<>>, [])
catch
{failed, Reason} ->
{error, Reason}
end.
pack({?MEMCACHE_DELETE, {Key}}) when is_binary(Key) ->
[<<"delete ">>, Key, <<"\r\n">>];
pack({?MEMCACHE_DELETEQ, {Key}}) when is_binary(Key) ->
[<<"delete ">>, Key, <<" noreply ">>, <<"\r\n">>];
pack({?MEMCACHE_ADD, {Key, Initial, ExpTime}}) ->
NBytes = integer_to_binary(size(Initial)),
[<<"add ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_SET, {Key, Initial, ExpTime, undefined}}) ->
NBytes = integer_to_binary(size(Initial)),
[<<"set ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_SET, {Key, Initial, ExpTime, CAS}}) when is_integer(CAS) ->
note : CAS should only be supplied if setting a value after looking it up . if the
NBytes = integer_to_binary(size(Initial)),
[<<"cas ">>,
Key,
<<" ">>,
<<"00">>,
<<" ">>,
ExpTime,
<<" ">>,
NBytes,
<<" ">>,
integer_to_binary(CAS),
<<"\r\n">>,
Initial,
<<"\r\n">>];
pack({?MEMCACHE_INCREMENT, {Key, Value}}) ->
[<<"incr ">>, Key, <<" ">>, Value, <<"\r\n">>];
pack({?MEMCACHE_FLUSH_ALL, {}}) ->
[<<"flush_all\r\n">>];
pack({?MEMCACHE_GET, {Keys}}) when is_list(Keys) ->
Query = lists:foldr(fun(Key, Acc) -> [Key, <<" ">> | Acc] end, [], Keys),
[<<"gets ">>, Query, <<"\r\n">>].
send(Client, Data) ->
case gen_tcp:send(Client#client.socket, Data) of
ok ->
ok;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback, [socket, send, error, {reason, Reason}]),
throw({failed, Reason})
end.
receive_response(Client, Cmd, TimeLimit, AccBinary, AccResult) ->
case gen_tcp_recv(Client, 0, TimeLimit) of
{ok, Data} ->
NAcc = <<AccBinary/binary, Data/binary>>,
case parse_reply(Client, Cmd, NAcc, TimeLimit, AccResult) of
{ok, Atom, []} when (Atom == stored) or (Atom == deleted) or (Atom == ok) ->
{ok, Atom};
{ok, Binary} when is_binary(Binary) ->
{ok, Binary};
{ok, finished, Result} ->
{ok, Result};
{ok, NBuffer, NewCmd, NAccResult} ->
receive_response(Client, NewCmd, TimeLimit, NBuffer, NAccResult);
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback,
[socket, rcv, error, {reason, Reason}]),
throw({failed, Reason})
end;
{error, Reason} ->
?LOG_EVENT(Client#client.event_callback, [socket, rcv, error, {reason, Reason}]),
throw({failed, Reason})
end.
process_result({?MEMCACHE_GET, {Keys}}, finished, Result) ->
Result ++ [#mero_item{key = Key} || Key <- Keys];
process_result(_Cmd, _Status, Result) ->
Result.
This is so extremely shitty that I will do the binary prototol no matter what :(
parse_reply(Client, Cmd, Buffer, TimeLimit, AccResult) ->
case split_command(Buffer) of
{error, incomplete} ->
{ok, Buffer, Cmd, AccResult};
{Command, BinaryRest} ->
case {Cmd, parse_command(Command)} of
{_, {ok, Status}} when is_atom(Status) ->
{ok, Status, process_result(Cmd, Status, AccResult)};
{{?MEMCACHE_GET, {Keys}}, {ok, {value, Key, Bytes, CAS}}} ->
case parse_value(Client, Key, Bytes, CAS, TimeLimit, BinaryRest) of
{ok, Item, NewBinaryRest} ->
parse_reply(Client,
{?MEMCACHE_GET, {lists:delete(Key, Keys)}},
NewBinaryRest,
TimeLimit,
[Item | AccResult]);
{error, Reason} ->
{error, Reason}
end;
{_, {ok, Binary}} when is_binary(Binary) ->
{ok, Binary};
{_, {error, Reason}} ->
{error, Reason}
end
end.
parse_value(Client, Key, Bytes, CAS, TimeLimit, Buffer) ->
case Buffer of
<<Value:Bytes/binary, "\r\n", RestAfterValue/binary>> ->
{ok,
#mero_item{key = Key,
value = Value,
cas = CAS},
RestAfterValue};
_ when size(Buffer) < Bytes + size(<<"\r\n">>) ->
case gen_tcp_recv(Client, 0, TimeLimit) of
{ok, Data} ->
parse_value(Client, Key, Bytes, CAS, TimeLimit, <<Buffer/binary, Data/binary>>);
{error, Reason} ->
{error, Reason}
end;
_ ->
{error, invalid_value_size}
end.
split_command(Buffer) ->
case binary:split(Buffer, [<<"\r\n">>], []) of
[Line, RemainBuffer] ->
{binary:split(Line, [<<" ">>], [global, trim]), RemainBuffer};
[_UncompletedLine] ->
{error, incomplete}
end.
parse_command([<<"ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"CLIENT_ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"SERVER_ERROR">> | Reason]) ->
{error, Reason};
parse_command([<<"EXISTS">>]) ->
{error, already_exists};
parse_command([<<"NOT_FOUND">>]) ->
{error, not_found};
parse_command([<<"NOT_STORED">>]) ->
{error, not_stored};
parse_command([<<"END">>]) ->
{ok, finished};
parse_command([<<"STORED">>]) ->
{ok, stored};
parse_command([<<"DELETED">>]) ->
{ok, deleted};
parse_command([<<"VALUE">>, Key, _Flag, Bytes]) ->
{ok, {value, Key, list_to_integer(binary_to_list(Bytes)), undefined}};
parse_command([<<"VALUE">>, Key, _Flag, Bytes, CAS]) ->
{ok, {value, Key, list_to_integer(binary_to_list(Bytes)), binary_to_integer(CAS)}};
parse_command([<<"OK">>]) ->
{ok, ok};
parse_command([<<"VERSION">> | Version]) ->
{ok, Version};
parse_command([Value]) ->
{ok, Value};
parse_command(Line) ->
{error, {unknown, Line}}.
gen_tcp_recv(Client, Bytes, TimeLimit) ->
Timeout = mero_conf:millis_to(TimeLimit),
case Timeout of
0 ->
{error, timeout};
Timeout ->
gen_tcp:recv(Client#client.socket, Bytes, Timeout)
end.
to_integer(Value) when is_integer(Value) ->
Value;
to_integer(Value) when is_binary(Value) ->
binary_to_integer(Value).
async_mget(Client, Keys) ->
try
Data = pack({?MEMCACHE_GET, {Keys}}),
{ok, send(Client, Data)}
catch
{failed, Reason} ->
{error, Reason}
end.
async_delete(Client, Keys) ->
try
{ok, lists:foreach(fun(K) -> send(Client, pack({?MEMCACHE_DELETEQ, {K}})) end, Keys)}
catch
{failed, Reason} ->
{error, Reason}
end.
async_mget_response(Client, Keys, TimeLimit) ->
try
{ok, receive_response(Client, {?MEMCACHE_GET, {Keys}}, TimeLimit, <<>>, [])}
catch
{failed, Reason} ->
{error, Reason}
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.