_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
a99069ed5409b15a962e8048f299a1d1f26d88d2ed2a33e0b9cfcc1878465c66
backtracking/ocamlgraph
dGraphTreeModel.ml
(**************************************************************************) (* *) (* This file is part of OcamlGraph. *) (* *) Copyright ( C ) 2009 - 2010 CEA ( Commissariat � l' � ) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 , with a linking exception . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) (* See the file ../LICENSE for more details. *) (* *) (* Authors: *) ( ) (* - Jean-Denis Koeck () *) - ( ) (* *) (**************************************************************************) module type S = sig module Tree: Graphviz.GraphWithDotAttrs module TreeManipulation : sig type t val get_structure : t -> Tree.t val get_tree_vertices : Tree.V.label -> t -> Tree.V.t list val get_graph_vertex : Tree.V.t -> t -> Tree.V.label val is_ghost_node : Tree.V.t -> t -> bool val is_ghost_edge : Tree.E.t -> t -> bool end type cluster = string type graph_layout class tree_model : graph_layout -> TreeManipulation.t -> [Tree.V.t, Tree.E.t, cluster] DGraphModel.abstract_model val tree : unit -> TreeManipulation.t end module Build (G: Sig.G) (T: Graphviz.GraphWithDotAttrs with type V.label = G.V.t) (TM: DGraphSubTree.S with type Tree.t = T.t and type Tree.V.t = T.V.t and type Tree.E.t = T.E.t) = struct module TreeManipulation = TM type cluster = string module X = XDot.Make(T) type graph_layout = X.graph_layout class tree_model layout tree : [ T.V.t, T.E.t, cluster ] DGraphModel.abstract_model = let tree_structure = TM.get_structure tree in object (* Iterators *) method iter_edges f = T.iter_edges (fun v1 v2 -> if not (TM.is_ghost_node v1 tree && TM.is_ghost_node v2 tree) then f v1 v2) tree_structure method iter_edges_e f = T.iter_edges_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure method iter_pred f v = T.iter_pred (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure v method iter_pred_e f v = T.iter_pred_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure v method iter_succ f = T.iter_succ (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure method iter_succ_e f = T.iter_succ_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure method iter_vertex f = T.iter_vertex (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure method iter_associated_vertex f v = let origin_vertex = TM.get_graph_vertex v tree in List.iter (fun v -> if not (TM.is_ghost_node v tree) then f v) (TM.get_tree_vertices origin_vertex tree) method iter_clusters f = Hashtbl.iter (fun k _ -> f k) layout.X.cluster_layouts (* Membership functions *) method find_edge = try T.find_edge tree_structure with Not_found -> assert false method mem_edge = T.mem_edge tree_structure method mem_edge_e = T.mem_edge_e tree_structure method mem_vertex = T.mem_vertex tree_structure method src = T.E.src method dst = T.E.dst Layout method bounding_box = layout.X.bbox method get_vertex_layout v = try X.HV.find layout.X.vertex_layouts v with Not_found -> assert false method get_edge_layout e = try X.HE.find e layout.X.edge_layouts with Not_found -> assert false method get_cluster_layout c = try Hashtbl.find layout.X.cluster_layouts c with Not_found -> assert false end end module SubTreeMake(G: Graphviz.GraphWithDotAttrs) = struct module T = Imperative.Digraph.Abstract(G.V) module TM = DGraphSubTree.Make(G)(T) let tree_ref : TM.t option ref = ref None let tree () = match !tree_ref with None -> assert false | Some t -> t let graph_ref: G.t option ref = ref None let graph () = match !graph_ref with None -> assert false | Some g -> g module Tree = struct include T let graph_attributes _ = G.graph_attributes (graph ()) let default_vertex_attributes _ = G.default_vertex_attributes (graph ()) let default_edge_attributes _ = G.default_edge_attributes (graph ()) let cpt = ref 0 let name_table = Hashtbl.create 97 let vertex_name v = try Hashtbl.find name_table v with Not_found -> incr cpt; Hashtbl.add name_table v (string_of_int !cpt); string_of_int !cpt let vertex_attributes v = let t = tree () in if TM.is_ghost_node v t then [ `Style `Invis ] else G.vertex_attributes (TM.get_graph_vertex v t) let edge_attributes e = let t = tree () in if TM.is_ghost_node (T.E.src e) t || TM.is_ghost_node (T.E.dst e) t then [ `Style `Dashed; `Dir `None ] else G.edge_attributes (G.find_edge (graph ()) (TM.get_graph_vertex (T.E.src e) t) (TM.get_graph_vertex (T.E.dst e) t)) let get_subgraph v = let t = tree () in if TM.is_ghost_node v t then None else G.get_subgraph (TM.get_graph_vertex v t) end include Build(G)(Tree)(TM) module TreeLayout = DGraphTreeLayout.Make (Tree) (struct let is_ghost_node v = TM.is_ghost_node v (tree ()) end) let from_graph ?(depth_forward=2) ?(depth_backward=2) ~fontMeasure g v = (* Generate subtree *) let t = TM.make g v depth_forward depth_backward in tree_ref := Some t; graph_ref := Some g; let layout = TreeLayout.from_tree ~fontMeasure (TM.get_structure t) (TM.get_root t) in new tree_model layout t end module SubTreeDotModelMake = struct module T = Imperative.Digraph.Abstract(DGraphModel.DotG.V) module TM = DGraphSubTree.Make_from_dot_model(T) let tree_ref : TM.t option ref = ref None let tree () = match !tree_ref with None -> assert false | Some t -> t module TreeLayout = DGraphTreeLayout.MakeFromDotModel (T) (struct let is_ghost_node v = TM.is_ghost_node v (tree ()) end) include TreeLayout include Build(DGraphModel.DotG)(Tree)(TM) let from_model ?(depth_forward=2) ?(depth_backward=2) model v = let t = TM.make model v depth_forward depth_backward in tree_ref := Some t; let tree_structure = TM.get_structure t in let layout = from_model tree_structure (TM.get_root t) model in new tree_model layout t end
null
https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/src/dGraphTreeModel.ml
ocaml
************************************************************************ This file is part of OcamlGraph. you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. See the file ../LICENSE for more details. Authors: - Jean-Denis Koeck () ************************************************************************ Iterators Membership functions Generate subtree
Copyright ( C ) 2009 - 2010 CEA ( Commissariat � l' � ) Lesser General Public License as published by the Free Software Foundation , version 2.1 , with a linking exception . ( ) - ( ) module type S = sig module Tree: Graphviz.GraphWithDotAttrs module TreeManipulation : sig type t val get_structure : t -> Tree.t val get_tree_vertices : Tree.V.label -> t -> Tree.V.t list val get_graph_vertex : Tree.V.t -> t -> Tree.V.label val is_ghost_node : Tree.V.t -> t -> bool val is_ghost_edge : Tree.E.t -> t -> bool end type cluster = string type graph_layout class tree_model : graph_layout -> TreeManipulation.t -> [Tree.V.t, Tree.E.t, cluster] DGraphModel.abstract_model val tree : unit -> TreeManipulation.t end module Build (G: Sig.G) (T: Graphviz.GraphWithDotAttrs with type V.label = G.V.t) (TM: DGraphSubTree.S with type Tree.t = T.t and type Tree.V.t = T.V.t and type Tree.E.t = T.E.t) = struct module TreeManipulation = TM type cluster = string module X = XDot.Make(T) type graph_layout = X.graph_layout class tree_model layout tree : [ T.V.t, T.E.t, cluster ] DGraphModel.abstract_model = let tree_structure = TM.get_structure tree in object method iter_edges f = T.iter_edges (fun v1 v2 -> if not (TM.is_ghost_node v1 tree && TM.is_ghost_node v2 tree) then f v1 v2) tree_structure method iter_edges_e f = T.iter_edges_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure method iter_pred f v = T.iter_pred (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure v method iter_pred_e f v = T.iter_pred_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure v method iter_succ f = T.iter_succ (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure method iter_succ_e f = T.iter_succ_e (fun e -> if not (TM.is_ghost_edge e tree) then f e) tree_structure method iter_vertex f = T.iter_vertex (fun v -> if not (TM.is_ghost_node v tree) then f v) tree_structure method iter_associated_vertex f v = let origin_vertex = TM.get_graph_vertex v tree in List.iter (fun v -> if not (TM.is_ghost_node v tree) then f v) (TM.get_tree_vertices origin_vertex tree) method iter_clusters f = Hashtbl.iter (fun k _ -> f k) layout.X.cluster_layouts method find_edge = try T.find_edge tree_structure with Not_found -> assert false method mem_edge = T.mem_edge tree_structure method mem_edge_e = T.mem_edge_e tree_structure method mem_vertex = T.mem_vertex tree_structure method src = T.E.src method dst = T.E.dst Layout method bounding_box = layout.X.bbox method get_vertex_layout v = try X.HV.find layout.X.vertex_layouts v with Not_found -> assert false method get_edge_layout e = try X.HE.find e layout.X.edge_layouts with Not_found -> assert false method get_cluster_layout c = try Hashtbl.find layout.X.cluster_layouts c with Not_found -> assert false end end module SubTreeMake(G: Graphviz.GraphWithDotAttrs) = struct module T = Imperative.Digraph.Abstract(G.V) module TM = DGraphSubTree.Make(G)(T) let tree_ref : TM.t option ref = ref None let tree () = match !tree_ref with None -> assert false | Some t -> t let graph_ref: G.t option ref = ref None let graph () = match !graph_ref with None -> assert false | Some g -> g module Tree = struct include T let graph_attributes _ = G.graph_attributes (graph ()) let default_vertex_attributes _ = G.default_vertex_attributes (graph ()) let default_edge_attributes _ = G.default_edge_attributes (graph ()) let cpt = ref 0 let name_table = Hashtbl.create 97 let vertex_name v = try Hashtbl.find name_table v with Not_found -> incr cpt; Hashtbl.add name_table v (string_of_int !cpt); string_of_int !cpt let vertex_attributes v = let t = tree () in if TM.is_ghost_node v t then [ `Style `Invis ] else G.vertex_attributes (TM.get_graph_vertex v t) let edge_attributes e = let t = tree () in if TM.is_ghost_node (T.E.src e) t || TM.is_ghost_node (T.E.dst e) t then [ `Style `Dashed; `Dir `None ] else G.edge_attributes (G.find_edge (graph ()) (TM.get_graph_vertex (T.E.src e) t) (TM.get_graph_vertex (T.E.dst e) t)) let get_subgraph v = let t = tree () in if TM.is_ghost_node v t then None else G.get_subgraph (TM.get_graph_vertex v t) end include Build(G)(Tree)(TM) module TreeLayout = DGraphTreeLayout.Make (Tree) (struct let is_ghost_node v = TM.is_ghost_node v (tree ()) end) let from_graph ?(depth_forward=2) ?(depth_backward=2) ~fontMeasure g v = let t = TM.make g v depth_forward depth_backward in tree_ref := Some t; graph_ref := Some g; let layout = TreeLayout.from_tree ~fontMeasure (TM.get_structure t) (TM.get_root t) in new tree_model layout t end module SubTreeDotModelMake = struct module T = Imperative.Digraph.Abstract(DGraphModel.DotG.V) module TM = DGraphSubTree.Make_from_dot_model(T) let tree_ref : TM.t option ref = ref None let tree () = match !tree_ref with None -> assert false | Some t -> t module TreeLayout = DGraphTreeLayout.MakeFromDotModel (T) (struct let is_ghost_node v = TM.is_ghost_node v (tree ()) end) include TreeLayout include Build(DGraphModel.DotG)(Tree)(TM) let from_model ?(depth_forward=2) ?(depth_backward=2) model v = let t = TM.make model v depth_forward depth_backward in tree_ref := Some t; let tree_structure = TM.get_structure t in let layout = from_model tree_structure (TM.get_root t) model in new tree_model layout t end
bc7fc8f657c825a94be5d4f5b1d1b564746333acfdf0828407e4836a9091ce66
f-f/dhall-clj
alpha_normalize.clj
(ns dhall-clj.alpha-normalize (:require [dhall-clj.ast :refer :all] [medley.core :refer [map-vals]])) (defprotocol IAlphaNormalize (alpha-normalize [this] "α-normalize an expression by renaming all variables to `_` and using De Bruijn indices to distinguish them")) (extend-protocol IAlphaNormalize dhall_clj.ast.Const (alpha-normalize [this] this) dhall_clj.ast.Var (alpha-normalize [this] this) dhall_clj.ast.Lam (alpha-normalize [{:keys [arg type body] :as this}] (let [var (->Var arg 0) v' (->Var "_" 0) body' (if (= arg "_") (alpha-normalize body) (-> body (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize)))] (assoc this :arg "_" :type (alpha-normalize type) :body body'))) dhall_clj.ast.Pi (alpha-normalize [{:keys [arg type body] :as this}] (let [var (->Var arg 0) v' (->Var "_" 0) body' (if (= arg "_") (alpha-normalize body) (-> body (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize)))] (assoc this :arg "_" :type (alpha-normalize type) :body body'))) dhall_clj.ast.App (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Let (alpha-normalize [{:keys [bindings next] :as this}] (let [[{:keys [label type? e] :as binding} & more-bindings] bindings var (->Var label 0) v' (->Var "_" 0) next' (if (= label "_") (alpha-normalize next) (-> next (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize))) type?' (when type? (alpha-normalize type?)) binding' (assoc binding :label "_" :type? type?' :e (alpha-normalize e))] (if-not (seq more-bindings) (assoc this :bindings (list binding') :next next') (-> this (update :bindings rest) (assoc :next next') (alpha-normalize) (update :bindings conj binding'))))) dhall_clj.ast.Annot (alpha-normalize [this] (-> this (update :val alpha-normalize) (update :type alpha-normalize))) dhall_clj.ast.BoolT (alpha-normalize [this] this) dhall_clj.ast.BoolLit (alpha-normalize [this] this) dhall_clj.ast.BoolAnd (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolOr (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolEQ (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolNE (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolIf (alpha-normalize [this] (-> this (update :test alpha-normalize) (update :then alpha-normalize) (update :else alpha-normalize))) dhall_clj.ast.NaturalT (alpha-normalize [this] this) dhall_clj.ast.NaturalLit (alpha-normalize [this] this) dhall_clj.ast.NaturalFold (alpha-normalize [this] this) dhall_clj.ast.NaturalBuild (alpha-normalize [this] this) dhall_clj.ast.NaturalIsZero (alpha-normalize [this] this) dhall_clj.ast.NaturalEven (alpha-normalize [this] this) dhall_clj.ast.NaturalOdd (alpha-normalize [this] this) dhall_clj.ast.NaturalToInteger (alpha-normalize [this] this) dhall_clj.ast.NaturalShow (alpha-normalize [this] this) dhall_clj.ast.NaturalPlus (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.NaturalTimes (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.IntegerT (alpha-normalize [this] this) dhall_clj.ast.IntegerLit (alpha-normalize [this] this) dhall_clj.ast.IntegerShow (alpha-normalize [this] this) dhall_clj.ast.IntegerToDouble (alpha-normalize [this] this) dhall_clj.ast.DoubleT (alpha-normalize [this] this) dhall_clj.ast.DoubleLit (alpha-normalize [this] this) dhall_clj.ast.DoubleShow (alpha-normalize [this] this) dhall_clj.ast.TextT (alpha-normalize [this] this) dhall_clj.ast.TextLit (alpha-normalize [this] (map-chunks this alpha-normalize)) dhall_clj.ast.TextShow (alpha-normalize [this] this) dhall_clj.ast.TextAppend (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.ListT (alpha-normalize [this] this) dhall_clj.ast.ListLit (alpha-normalize [{:keys [type?] :as this}] (-> this (assoc :type? (when type? (alpha-normalize type?))) (update :exprs (partial map alpha-normalize)))) dhall_clj.ast.ListAppend (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.ListBuild (alpha-normalize [this] this) dhall_clj.ast.ListFold (alpha-normalize [this] this) dhall_clj.ast.ListLength (alpha-normalize [this] this) dhall_clj.ast.ListHead (alpha-normalize [this] this) dhall_clj.ast.ListLast (alpha-normalize [this] this) dhall_clj.ast.ListIndexed (alpha-normalize [this] this) dhall_clj.ast.ListReverse (alpha-normalize [this] this) dhall_clj.ast.OptionalT (alpha-normalize [this] this) dhall_clj.ast.OptionalLit (alpha-normalize [{:keys [val?] :as this}] (-> this (update :type alpha-normalize) (assoc :val? (when val? (alpha-normalize val?))))) dhall_clj.ast.Some (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.None (alpha-normalize [this] this) dhall_clj.ast.OptionalFold (alpha-normalize [this] this) dhall_clj.ast.OptionalBuild (alpha-normalize [this] this) dhall_clj.ast.RecordT (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals alpha-normalize kvs)))) dhall_clj.ast.RecordLit (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals alpha-normalize kvs)))) dhall_clj.ast.UnionT (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals #(when % (alpha-normalize %)) kvs)))) dhall_clj.ast.UnionLit (alpha-normalize [{:keys [v?] :as this}] (-> this (assoc :v? (when v? (alpha-normalize v?))) (update :kvs (fn [kvs] (map-vals #(when % (alpha-normalize %)) kvs))))) dhall_clj.ast.Combine (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.CombineTypes (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Prefer (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Merge (alpha-normalize [{:keys [type?] :as this}] (-> this (update :a alpha-normalize) (update :b alpha-normalize) (assoc :type? (when type? (alpha-normalize type?))))) dhall_clj.ast.Field (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.Project (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.ImportAlt (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))))
null
https://raw.githubusercontent.com/f-f/dhall-clj/05d25d2464972bbeae46d828b478b4cfd59836dc/src/dhall_clj/alpha_normalize.clj
clojure
(ns dhall-clj.alpha-normalize (:require [dhall-clj.ast :refer :all] [medley.core :refer [map-vals]])) (defprotocol IAlphaNormalize (alpha-normalize [this] "α-normalize an expression by renaming all variables to `_` and using De Bruijn indices to distinguish them")) (extend-protocol IAlphaNormalize dhall_clj.ast.Const (alpha-normalize [this] this) dhall_clj.ast.Var (alpha-normalize [this] this) dhall_clj.ast.Lam (alpha-normalize [{:keys [arg type body] :as this}] (let [var (->Var arg 0) v' (->Var "_" 0) body' (if (= arg "_") (alpha-normalize body) (-> body (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize)))] (assoc this :arg "_" :type (alpha-normalize type) :body body'))) dhall_clj.ast.Pi (alpha-normalize [{:keys [arg type body] :as this}] (let [var (->Var arg 0) v' (->Var "_" 0) body' (if (= arg "_") (alpha-normalize body) (-> body (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize)))] (assoc this :arg "_" :type (alpha-normalize type) :body body'))) dhall_clj.ast.App (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Let (alpha-normalize [{:keys [bindings next] :as this}] (let [[{:keys [label type? e] :as binding} & more-bindings] bindings var (->Var label 0) v' (->Var "_" 0) next' (if (= label "_") (alpha-normalize next) (-> next (shift 1 v') (subst var v') (shift -1 var) (alpha-normalize))) type?' (when type? (alpha-normalize type?)) binding' (assoc binding :label "_" :type? type?' :e (alpha-normalize e))] (if-not (seq more-bindings) (assoc this :bindings (list binding') :next next') (-> this (update :bindings rest) (assoc :next next') (alpha-normalize) (update :bindings conj binding'))))) dhall_clj.ast.Annot (alpha-normalize [this] (-> this (update :val alpha-normalize) (update :type alpha-normalize))) dhall_clj.ast.BoolT (alpha-normalize [this] this) dhall_clj.ast.BoolLit (alpha-normalize [this] this) dhall_clj.ast.BoolAnd (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolOr (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolEQ (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolNE (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.BoolIf (alpha-normalize [this] (-> this (update :test alpha-normalize) (update :then alpha-normalize) (update :else alpha-normalize))) dhall_clj.ast.NaturalT (alpha-normalize [this] this) dhall_clj.ast.NaturalLit (alpha-normalize [this] this) dhall_clj.ast.NaturalFold (alpha-normalize [this] this) dhall_clj.ast.NaturalBuild (alpha-normalize [this] this) dhall_clj.ast.NaturalIsZero (alpha-normalize [this] this) dhall_clj.ast.NaturalEven (alpha-normalize [this] this) dhall_clj.ast.NaturalOdd (alpha-normalize [this] this) dhall_clj.ast.NaturalToInteger (alpha-normalize [this] this) dhall_clj.ast.NaturalShow (alpha-normalize [this] this) dhall_clj.ast.NaturalPlus (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.NaturalTimes (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.IntegerT (alpha-normalize [this] this) dhall_clj.ast.IntegerLit (alpha-normalize [this] this) dhall_clj.ast.IntegerShow (alpha-normalize [this] this) dhall_clj.ast.IntegerToDouble (alpha-normalize [this] this) dhall_clj.ast.DoubleT (alpha-normalize [this] this) dhall_clj.ast.DoubleLit (alpha-normalize [this] this) dhall_clj.ast.DoubleShow (alpha-normalize [this] this) dhall_clj.ast.TextT (alpha-normalize [this] this) dhall_clj.ast.TextLit (alpha-normalize [this] (map-chunks this alpha-normalize)) dhall_clj.ast.TextShow (alpha-normalize [this] this) dhall_clj.ast.TextAppend (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.ListT (alpha-normalize [this] this) dhall_clj.ast.ListLit (alpha-normalize [{:keys [type?] :as this}] (-> this (assoc :type? (when type? (alpha-normalize type?))) (update :exprs (partial map alpha-normalize)))) dhall_clj.ast.ListAppend (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.ListBuild (alpha-normalize [this] this) dhall_clj.ast.ListFold (alpha-normalize [this] this) dhall_clj.ast.ListLength (alpha-normalize [this] this) dhall_clj.ast.ListHead (alpha-normalize [this] this) dhall_clj.ast.ListLast (alpha-normalize [this] this) dhall_clj.ast.ListIndexed (alpha-normalize [this] this) dhall_clj.ast.ListReverse (alpha-normalize [this] this) dhall_clj.ast.OptionalT (alpha-normalize [this] this) dhall_clj.ast.OptionalLit (alpha-normalize [{:keys [val?] :as this}] (-> this (update :type alpha-normalize) (assoc :val? (when val? (alpha-normalize val?))))) dhall_clj.ast.Some (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.None (alpha-normalize [this] this) dhall_clj.ast.OptionalFold (alpha-normalize [this] this) dhall_clj.ast.OptionalBuild (alpha-normalize [this] this) dhall_clj.ast.RecordT (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals alpha-normalize kvs)))) dhall_clj.ast.RecordLit (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals alpha-normalize kvs)))) dhall_clj.ast.UnionT (alpha-normalize [this] (update this :kvs (fn [kvs] (map-vals #(when % (alpha-normalize %)) kvs)))) dhall_clj.ast.UnionLit (alpha-normalize [{:keys [v?] :as this}] (-> this (assoc :v? (when v? (alpha-normalize v?))) (update :kvs (fn [kvs] (map-vals #(when % (alpha-normalize %)) kvs))))) dhall_clj.ast.Combine (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.CombineTypes (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Prefer (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))) dhall_clj.ast.Merge (alpha-normalize [{:keys [type?] :as this}] (-> this (update :a alpha-normalize) (update :b alpha-normalize) (assoc :type? (when type? (alpha-normalize type?))))) dhall_clj.ast.Field (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.Project (alpha-normalize [this] (update this :e alpha-normalize)) dhall_clj.ast.ImportAlt (alpha-normalize [this] (-> this (update :a alpha-normalize) (update :b alpha-normalize))))
4cb0b261ebe52950cbe764fd7bbd563d4f8684e0b73dc0fafee7a554686af13e
serokell/qtah
Gui.hs
This file is part of Qtah . -- Copyright 2015 - 2018 The Qtah Authors . -- -- 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 , either version 3 of the License , or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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, see </>. module Graphics.UI.Qtah.Generator.Interface.Gui (modules) where import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QActionEvent as QActionEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QBrush as QBrush import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QClipboard as QClipboard import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QCloseEvent as QCloseEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QColor as QColor import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QCursor as QCursor import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QDoubleValidator as QDoubleValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QEnterEvent as QEnterEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QExposeEvent as QExposeEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFocusEvent as QFocusEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFont as QFont import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFontDatabase as QFontDatabase import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QHideEvent as QHideEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QHoverEvent as QHoverEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QIcon as QIcon import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QImage as QImage import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QInputEvent as QInputEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QIntValidator as QIntValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QKeyEvent as QKeyEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QMouseEvent as QMouseEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QOpenGLWindow as QOpenGLWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintDevice as QPaintDevice import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintDeviceWindow as QPaintDeviceWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintEvent as QPaintEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPainter as QPainter import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPainterPath as QPainterPath import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPen as QPen import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPixmap as QPixmap import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPolygon as QPolygon import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPolygonF as QPolygonF import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QRasterWindow as QRasterWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QRegion as QRegion import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QShowEvent as QShowEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QStandardItemModel as QStandardItemModel import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QSurface as QSurface import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QTransform as QTransform import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QValidator as QValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QWheelEvent as QWheelEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QWindow as QWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QtahOpenGLWindow as QtahOpenGLWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QtahRasterWindow as QtahRasterWindow import Graphics.UI.Qtah.Generator.Module (AModule) {-# ANN module "HLint: ignore Use camelCase" #-} modules :: [AModule] modules = [ QActionEvent.aModule , QBrush.aModule , QClipboard.aModule , QCloseEvent.aModule , QColor.aModule , QCursor.aModule , QDoubleValidator.aModule , QEnterEvent.aModule , QExposeEvent.aModule , QFocusEvent.aModule , QFont.aModule , QFontDatabase.aModule , QHideEvent.aModule , QHoverEvent.aModule , QIcon.aModule , QImage.aModule , QInputEvent.aModule , QIntValidator.aModule , QKeyEvent.aModule , QMouseEvent.aModule , QOpenGLWindow.aModule , QPaintDevice.aModule , QPaintDeviceWindow.aModule , QPaintEvent.aModule , QPainter.aModule , QPainterPath.aModule , QPen.aModule , QPixmap.aModule , QPolygon.aModule , QPolygonF.aModule , QRasterWindow.aModule , QRegion.aModule , QShowEvent.aModule , QStandardItemModel.aModule , QStandardItemModel.itemModule , QStandardItemModel.itemListModule , QSurface.aModule , QTransform.aModule , QValidator.aModule , QWheelEvent.aModule , QWindow.aModule , QtahOpenGLWindow.aModule , QtahRasterWindow.aModule ]
null
https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Gui.hs
haskell
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 (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 along with this program. If not, see </>. # ANN module "HLint: ignore Use camelCase" #
This file is part of Qtah . Copyright 2015 - 2018 The Qtah Authors . the Free Software Foundation , either version 3 of the License , or GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License module Graphics.UI.Qtah.Generator.Interface.Gui (modules) where import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QActionEvent as QActionEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QBrush as QBrush import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QClipboard as QClipboard import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QCloseEvent as QCloseEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QColor as QColor import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QCursor as QCursor import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QDoubleValidator as QDoubleValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QEnterEvent as QEnterEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QExposeEvent as QExposeEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFocusEvent as QFocusEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFont as QFont import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QFontDatabase as QFontDatabase import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QHideEvent as QHideEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QHoverEvent as QHoverEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QIcon as QIcon import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QImage as QImage import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QInputEvent as QInputEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QIntValidator as QIntValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QKeyEvent as QKeyEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QMouseEvent as QMouseEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QOpenGLWindow as QOpenGLWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintDevice as QPaintDevice import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintDeviceWindow as QPaintDeviceWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPaintEvent as QPaintEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPainter as QPainter import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPainterPath as QPainterPath import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPen as QPen import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPixmap as QPixmap import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPolygon as QPolygon import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QPolygonF as QPolygonF import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QRasterWindow as QRasterWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QRegion as QRegion import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QShowEvent as QShowEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QStandardItemModel as QStandardItemModel import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QSurface as QSurface import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QTransform as QTransform import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QValidator as QValidator import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QWheelEvent as QWheelEvent import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QWindow as QWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QtahOpenGLWindow as QtahOpenGLWindow import qualified Graphics.UI.Qtah.Generator.Interface.Gui.QtahRasterWindow as QtahRasterWindow import Graphics.UI.Qtah.Generator.Module (AModule) modules :: [AModule] modules = [ QActionEvent.aModule , QBrush.aModule , QClipboard.aModule , QCloseEvent.aModule , QColor.aModule , QCursor.aModule , QDoubleValidator.aModule , QEnterEvent.aModule , QExposeEvent.aModule , QFocusEvent.aModule , QFont.aModule , QFontDatabase.aModule , QHideEvent.aModule , QHoverEvent.aModule , QIcon.aModule , QImage.aModule , QInputEvent.aModule , QIntValidator.aModule , QKeyEvent.aModule , QMouseEvent.aModule , QOpenGLWindow.aModule , QPaintDevice.aModule , QPaintDeviceWindow.aModule , QPaintEvent.aModule , QPainter.aModule , QPainterPath.aModule , QPen.aModule , QPixmap.aModule , QPolygon.aModule , QPolygonF.aModule , QRasterWindow.aModule , QRegion.aModule , QShowEvent.aModule , QStandardItemModel.aModule , QStandardItemModel.itemModule , QStandardItemModel.itemListModule , QSurface.aModule , QTransform.aModule , QValidator.aModule , QWheelEvent.aModule , QWindow.aModule , QtahOpenGLWindow.aModule , QtahRasterWindow.aModule ]
1d4903a27d912dfbe42aed5b0d8dcebf0b3cd7a52edd6a7f93d4d21c0cf0f06e
spurious/sagittarius-scheme-mirror
packet.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; ;;; net/mq/mqtt/packet.scm - MQTT v3.1.1 packet ;;; Copyright ( c ) 2010 - 2014 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; reference ;; -open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html ;; This library only provides reading and parsing packets. MQTT is one simple protocol so we do n't make much complexity ;; on this layer. (no need) (library (net mq mqtt packet) (export read-fixed-header read-variable-header&payload ;; write write-fixed-header write-utf8 write-packet-identifier ;; packet types +connect+ +connack+ +publish+ +puback+ +pubrec+ +pubrel+ +pubcomp+ +subscribe+ +suback+ +unsubscribe+ +unsuback+ +pingreq+ +pingresp+ +disconnect+ CONNACK code +connack-accepted+ +connack-unacceptable-protocol+ +connack-identifier-rejected+ +connack-server-unavailable+ +connack-bad-username/password+ +connack-authentication-error+ QoS +qos-at-most-once+ +qos-at-least-once+ +qos-exactly-once+ ;; suback +suback-failure+ ) (import (rnrs) (clos user) (sagittarius) (sagittarius object) (binary pack) (binary io)) (define-constant +connect+ 1) (define-constant +connack+ 2) (define-constant +publish+ 3) (define-constant +puback+ 4) (define-constant +pubrec+ 5) (define-constant +pubrel+ 6) (define-constant +pubcomp+ 7) (define-constant +subscribe+ 8) (define-constant +suback+ 9) (define-constant +unsubscribe+ 10) (define-constant +unsuback+ 11) (define-constant +pingreq+ 12) (define-constant +pingresp+ 13) (define-constant +disconnect+ 14) ;; connack code (define-constant +connack-accepted+ 0) (define-constant +connack-unacceptable-protocol+ 1) (define-constant +connack-identifier-rejected+ 2) (define-constant +connack-server-unavailable+ 3) (define-constant +connack-bad-username/password+ 4) (define-constant +connack-authentication-error+ 5) QoS (define-constant +qos-at-most-once+ 0) (define-constant +qos-at-least-once+ 1) (define-constant +qos-exactly-once+ 2) ;; subscription failure (define-constant +suback-failure+ #x80) (define (read-fixed-header in) (define (read-length in) (define (check-error multiplier) (when (> multiplier (expt #x80 3)) (error 'read-fixed-header "Malformed remaining length"))) (do ((encoded-byte (get-u8 in) (get-u8 in)) (v 0 (+ v (* (bitwise-and encoded-byte #x7F) multiplier))) (multiplier 1 (* multiplier #x80))) ((zero? (bitwise-and encoded-byte #x80)) (check-error multiplier) (+ v (* encoded-byte multiplier))) (check-error multiplier))) (let ((b1 (get-u8 in))) (if (eof-object? b1) (values #f #f #f) (let ((len (read-length in))) (values (bitwise-arithmetic-shift-right b1 4) (bitwise-and b1 #x0F) len))))) (define (write-fixed-header out type flag remaining-length) (define (encode-length out len) (let loop ((encoded-byte (mod len #x80)) (X (div len #x80))) (if (positive? X) (put-u8 out (bitwise-ior encoded-byte #x80)) (put-u8 out encoded-byte)) (unless (zero? X) (loop (mod X #x80) (div X #x80))))) (put-u8 out (bitwise-ior (bitwise-arithmetic-shift type 4) flag)) (encode-length out remaining-length)) (define (write-utf8 out bv) (put-u16 out (bytevector-length bv) (endianness big)) (put-bytevector out bv)) (define (write-packet-identifier out pi) (put-u16 out pi (endianness big))) ;; reading variable header and payload (define (read-utf8-string in) (let ((len (get-unpack in "!S"))) (values (+ len 2) (utf8->string (get-bytevector-n in len))))) (define (read-application-data in) (let ((len (get-unpack in "!S"))) (values (+ len 2) (get-bytevector-n in len)))) ;; hmmmm, binary? (define (read-packet-identifier in) (values 2 (get-bytevector-n in 2))) ;; rules are how to read variable header ;; followings are the rules ;; :u8 - byte : u16 - 16 bit unsigned integer : utf8 - utf8 string ;; :pi - packet identifier ;; As far as I know, there is no other types on MQTT spec remaining length is required in case of more than 1 packets ;; are sent in one go. (define (read-variable-header&payload in len :key (chunk-size 4096) :allow-other-keys rules) (define (read-variable-header in rules) (let loop ((rules rules) (size 0) (r '())) (if (null? rules) (values size (reverse! r)) (case (car rules) ((:u8) (loop (cdr rules) (+ size 1) (cons (get-u8 in) r))) ((:u16 :pi) (loop (cdr rules) (+ size 2) (cons (get-unpack in "!S") r))) ((:utf8) (let-values (((len str) (read-utf8-string in))) (loop (cdr rules) (+ size len) (cons str r)))) (else => (lambda (t) (error 'read-variable-header "unknown rule" t))))))) ;; first read variables (let-values (((vlen vals) (read-variable-header in rules))) (let ((len (- len vlen))) (when (negative? len) (error 'read-variable-header&payload "corrupted data stream")) (values vals (if (> len chunk-size) (input-port->chunked-binary-input-port in :chunk-size chunk-size :threshold len) (open-bytevector-input-port (get-bytevector-n in len))))))) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/net/mq/mqtt/packet.scm
scheme
coding : utf-8 -*- net/mq/mqtt/packet.scm - MQTT v3.1.1 packet Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. reference -open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html This library only provides reading and parsing packets. on this layer. (no need) write packet types suback connack code subscription failure reading variable header and payload hmmmm, binary? rules are how to read variable header followings are the rules :u8 - byte :pi - packet identifier As far as I know, there is no other types on MQTT spec are sent in one go. first read variables
Copyright ( c ) 2010 - 2014 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING MQTT is one simple protocol so we do n't make much complexity (library (net mq mqtt packet) (export read-fixed-header read-variable-header&payload write-fixed-header write-utf8 write-packet-identifier +connect+ +connack+ +publish+ +puback+ +pubrec+ +pubrel+ +pubcomp+ +subscribe+ +suback+ +unsubscribe+ +unsuback+ +pingreq+ +pingresp+ +disconnect+ CONNACK code +connack-accepted+ +connack-unacceptable-protocol+ +connack-identifier-rejected+ +connack-server-unavailable+ +connack-bad-username/password+ +connack-authentication-error+ QoS +qos-at-most-once+ +qos-at-least-once+ +qos-exactly-once+ +suback-failure+ ) (import (rnrs) (clos user) (sagittarius) (sagittarius object) (binary pack) (binary io)) (define-constant +connect+ 1) (define-constant +connack+ 2) (define-constant +publish+ 3) (define-constant +puback+ 4) (define-constant +pubrec+ 5) (define-constant +pubrel+ 6) (define-constant +pubcomp+ 7) (define-constant +subscribe+ 8) (define-constant +suback+ 9) (define-constant +unsubscribe+ 10) (define-constant +unsuback+ 11) (define-constant +pingreq+ 12) (define-constant +pingresp+ 13) (define-constant +disconnect+ 14) (define-constant +connack-accepted+ 0) (define-constant +connack-unacceptable-protocol+ 1) (define-constant +connack-identifier-rejected+ 2) (define-constant +connack-server-unavailable+ 3) (define-constant +connack-bad-username/password+ 4) (define-constant +connack-authentication-error+ 5) QoS (define-constant +qos-at-most-once+ 0) (define-constant +qos-at-least-once+ 1) (define-constant +qos-exactly-once+ 2) (define-constant +suback-failure+ #x80) (define (read-fixed-header in) (define (read-length in) (define (check-error multiplier) (when (> multiplier (expt #x80 3)) (error 'read-fixed-header "Malformed remaining length"))) (do ((encoded-byte (get-u8 in) (get-u8 in)) (v 0 (+ v (* (bitwise-and encoded-byte #x7F) multiplier))) (multiplier 1 (* multiplier #x80))) ((zero? (bitwise-and encoded-byte #x80)) (check-error multiplier) (+ v (* encoded-byte multiplier))) (check-error multiplier))) (let ((b1 (get-u8 in))) (if (eof-object? b1) (values #f #f #f) (let ((len (read-length in))) (values (bitwise-arithmetic-shift-right b1 4) (bitwise-and b1 #x0F) len))))) (define (write-fixed-header out type flag remaining-length) (define (encode-length out len) (let loop ((encoded-byte (mod len #x80)) (X (div len #x80))) (if (positive? X) (put-u8 out (bitwise-ior encoded-byte #x80)) (put-u8 out encoded-byte)) (unless (zero? X) (loop (mod X #x80) (div X #x80))))) (put-u8 out (bitwise-ior (bitwise-arithmetic-shift type 4) flag)) (encode-length out remaining-length)) (define (write-utf8 out bv) (put-u16 out (bytevector-length bv) (endianness big)) (put-bytevector out bv)) (define (write-packet-identifier out pi) (put-u16 out pi (endianness big))) (define (read-utf8-string in) (let ((len (get-unpack in "!S"))) (values (+ len 2) (utf8->string (get-bytevector-n in len))))) (define (read-application-data in) (let ((len (get-unpack in "!S"))) (values (+ len 2) (get-bytevector-n in len)))) (define (read-packet-identifier in) (values 2 (get-bytevector-n in 2))) : u16 - 16 bit unsigned integer : utf8 - utf8 string remaining length is required in case of more than 1 packets (define (read-variable-header&payload in len :key (chunk-size 4096) :allow-other-keys rules) (define (read-variable-header in rules) (let loop ((rules rules) (size 0) (r '())) (if (null? rules) (values size (reverse! r)) (case (car rules) ((:u8) (loop (cdr rules) (+ size 1) (cons (get-u8 in) r))) ((:u16 :pi) (loop (cdr rules) (+ size 2) (cons (get-unpack in "!S") r))) ((:utf8) (let-values (((len str) (read-utf8-string in))) (loop (cdr rules) (+ size len) (cons str r)))) (else => (lambda (t) (error 'read-variable-header "unknown rule" t))))))) (let-values (((vlen vals) (read-variable-header in rules))) (let ((len (- len vlen))) (when (negative? len) (error 'read-variable-header&payload "corrupted data stream")) (values vals (if (> len chunk-size) (input-port->chunked-binary-input-port in :chunk-size chunk-size :threshold len) (open-bytevector-input-port (get-bytevector-n in len))))))) )
c0d01d7f33c8aada826b835182bb10f4849b5910e272bbc7ed88eb06abfea2a9
herd/herdtools7
op.ml
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2010 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) open Printf (*********************) type op = | Add | Sub | Mul | Div | And | Or | Xor | Nor | AndNot2 | ASR | CapaAdd | Alignd | Alignu | Build | ClrPerm | CpyType | CSeal | Cthi | Seal | SetValue | CapaSub | CapaSubs | CapaSetTag | Unseal | ShiftLeft | ShiftRight | Lsr | Lt | Gt | Eq | Ne | Le | Ge | Max | Min | SetTag | SquashMutable | CheckPerms of string | ToInteger let pp_op o = match o with | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | And -> "&" | Or -> "|" | Xor -> "^" (* in C ?? *) | Nor -> "nor" | AndNot2 -> "andnot2" | CapaAdd -> "capaadd" | Alignd -> "alignd" | Alignu -> "alignu" | Build -> "build" | ClrPerm -> "clrperm" | CpyType -> "cpytype" | CSeal -> "cseal" | Cthi -> "cthi" | Seal -> "seal" | SetValue -> "setvalue" | CapaSub -> "capasub" | CapaSubs -> "capasubs" | Unseal -> "unseal" In Java ? ? | ShiftRight -> ">>>" | Lsr -> ">>>" | Eq -> "==" | Lt -> "<" | Gt -> ">" | Le -> "<=" | Ge -> ">=" | Ne -> "!=" | Max -> "max" | Min -> "min" | ASR -> "ASR" | SetTag -> "settag" | CapaSetTag -> "capasettag" | SquashMutable -> "squashmutable" | CheckPerms perms -> sprintf "checkcapa:%s" perms | ToInteger -> "ToInteger" let is_infix = function | Add|Sub|Mul|Div|And|Or|Xor|ShiftLeft | ShiftRight|Lsr|Eq|Lt|Gt|Le|Ge|Ne -> true | Nor|AndNot2|ASR|CapaAdd|Alignd|Alignu|Build | ClrPerm|CpyType|CSeal|Cthi|Seal|SetValue | CapaSub|CapaSubs|CapaSetTag|Unseal | Max|Min|SetTag|SquashMutable|CheckPerms _ | ToInteger -> false let pp_ptx_cmp_op = function | Eq -> ".eq" | Lt -> ".lt" | Gt -> ".gt" | Ne -> ".ne" | Le -> ".le" | Ge -> ".ge" | _ -> Warn.user_error "Invalid PTX comparison operator" (********************) type 'aop op1 = | Not | SetBit of int | UnSetBit of int | ReadBit of int | LeftShift of int | LogicalRightShift of int | ArithRightShift of int | AddK of int | AndK of string | Mask of MachSize.sz | Sxt of MachSize.sz | Inv | TagLoc (* Get tag memory location from location *) | CapaTagLoc | TagExtract (* Extract tag from tagged location *) | LocExtract (* Extract actual location from location *) Unset x bits to the left from y | CapaGetTag | CheckSealed | CapaStrip | IsVirtual (* Detect virtual addresses *) get TLB entry from location | PTELoc (* get PTE entry from location *) | Offset (* get offset from base (symbolic) location *) | IsInstr (* Check nature of constant *) | ArchOp1 of 'aop let pp_op1 hexa pp_aop o = match o with | Not -> "!" | SetBit i -> sprintf "setbit%i" i | UnSetBit i -> sprintf "unsetbit%i" i | ReadBit i -> sprintf "readbit%i" i | LeftShift i -> sprintf "<<[%i]" i | LogicalRightShift i -> sprintf ">>>[%i]" i | ArithRightShift i -> sprintf ">>[%i]" i | AddK i -> (if hexa then sprintf "+[0x%x]" else sprintf "+[%i]") i | AndK i -> sprintf "&[%s]" i | Inv -> "~" | Mask sz -> sprintf "mask%02i" (MachSize.nbits sz) | Sxt sz -> sprintf "sxt%02i" (MachSize.nbits sz) | TagLoc -> "tagloc" | CapaTagLoc -> "capatagloc" | TagExtract -> "tagextract" | LocExtract -> "locextract" | UnSetXBits (nbBits, from) -> sprintf "unset %i bits to the left from %ith bit" nbBits from | CapaGetTag -> "capagettag" | CheckSealed -> "checksealed" | CapaStrip -> "capastrip" | TLBLoc -> "TLBloc" | PTELoc -> "PTEloc" | Offset -> "offset" | IsVirtual -> "IsVirtual" | IsInstr -> "IsInstruction" | ArchOp1 aop -> pp_aop hexa aop (***********) type op3 = If let pp_op3 o s1 s2 s3 = match o with | If -> sprintf "%s ? %s : %s" s1 s2 s3
null
https://raw.githubusercontent.com/herd/herdtools7/d0fa745ab09a1607b4a192f8fcb16548786f7a9e/lib/op.ml
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, ************************************************************************** ******************* in C ?? ****************** Get tag memory location from location Extract tag from tagged location Extract actual location from location Detect virtual addresses get PTE entry from location get offset from base (symbolic) location Check nature of constant *********
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2010 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . open Printf type op = | Add | Sub | Mul | Div | And | Or | Xor | Nor | AndNot2 | ASR | CapaAdd | Alignd | Alignu | Build | ClrPerm | CpyType | CSeal | Cthi | Seal | SetValue | CapaSub | CapaSubs | CapaSetTag | Unseal | ShiftLeft | ShiftRight | Lsr | Lt | Gt | Eq | Ne | Le | Ge | Max | Min | SetTag | SquashMutable | CheckPerms of string | ToInteger let pp_op o = match o with | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | And -> "&" | Or -> "|" | Nor -> "nor" | AndNot2 -> "andnot2" | CapaAdd -> "capaadd" | Alignd -> "alignd" | Alignu -> "alignu" | Build -> "build" | ClrPerm -> "clrperm" | CpyType -> "cpytype" | CSeal -> "cseal" | Cthi -> "cthi" | Seal -> "seal" | SetValue -> "setvalue" | CapaSub -> "capasub" | CapaSubs -> "capasubs" | Unseal -> "unseal" In Java ? ? | ShiftRight -> ">>>" | Lsr -> ">>>" | Eq -> "==" | Lt -> "<" | Gt -> ">" | Le -> "<=" | Ge -> ">=" | Ne -> "!=" | Max -> "max" | Min -> "min" | ASR -> "ASR" | SetTag -> "settag" | CapaSetTag -> "capasettag" | SquashMutable -> "squashmutable" | CheckPerms perms -> sprintf "checkcapa:%s" perms | ToInteger -> "ToInteger" let is_infix = function | Add|Sub|Mul|Div|And|Or|Xor|ShiftLeft | ShiftRight|Lsr|Eq|Lt|Gt|Le|Ge|Ne -> true | Nor|AndNot2|ASR|CapaAdd|Alignd|Alignu|Build | ClrPerm|CpyType|CSeal|Cthi|Seal|SetValue | CapaSub|CapaSubs|CapaSetTag|Unseal | Max|Min|SetTag|SquashMutable|CheckPerms _ | ToInteger -> false let pp_ptx_cmp_op = function | Eq -> ".eq" | Lt -> ".lt" | Gt -> ".gt" | Ne -> ".ne" | Le -> ".le" | Ge -> ".ge" | _ -> Warn.user_error "Invalid PTX comparison operator" type 'aop op1 = | Not | SetBit of int | UnSetBit of int | ReadBit of int | LeftShift of int | LogicalRightShift of int | ArithRightShift of int | AddK of int | AndK of string | Mask of MachSize.sz | Sxt of MachSize.sz | Inv | CapaTagLoc Unset x bits to the left from y | CapaGetTag | CheckSealed | CapaStrip get TLB entry from location | ArchOp1 of 'aop let pp_op1 hexa pp_aop o = match o with | Not -> "!" | SetBit i -> sprintf "setbit%i" i | UnSetBit i -> sprintf "unsetbit%i" i | ReadBit i -> sprintf "readbit%i" i | LeftShift i -> sprintf "<<[%i]" i | LogicalRightShift i -> sprintf ">>>[%i]" i | ArithRightShift i -> sprintf ">>[%i]" i | AddK i -> (if hexa then sprintf "+[0x%x]" else sprintf "+[%i]") i | AndK i -> sprintf "&[%s]" i | Inv -> "~" | Mask sz -> sprintf "mask%02i" (MachSize.nbits sz) | Sxt sz -> sprintf "sxt%02i" (MachSize.nbits sz) | TagLoc -> "tagloc" | CapaTagLoc -> "capatagloc" | TagExtract -> "tagextract" | LocExtract -> "locextract" | UnSetXBits (nbBits, from) -> sprintf "unset %i bits to the left from %ith bit" nbBits from | CapaGetTag -> "capagettag" | CheckSealed -> "checksealed" | CapaStrip -> "capastrip" | TLBLoc -> "TLBloc" | PTELoc -> "PTEloc" | Offset -> "offset" | IsVirtual -> "IsVirtual" | IsInstr -> "IsInstruction" | ArchOp1 aop -> pp_aop hexa aop type op3 = If let pp_op3 o s1 s2 s3 = match o with | If -> sprintf "%s ? %s : %s" s1 s2 s3
68c7d93685e33a28963ceac6b6aa865f7e55e2fc82bf6e44214657a81aa7bd6f
OlivierSohn/hamazed
Hue.hs
# LANGUAGE NoImplicitPrelude # | Every ' Color8 ' can be decomposed in a /saturated/ part and a /gray/ part . Throughout this module , the notion of hue applies to the /saturated/ part . Throughout this module, the notion of hue applies to the /saturated/ part. -} module Imj.Graphics.Color.Hue ( rotateHue , hue , countHuesOfSameIntensity , sameIntensityHues ) where import Imj.Prelude import Imj.Graphics.Color.Types import Imj.Graphics.Color.Hue.Internal # INLINE hue # hue :: Color8 a -> Maybe Float hue = hue' . color8CodeToXterm256 -- | Generates a color that has the same /gray/ component as the input color, and whose /saturated/ component has the same intensity ( ie max color component ) as the /saturated/ component of the input color . rotateHue :: Float -- ^ The angle, in Turns (as defined -- < here>), ie @1@ is a full circle. Due to the discrete nature of the 6x6x6 color space in which ' Color8 ' live , angles will be rounded , hence this function called with 2 different but close -- angles may generate the same color. -- You may want to use 'countHuesOfSameIntensity' to compute the minimum angle that will produce -- a different color. -> Color8 a -> Color8 a rotateHue dh = xterm256ColorToCode . rotateHue' dh . color8CodeToXterm256 Returns how many different colors can be obtained from this color by calling ' rotateHue ' on it . To get each one of these colors : @ let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map ( \i - > rotateHue ( fromIntegral i * angleIncrement ) color ) [ 0 .. pred n ] @ To get each one of these colors: @ let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map (\i -> rotateHue (fromIntegral i * angleIncrement) color) [0..pred n] @ -} countHuesOfSameIntensity :: Color8 a -> Int countHuesOfSameIntensity = countHuesOfSameIntensity' . color8CodeToXterm256 -- | Returns all 'Color8' that have the same /gray/ component as the input 'Color8' -- and saturated components of the same intensity as the saturated component of the -- input 'Color8'. sameIntensityHues :: Color8 a -> [Color8 a] sameIntensityHues color = let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map (\i -> rotateHue (fromIntegral i * angleIncrement) color) [0..pred n]
null
https://raw.githubusercontent.com/OlivierSohn/hamazed/6c2b20d839ede7b8651fb7b425cb27ea93808a4a/imj-base/src/Imj/Graphics/Color/Hue.hs
haskell
| Generates a color that has the same /gray/ component as the input color, ^ The angle, in Turns (as defined < here>), ie @1@ is a full circle. angles may generate the same color. You may want to use 'countHuesOfSameIntensity' to compute the minimum angle that will produce a different color. | Returns all 'Color8' that have the same /gray/ component as the input 'Color8' and saturated components of the same intensity as the saturated component of the input 'Color8'.
# LANGUAGE NoImplicitPrelude # | Every ' Color8 ' can be decomposed in a /saturated/ part and a /gray/ part . Throughout this module , the notion of hue applies to the /saturated/ part . Throughout this module, the notion of hue applies to the /saturated/ part. -} module Imj.Graphics.Color.Hue ( rotateHue , hue , countHuesOfSameIntensity , sameIntensityHues ) where import Imj.Prelude import Imj.Graphics.Color.Types import Imj.Graphics.Color.Hue.Internal # INLINE hue # hue :: Color8 a -> Maybe Float hue = hue' . color8CodeToXterm256 and whose /saturated/ component has the same intensity ( ie max color component ) as the /saturated/ component of the input color . rotateHue :: Float Due to the discrete nature of the 6x6x6 color space in which ' Color8 ' live , angles will be rounded , hence this function called with 2 different but close -> Color8 a -> Color8 a rotateHue dh = xterm256ColorToCode . rotateHue' dh . color8CodeToXterm256 Returns how many different colors can be obtained from this color by calling ' rotateHue ' on it . To get each one of these colors : @ let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map ( \i - > rotateHue ( fromIntegral i * angleIncrement ) color ) [ 0 .. pred n ] @ To get each one of these colors: @ let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map (\i -> rotateHue (fromIntegral i * angleIncrement) color) [0..pred n] @ -} countHuesOfSameIntensity :: Color8 a -> Int countHuesOfSameIntensity = countHuesOfSameIntensity' . color8CodeToXterm256 sameIntensityHues :: Color8 a -> [Color8 a] sameIntensityHues color = let n = countHuesOfSameIntensity color angleIncrement = 1 / fromIntegral n in map (\i -> rotateHue (fromIntegral i * angleIncrement) color) [0..pred n]
717d88c37838f63e3e07902953220c5be5e4ffb6e6eb47b4b835d3495a49aa47
ocsigen/js_of_ocaml
lazy.ml
Js_of_ocaml tests * / * Copyright ( C ) 2019 Hugo Heuzard * * 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 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) 2019 Hugo Heuzard * * 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 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 Util let%expect_test "static eval of string get" = let program = compile_and_parse {| let lz = lazy ( List.map (fun x -> x * x) [8;9] ) let rec do_the_lazy_rec n = if n = 0 then [] else (Lazy.force lz) :: do_the_lazy_rec (n-1) let _ = do_the_lazy_rec 8 |} in print_fun_decl program (Some "do_the_lazy_rec"); [%expect {| function do_the_lazy_rec(n){ if(0 === n) return 0; var _b_ = do_the_lazy_rec(n - 1 | 0), _c_ = runtime.caml_obj_tag(lz); if(250 === _c_) var _d_ = lz[1]; else{ var switch$0 = 0; if(246 !== _c_ && 244 !== _c_){var _d_ = lz; switch$0 = 1;} if(! switch$0) var _d_ = caml_call1(CamlinternalLazy[2], lz); } return [0, _d_, _b_]; } //end |}]
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/4b1253d25c7539a73305f4320a945ee9751abfee/compiler/tests-compiler/lazy.ml
ocaml
Js_of_ocaml tests * / * Copyright ( C ) 2019 Hugo Heuzard * * 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 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) 2019 Hugo Heuzard * * 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 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 Util let%expect_test "static eval of string get" = let program = compile_and_parse {| let lz = lazy ( List.map (fun x -> x * x) [8;9] ) let rec do_the_lazy_rec n = if n = 0 then [] else (Lazy.force lz) :: do_the_lazy_rec (n-1) let _ = do_the_lazy_rec 8 |} in print_fun_decl program (Some "do_the_lazy_rec"); [%expect {| function do_the_lazy_rec(n){ if(0 === n) return 0; var _b_ = do_the_lazy_rec(n - 1 | 0), _c_ = runtime.caml_obj_tag(lz); if(250 === _c_) var _d_ = lz[1]; else{ var switch$0 = 0; if(246 !== _c_ && 244 !== _c_){var _d_ = lz; switch$0 = 1;} if(! switch$0) var _d_ = caml_call1(CamlinternalLazy[2], lz); } return [0, _d_, _b_]; } //end |}]
5edf1b3646fe68b4cfb44527c74a3d4b389886d77a5b20fc1cd0f6a221838df1
deech/fltkhs-demos
nativefilechooser-simple-app.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Graphics.UI.FLTK.LowLevel.FL as FL import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Fl_Enumerations import Graphics.UI.FLTK.LowLevel.FLTKHS import System.Directory import System.Exit import qualified Data.Text as T openFile :: FilePath -> IO () openFile fp = print $ "Open '" ++ fp ++ "''" saveFile :: FilePath -> IO () saveFile fp = do print $ "Saving '" ++ fp ++ "'" exists' <- doesFileExist fp if not exists' then writeFile fp "Hello world.\n" else return () openCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () openCb fc _ = do setTitle fc "Open" res' <- showWidget fc case res' of NativeFileChooserPicked -> do f' <- getFilename fc case f' of (Just f'') -> do setPresetFile fc f'' openFile (T.unpack f'') _ -> return () _ -> return () saveAsCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () saveAsCb fc _ = do setTitle fc "Open" res' <- showWidget fc case res' of NativeFileChooserPicked -> do f' <- getFilename fc case f' of (Just f'') -> do setPresetFile fc f'' saveFile (T.unpack f'') _ -> return () _ -> return () saveCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () saveCb fc w' = do f' <- getFilename fc case f' of Nothing -> saveAsCb fc w' (Just f'') -> saveFile (T.unpack f'') quitCb :: Ref MenuItem -> IO () quitCb _ = exitSuccess initializeWindow :: Ref Window -> IO () initializeWindow w' = do chooser <- nativeFileChooserNew Nothing setFilter chooser "Text\t*.txt\n" setPresetFile chooser "untitiled.txt" begin w' menu <- sysMenuBarNew (toRectangle (0,0,400,25)) Nothing _ <- add menu "&File/&Open" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 'o')))) (Just (openCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Save" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 's')))) (Just (saveCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Save As" Nothing (Just (saveAsCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Quit" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 'q')))) (Just quitCb) (MenuItemFlags []) (Width w_w') <- getW w' (Height w_h') <- getH w' box' <- boxNew (toRectangle (20,25+20,w_w'-40,w_h'-40-25)) Nothing setColor box' whiteColor setBox box' FlatBox setAlign box' (Alignments [AlignTypeCenter, AlignTypeInside, AlignTypeWrap]) setLabel box' $ "This demo shows an example of implementing " `T.append` "common 'File' menu operations like:\n" `T.append` " File/Open, File/Save, File/Save As\n" `T.append` "..using the Fl_Native_File_Chooser widget.\n\n" `T.append` "Note 'Save' and 'Save As' really *does* create files! " `T.append` "This is to show how behavior differs when " `T.append` "files exist vs. do not."; setLabelsize box' (FontSize 12) end w' main :: IO () main = do _ <- FL.setScheme "gtk+" app <- windowNew (toSize (400,200)) Nothing (Just "Native File Chooser Example") initializeWindow app showWidget app _ <- FL.run return ()
null
https://raw.githubusercontent.com/deech/fltkhs-demos/64ed6dfd281d309535ea94d6396c0260395b37d0/src/Examples/nativefilechooser-simple-app.hs
haskell
# LANGUAGE OverloadedStrings #
module Main where import qualified Graphics.UI.FLTK.LowLevel.FL as FL import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Fl_Enumerations import Graphics.UI.FLTK.LowLevel.FLTKHS import System.Directory import System.Exit import qualified Data.Text as T openFile :: FilePath -> IO () openFile fp = print $ "Open '" ++ fp ++ "''" saveFile :: FilePath -> IO () saveFile fp = do print $ "Saving '" ++ fp ++ "'" exists' <- doesFileExist fp if not exists' then writeFile fp "Hello world.\n" else return () openCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () openCb fc _ = do setTitle fc "Open" res' <- showWidget fc case res' of NativeFileChooserPicked -> do f' <- getFilename fc case f' of (Just f'') -> do setPresetFile fc f'' openFile (T.unpack f'') _ -> return () _ -> return () saveAsCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () saveAsCb fc _ = do setTitle fc "Open" res' <- showWidget fc case res' of NativeFileChooserPicked -> do f' <- getFilename fc case f' of (Just f'') -> do setPresetFile fc f'' saveFile (T.unpack f'') _ -> return () _ -> return () saveCb :: Ref NativeFileChooser -> Ref MenuItem -> IO () saveCb fc w' = do f' <- getFilename fc case f' of Nothing -> saveAsCb fc w' (Just f'') -> saveFile (T.unpack f'') quitCb :: Ref MenuItem -> IO () quitCb _ = exitSuccess initializeWindow :: Ref Window -> IO () initializeWindow w' = do chooser <- nativeFileChooserNew Nothing setFilter chooser "Text\t*.txt\n" setPresetFile chooser "untitiled.txt" begin w' menu <- sysMenuBarNew (toRectangle (0,0,400,25)) Nothing _ <- add menu "&File/&Open" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 'o')))) (Just (openCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Save" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 's')))) (Just (saveCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Save As" Nothing (Just (saveAsCb chooser)) (MenuItemFlags []) _ <- add menu "&File/&Quit" (Just (KeySequence (ShortcutKeySequence [kb_CommandState] (NormalKeyType 'q')))) (Just quitCb) (MenuItemFlags []) (Width w_w') <- getW w' (Height w_h') <- getH w' box' <- boxNew (toRectangle (20,25+20,w_w'-40,w_h'-40-25)) Nothing setColor box' whiteColor setBox box' FlatBox setAlign box' (Alignments [AlignTypeCenter, AlignTypeInside, AlignTypeWrap]) setLabel box' $ "This demo shows an example of implementing " `T.append` "common 'File' menu operations like:\n" `T.append` " File/Open, File/Save, File/Save As\n" `T.append` "..using the Fl_Native_File_Chooser widget.\n\n" `T.append` "Note 'Save' and 'Save As' really *does* create files! " `T.append` "This is to show how behavior differs when " `T.append` "files exist vs. do not."; setLabelsize box' (FontSize 12) end w' main :: IO () main = do _ <- FL.setScheme "gtk+" app <- windowNew (toSize (400,200)) Nothing (Just "Native File Chooser Example") initializeWindow app showWidget app _ <- FL.run return ()
158b39a87bfcac65d159bc6129e425cffa0dfca3583d01556a57c7d218a9407f
racket/scribble
manual-utils.rkt
#lang racket/base (require "../struct.rkt" "../base.rkt" (only-in "../core.rkt" content? style?) racket/contract/base racket/list) (provide doc-prefix) (provide/contract [spacer element?] [to-flow (content? . -> . flow?)] [flow-spacer flow?] [flow-spacer/n (-> exact-nonnegative-integer? flow?)] [flow-empty-line flow?] [make-table-if-necessary ((or/c style? string?) list? . -> . (list/c (or/c omitable-paragraph? table?)))] [current-display-width (parameter/c exact-nonnegative-integer?)]) (define spacer (hspace 1)) (define (to-flow e) (make-flow (list (make-omitable-paragraph (list e))))) (define flow-spacer (to-flow spacer)) (define (flow-spacer/n n) (to-flow (hspace n))) (define flow-empty-line (to-flow (tt 'nbsp))) (define (make-table-if-necessary style content) (cond [(= 1 (length content)) (define paras (append-map flow-paragraphs (car content))) (if (andmap paragraph? paras) (list (make-omitable-paragraph (append-map paragraph-content paras))) (list (make-table style content)))] [else (list (make-table style content))])) (define current-display-width (make-parameter 65))
null
https://raw.githubusercontent.com/racket/scribble/d36a983e9d216e04ac1738fa3689c80731937f38/scribble-lib/scribble/private/manual-utils.rkt
racket
#lang racket/base (require "../struct.rkt" "../base.rkt" (only-in "../core.rkt" content? style?) racket/contract/base racket/list) (provide doc-prefix) (provide/contract [spacer element?] [to-flow (content? . -> . flow?)] [flow-spacer flow?] [flow-spacer/n (-> exact-nonnegative-integer? flow?)] [flow-empty-line flow?] [make-table-if-necessary ((or/c style? string?) list? . -> . (list/c (or/c omitable-paragraph? table?)))] [current-display-width (parameter/c exact-nonnegative-integer?)]) (define spacer (hspace 1)) (define (to-flow e) (make-flow (list (make-omitable-paragraph (list e))))) (define flow-spacer (to-flow spacer)) (define (flow-spacer/n n) (to-flow (hspace n))) (define flow-empty-line (to-flow (tt 'nbsp))) (define (make-table-if-necessary style content) (cond [(= 1 (length content)) (define paras (append-map flow-paragraphs (car content))) (if (andmap paragraph? paras) (list (make-omitable-paragraph (append-map paragraph-content paras))) (list (make-table style content)))] [else (list (make-table style content))])) (define current-display-width (make-parameter 65))
4ca7b5587ea893e346e44da2e0e25ac0036dde5b9e401db0f0d55549267155a6
marick/Midje
experimental.clj
(ns midje.experimental (:require [midje.parsing.0-to-fact-form.generative :as parse-generative] [pointer.core :as pointer])) (defmacro for-all "Check facts using values generated using test.check generators, as long as the generators are independent of each other (see gen-let for a more general alternative) Options :seed used to re-run previous checks :max-size controls the size of generated vlues :num-tests how many times to run the checks (for-all \"doc string\" [pos-int gen/s-pos-int neg-int gen/s-neg-int] {:num-tests 500} (fact (+ pos-int neg-int) => #(<= neg-int % pos-int)))" {:arglists '([binding-form & facts] [name doc-string binding-form opts-map & facts])} [& _] (pointer/set-fallback-line-number-from &form) (parse-generative/parse-for-all &form)) (defmacro gen-let "Check facts using values generated using test.check generators, allowing generators to be composed together. gen-let is strictly more powerful than for-all, but exhibits worse performance and test case shrinking behavior, as it desugars to a chan of `bind` expressions. Options :seed used to re-run previous checks :max-size controls the size of generated vlues :num-tests how many times to run the checks (fact \"doc string\" (gen-let [i gen/s-pos-int is (gen/vector gen/int i) e (gen/elements is)] (count is) => i (some #{e} is) => e)) Intermediate computations can be done with the `:let` keyword as in: (gen-let [i (gen/choose 0 9) :let [s (str i) s2 (str s s)] xs (gen/elements [s s2])] (->> xs seq (map #(Character/getNumericValue %)) (some #{i})) => i)" {:arglists '([binding-form & facts] [name doc-string binding-form opts-map & facts])} [& _] (pointer/set-fallback-line-number-from &form) (parse-generative/parse-gen-let &form))
null
https://raw.githubusercontent.com/marick/Midje/2b9bcb117442d3bd2d16446b47540888d683c717/src/midje/experimental.clj
clojure
(ns midje.experimental (:require [midje.parsing.0-to-fact-form.generative :as parse-generative] [pointer.core :as pointer])) (defmacro for-all "Check facts using values generated using test.check generators, as long as the generators are independent of each other (see gen-let for a more general alternative) Options :seed used to re-run previous checks :max-size controls the size of generated vlues :num-tests how many times to run the checks (for-all \"doc string\" [pos-int gen/s-pos-int neg-int gen/s-neg-int] {:num-tests 500} (fact (+ pos-int neg-int) => #(<= neg-int % pos-int)))" {:arglists '([binding-form & facts] [name doc-string binding-form opts-map & facts])} [& _] (pointer/set-fallback-line-number-from &form) (parse-generative/parse-for-all &form)) (defmacro gen-let "Check facts using values generated using test.check generators, allowing generators to be composed together. gen-let is strictly more powerful than for-all, but exhibits worse performance and test case shrinking behavior, as it desugars to a chan of `bind` expressions. Options :seed used to re-run previous checks :max-size controls the size of generated vlues :num-tests how many times to run the checks (fact \"doc string\" (gen-let [i gen/s-pos-int is (gen/vector gen/int i) e (gen/elements is)] (count is) => i (some #{e} is) => e)) Intermediate computations can be done with the `:let` keyword as in: (gen-let [i (gen/choose 0 9) :let [s (str i) s2 (str s s)] xs (gen/elements [s s2])] (->> xs seq (map #(Character/getNumericValue %)) (some #{i})) => i)" {:arglists '([binding-form & facts] [name doc-string binding-form opts-map & facts])} [& _] (pointer/set-fallback-line-number-from &form) (parse-generative/parse-gen-let &form))
dcf79973656b7ef5d3bfa29833f84ee710dab0a4d4d8f0c37d228a386272cd2b
mirage/irmin
irmin_unix.ml
* Copyright ( c ) 2022 Tarides < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2022 Tarides <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Info = Info.Make module I = Info (Irmin.Info.Default) let info = I.v
null
https://raw.githubusercontent.com/mirage/irmin/76d8f910c294029b9a994607f25feaca9bfb8ea0/src/irmin/unix/irmin_unix.ml
ocaml
* Copyright ( c ) 2022 Tarides < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2022 Tarides <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Info = Info.Make module I = Info (Irmin.Info.Default) let info = I.v
09ba1fbcfedd0d35fda209eecbe577b8f50075e948d67c8f27724eda28138701
Liqwid-Labs/liqwid-plutarch-extra
Star.hs
module Plutarch.Extra.Star ( -- * Type PStar (..), -- * Functions papplyStar, ) where import Plutarch.Extra.Applicative (PApplicative (ppure), PApply (pliftA2)) import Plutarch.Extra.Bind (PBind ((#>>=))) import Plutarch.Extra.Category (PCategory (pidentity), PSemigroupoid ((#>>>))) import Plutarch.Extra.Functor (PFunctor (PSubcategory, pfmap), Plut) import Plutarch.Extra.Profunctor (PProfunctor (PCoSubcategory, PContraSubcategory, pdimap)) import Plutarch.Extra.TermCont (pmatchC) | The ( profunctorial ) view over a Kleisli arrow . Its name comes from category theory , as it is one of the ways we can lift a functor ( in this case , ) into a profunctor . This essentially enables us to work with @a : -- > f b@ using ' PSemigroupoid ' and ' PCategory ' operations as easily as we do @a : -- > b@ , provided that @f@ is at least a ' PBind ' . With the addition of a ' PApplicative ' ( for identities ) , we become a full ' PCategory ' . Furthermore , we can also compose freely with ordinary ' : -- > ' at ends of a ' PStar ' , provided @f@ is at least ' PFunctor ' . @since 3.0.1 theory, as it is one of the ways we can lift a functor (in this case, @f@) into a profunctor. This essentially enables us to work with @a :--> f b@ using 'PSemigroupoid' and 'PCategory' operations as easily as we do @a :--> b@, provided that @f@ is at least a 'PBind'. With the addition of a 'PApplicative' (for identities), we become a full 'PCategory'. Furthermore, we can also compose freely with ordinary Plutarch ':-->' at /both/ ends of a 'PStar', provided @f@ is at least 'PFunctor'. @since 3.0.1 -} newtype PStar (f :: (S -> Type) -> S -> Type) (a :: S -> Type) (b :: S -> Type) (s :: S) = PStar (Term s (a :--> f b)) deriving stock | @since 3.0.1 Generic ) deriving anyclass | @since 3.0.1 PlutusType ) | @since 3.0.1 instance DerivePlutusType (PStar f a b) where type DPTStrat _ = PlutusTypeNewtype | If is at least a ' PFunctor ' , we can pre - process and post - process work done in @PStar f@ using pure functions . @since 3.1.0 done in @PStar f@ using pure functions. @since 3.1.0 -} instance (PFunctor f) => PProfunctor (PStar f) where type PContraSubcategory (PStar f) = Plut type PCoSubcategory (PStar f) = PSubcategory f pdimap = phoistAcyclic $ plam $ \into outOf xs -> unTermCont $ do PStar g <- pmatchC xs pure . pcon . PStar $ pdimap # into # (pfmap # outOf) # g | Strengthening @f@ to ' PBind ' allows us to compose @PStar f@ computations like ordinary functions . @since 3.0.1 like ordinary Plutarch functions. @since 3.0.1 -} instance (PBind f) => PSemigroupoid (PStar f) where # INLINEABLE ( # > > > ) # t #>>> t' = pmatch t $ \case PStar ab -> pmatch t' $ \case PStar bc -> pcon . PStar . plam $ \x -> (ab # x) #>>= bc | Strengthening @f@ by adding ' PApplicative ' gives us an identity , which makes us a full category , on par with @Plut@ as evidenced by ' : -- > ' . , @since 3.0.1 makes us a full category, on par with @Plut@ as evidenced by ':-->'. , @since 3.0.1 -} instance (PApplicative f, PBind f) => PCategory (PStar f) where pidentity = pcon . PStar . plam $ \x -> ppure # x | This essentially makes @PStar f a b@ equivalent to the @ReaderT a f b@ : that is , a read - only environment of type @a@ producing a result of type @b@ in an effect @f@. If @f@ is /only/ a ' PFunctor ' , we can only lift , but not compose . @since 3.0.1 b@: that is, a read-only environment of type @a@ producing a result of type @b@ in an effect @f@. If @f@ is /only/ a 'PFunctor', we can only lift, but not compose. @since 3.0.1 -} instance (PFunctor f) => PFunctor (PStar f a) where type PSubcategory (PStar f a) = PSubcategory f pfmap = phoistAcyclic $ plam $ \f xs -> unTermCont $ do PStar g <- pmatchC xs pure . pcon . PStar . plam $ \x -> pfmap # f # (g # x) | Strengthening to ' PApply ' for allows us to combine together computations in @PStar f a@ using the same \'view\ ' as in the ' PFunctor ' instance . @since 3.0.1 computations in @PStar f a@ using the same \'view\' as in the 'PFunctor' instance. @since 3.0.1 -} instance (PApply f) => PApply (PStar f a) where pliftA2 = phoistAcyclic $ plam $ \f xs ys -> unTermCont $ do PStar g <- pmatchC xs PStar h <- pmatchC ys pure . pcon . PStar . plam $ \x -> pliftA2 # f # (g # x) # (h # x) | Strengthening to ' PApplicative ' for @f@ allows arbitrary lifts into @PStar f a@ , using the same \'view\ ' as in the ' PFunctor ' instance . @since 3.0.1 f a@, using the same \'view\' as in the 'PFunctor' instance. @since 3.0.1 -} instance (PApplicative f) => PApplicative (PStar f a) where ppure = phoistAcyclic $ plam $ \x -> pcon . PStar . plam $ \_ -> ppure # x | Strengthening to ' PBind ' for @f@ allows dynamic control flow on the basis of the result of a @PStar f a@ , using the same \'view\ ' as the ' PFunctor ' instance . @since 3.0.1 of the result of a @PStar f a@, using the same \'view\' as the 'PFunctor' instance. @since 3.0.1 -} instance (PBind f) => PBind (PStar f a) where # INLINEABLE ( # > > =) # xs #>>= f = pmatch xs $ \case PStar g -> pcon . PStar . plam $ \x -> (g # x) #>>= (f #>>> (papplyStar # x)) | \'Run\ ' the ' PStar ' as the function it secretly is . Useful for cases where you want to build up a large computation using ' PStar ' instances , then execute . @since 3.0.1 you want to build up a large computation using 'PStar' instances, then execute. @since 3.0.1 -} papplyStar :: forall (a :: S -> Type) (b :: S -> Type) (f :: (S -> Type) -> S -> Type) (s :: S). > PStar f a b : -- > f b ) papplyStar = phoistAcyclic $ plam $ \x f -> pmatch f $ \case PStar f' -> f' # x
null
https://raw.githubusercontent.com/Liqwid-Labs/liqwid-plutarch-extra/e354b559c358c1500854ad3c9f14133b258b7531/src/Plutarch/Extra/Star.hs
haskell
* Type * Functions > f b@ using ' PSemigroupoid ' > b@ , provided that @f@ > ' at ends of a ' PStar ' , provided @f@ is at > f b@ using 'PSemigroupoid' > b@, provided that @f@ >' at /both/ ends of a 'PStar', provided @f@ is at > f b)) > ' . >'. > f b )
module Plutarch.Extra.Star ( PStar (..), papplyStar, ) where import Plutarch.Extra.Applicative (PApplicative (ppure), PApply (pliftA2)) import Plutarch.Extra.Bind (PBind ((#>>=))) import Plutarch.Extra.Category (PCategory (pidentity), PSemigroupoid ((#>>>))) import Plutarch.Extra.Functor (PFunctor (PSubcategory, pfmap), Plut) import Plutarch.Extra.Profunctor (PProfunctor (PCoSubcategory, PContraSubcategory, pdimap)) import Plutarch.Extra.TermCont (pmatchC) | The ( profunctorial ) view over a Kleisli arrow . Its name comes from category theory , as it is one of the ways we can lift a functor ( in this case , ) into a profunctor . is at least a ' PBind ' . With the addition of a ' PApplicative ' ( for identities ) , we become a full ' PCategory ' . Furthermore , we can also compose freely with least ' PFunctor ' . @since 3.0.1 theory, as it is one of the ways we can lift a functor (in this case, @f@) into a profunctor. is at least a 'PBind'. With the addition of a 'PApplicative' (for identities), we become a full 'PCategory'. Furthermore, we can also compose freely with least 'PFunctor'. @since 3.0.1 -} newtype PStar (f :: (S -> Type) -> S -> Type) (a :: S -> Type) (b :: S -> Type) (s :: S) deriving stock | @since 3.0.1 Generic ) deriving anyclass | @since 3.0.1 PlutusType ) | @since 3.0.1 instance DerivePlutusType (PStar f a b) where type DPTStrat _ = PlutusTypeNewtype | If is at least a ' PFunctor ' , we can pre - process and post - process work done in @PStar f@ using pure functions . @since 3.1.0 done in @PStar f@ using pure functions. @since 3.1.0 -} instance (PFunctor f) => PProfunctor (PStar f) where type PContraSubcategory (PStar f) = Plut type PCoSubcategory (PStar f) = PSubcategory f pdimap = phoistAcyclic $ plam $ \into outOf xs -> unTermCont $ do PStar g <- pmatchC xs pure . pcon . PStar $ pdimap # into # (pfmap # outOf) # g | Strengthening @f@ to ' PBind ' allows us to compose @PStar f@ computations like ordinary functions . @since 3.0.1 like ordinary Plutarch functions. @since 3.0.1 -} instance (PBind f) => PSemigroupoid (PStar f) where # INLINEABLE ( # > > > ) # t #>>> t' = pmatch t $ \case PStar ab -> pmatch t' $ \case PStar bc -> pcon . PStar . plam $ \x -> (ab # x) #>>= bc | Strengthening @f@ by adding ' PApplicative ' gives us an identity , which , @since 3.0.1 , @since 3.0.1 -} instance (PApplicative f, PBind f) => PCategory (PStar f) where pidentity = pcon . PStar . plam $ \x -> ppure # x | This essentially makes @PStar f a b@ equivalent to the @ReaderT a f b@ : that is , a read - only environment of type @a@ producing a result of type @b@ in an effect @f@. If @f@ is /only/ a ' PFunctor ' , we can only lift , but not compose . @since 3.0.1 b@: that is, a read-only environment of type @a@ producing a result of type @b@ in an effect @f@. If @f@ is /only/ a 'PFunctor', we can only lift, but not compose. @since 3.0.1 -} instance (PFunctor f) => PFunctor (PStar f a) where type PSubcategory (PStar f a) = PSubcategory f pfmap = phoistAcyclic $ plam $ \f xs -> unTermCont $ do PStar g <- pmatchC xs pure . pcon . PStar . plam $ \x -> pfmap # f # (g # x) | Strengthening to ' PApply ' for allows us to combine together computations in @PStar f a@ using the same \'view\ ' as in the ' PFunctor ' instance . @since 3.0.1 computations in @PStar f a@ using the same \'view\' as in the 'PFunctor' instance. @since 3.0.1 -} instance (PApply f) => PApply (PStar f a) where pliftA2 = phoistAcyclic $ plam $ \f xs ys -> unTermCont $ do PStar g <- pmatchC xs PStar h <- pmatchC ys pure . pcon . PStar . plam $ \x -> pliftA2 # f # (g # x) # (h # x) | Strengthening to ' PApplicative ' for @f@ allows arbitrary lifts into @PStar f a@ , using the same \'view\ ' as in the ' PFunctor ' instance . @since 3.0.1 f a@, using the same \'view\' as in the 'PFunctor' instance. @since 3.0.1 -} instance (PApplicative f) => PApplicative (PStar f a) where ppure = phoistAcyclic $ plam $ \x -> pcon . PStar . plam $ \_ -> ppure # x | Strengthening to ' PBind ' for @f@ allows dynamic control flow on the basis of the result of a @PStar f a@ , using the same \'view\ ' as the ' PFunctor ' instance . @since 3.0.1 of the result of a @PStar f a@, using the same \'view\' as the 'PFunctor' instance. @since 3.0.1 -} instance (PBind f) => PBind (PStar f a) where # INLINEABLE ( # > > =) # xs #>>= f = pmatch xs $ \case PStar g -> pcon . PStar . plam $ \x -> (g # x) #>>= (f #>>> (papplyStar # x)) | \'Run\ ' the ' PStar ' as the function it secretly is . Useful for cases where you want to build up a large computation using ' PStar ' instances , then execute . @since 3.0.1 you want to build up a large computation using 'PStar' instances, then execute. @since 3.0.1 -} papplyStar :: forall (a :: S -> Type) (b :: S -> Type) (f :: (S -> Type) -> S -> Type) (s :: S). papplyStar = phoistAcyclic $ plam $ \x f -> pmatch f $ \case PStar f' -> f' # x
03d51b7b49e4ca5cad06517f956377920687608515b6482f27af9d8cefd76450
rabbitmq/rabbitmq-sharding
rabbit_sharding_policy_validator.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . %% -module(rabbit_sharding_policy_validator). -behaviour(rabbit_policy_validator). -include_lib("rabbit_common/include/rabbit.hrl"). -export([register/0, validate_policy/1]). -rabbit_boot_step({?MODULE, [{description, "sharding parameters"}, {mfa, {?MODULE, register, []}}, {requires, rabbit_registry}, {enables, recovery}]}). register() -> [rabbit_registry:register(Class, Name, ?MODULE) || {Class, Name} <- [{policy_validator, <<"shards-per-node">>}, {policy_validator, <<"routing-key">>}]], ok. validate_policy(KeyList) -> SPN = proplists:get_value(<<"shards-per-node">>, KeyList, none), RKey = proplists:get_value(<<"routing-key">>, KeyList, none), case {SPN, RKey} of {none, none} -> ok; {none, _} -> {error, "shards-per-node must be specified", []}; {SPN, none} -> validate_shards_per_node(SPN); {SPN, RKey} -> case validate_shards_per_node(SPN) of ok -> validate_routing_key(RKey); Else -> Else end end. %%---------------------------------------------------------------------------- validate_shards_per_node(Term) when is_number(Term) -> case Term >= 0 of true -> ok; false -> {error, "shards-per-node should be greater than 0, actually was ~p", [Term]} end; validate_shards_per_node(Term) -> {error, "shards-per-node should be a number, actually was ~p", [Term]}. validate_routing_key(Term) when is_binary(Term) -> ok; validate_routing_key(Term) -> {error, "routing-key should be binary, actually was ~p", [Term]}.
null
https://raw.githubusercontent.com/rabbitmq/rabbitmq-sharding/722f8165f156b03ffa2cb7890999b8c37446d3a6/src/rabbit_sharding_policy_validator.erl
erlang
----------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_sharding_policy_validator). -behaviour(rabbit_policy_validator). -include_lib("rabbit_common/include/rabbit.hrl"). -export([register/0, validate_policy/1]). -rabbit_boot_step({?MODULE, [{description, "sharding parameters"}, {mfa, {?MODULE, register, []}}, {requires, rabbit_registry}, {enables, recovery}]}). register() -> [rabbit_registry:register(Class, Name, ?MODULE) || {Class, Name} <- [{policy_validator, <<"shards-per-node">>}, {policy_validator, <<"routing-key">>}]], ok. validate_policy(KeyList) -> SPN = proplists:get_value(<<"shards-per-node">>, KeyList, none), RKey = proplists:get_value(<<"routing-key">>, KeyList, none), case {SPN, RKey} of {none, none} -> ok; {none, _} -> {error, "shards-per-node must be specified", []}; {SPN, none} -> validate_shards_per_node(SPN); {SPN, RKey} -> case validate_shards_per_node(SPN) of ok -> validate_routing_key(RKey); Else -> Else end end. validate_shards_per_node(Term) when is_number(Term) -> case Term >= 0 of true -> ok; false -> {error, "shards-per-node should be greater than 0, actually was ~p", [Term]} end; validate_shards_per_node(Term) -> {error, "shards-per-node should be a number, actually was ~p", [Term]}. validate_routing_key(Term) when is_binary(Term) -> ok; validate_routing_key(Term) -> {error, "routing-key should be binary, actually was ~p", [Term]}.
c69ac79a3e8dfa0d269a0bd41613afa0a0301ca42fc618d6266ccf5402ef3ba1
m-schmidt/Asm6502
Commandline.hs
-- |Module to parse the command line module Commandline ( OutFormat(..) , Options(..) , commandLineOptions ) where import Control.Monad import Data.Char import Data.List import Error import System.Console.GetOpt import System.FilePath import Text.Read -- |Supported output formats data OutFormat = PRG -- ^ A binary format directly loadable by an emulator | HEX -- ^ A textual hexdump deriving (Eq,Show,Read) -- |Command line options of the assembler data Options = Options { optDumpParsed :: Bool -- ^ Tracing: dump parsed input program ^ output format , optFormatRaw :: String -- ^ Raw output format as specified on command line , optOutput :: FilePath -- ^ The output file , optShowHelp :: Bool -- ^ Show help and terminate program , optShowSymtab :: Bool -- ^ Tracing: print all symbols with their resolved addresses , optShowVersion :: Bool -- ^ Show version information and terminate program } deriving (Eq,Show) -- |Default values for command line options defaultOptions :: Options defaultOptions = Options { optDumpParsed = False , optFormat = PRG , optFormatRaw = "" , optOutput = "" , optShowHelp = False , optShowSymtab = False , optShowVersion = False } |Option descriptions for GetOpt module options :: [OptDescr (Options -> Options)] options = [ Option ['h','?'] ["help"] (NoArg (\opts -> opts { optShowHelp = True })) "Print this help message." , Option ['v'] ["version"] (NoArg (\opts -> opts { optShowVersion = True })) "Print the version information." , Option ['s'] ["symtab"] (NoArg (\opts -> opts { optShowSymtab = True })) "Print the symbol table." , Option ['d'] ["dparse"] (NoArg (\opts -> opts { optDumpParsed = True })) "Print the parsed input program." , Option ['o'] ["output"] (ReqArg (\s opts -> opts { optOutput = s }) "FILE") ("Set output file. Defaults to '<input>.prg' or '<input>.hex'.") , Option ['f'] ["format"] (ReqArg (\s opts -> opts { optFormatRaw = s }) "FORMAT") ("Set output format to 'PRG' or 'HEX'. Defaults to '" ++ show (optFormat defaultOptions) ++ "'.") ] -- |Command line handling commandLineOptions :: [String] -> IO (Options, String) commandLineOptions argv = case getOpt Permute options argv of (o,n,[]) -> do when (optShowHelp o') showHelp when (optShowVersion o') showVersion file <- handleInputFile n opts <- handleOutputFormat o' >>= handleOutputFile file return (opts, file) where o' = foldl (flip id) defaultOptions o (_,_,errs) -> exitWithError $ concat (map ("Error: "++) $ nub errs) ++ usageInfo header options -- |Header message for usage info header :: String header = "Synopsis: asm6502 [options] <input file>" -- |Show help and exit programm showHelp :: IO () showHelp = exitWithInfo (usageInfo header options) -- |Show version info and exit programm showVersion :: IO () showVersion = exitWithInfo "Asm6502 version 1" -- |Check for a single input file handleInputFile :: [String] -> IO String handleInputFile files = do case files of f:[] -> return $ makeValid f _ -> exitWithError "Error: please specify exactly one input file" -- |Check for a valid output format specification handleOutputFormat :: Options -> IO Options handleOutputFormat opts | null format = return opts | otherwise = case readMaybe format of Just f -> return opts { optFormat = f } Nothing -> exitWithError $ "Error: illegal output format '" ++ format ++ "'" where format = map toUpper $ optFormatRaw opts for name of output file , generate one from input file if missing handleOutputFile :: FilePath -> Options -> IO Options handleOutputFile file opts | null output = return opts { optOutput = replaceExtension file $ map toLower $ show $ optFormat opts } | otherwise = return opts where output = optOutput opts
null
https://raw.githubusercontent.com/m-schmidt/Asm6502/bec7b262088b2a125445292ddb9a7cc34859527f/src/Commandline.hs
haskell
|Module to parse the command line |Supported output formats ^ A binary format directly loadable by an emulator ^ A textual hexdump |Command line options of the assembler ^ Tracing: dump parsed input program ^ Raw output format as specified on command line ^ The output file ^ Show help and terminate program ^ Tracing: print all symbols with their resolved addresses ^ Show version information and terminate program |Default values for command line options |Command line handling |Header message for usage info |Show help and exit programm |Show version info and exit programm |Check for a single input file |Check for a valid output format specification
module Commandline ( OutFormat(..) , Options(..) , commandLineOptions ) where import Control.Monad import Data.Char import Data.List import Error import System.Console.GetOpt import System.FilePath import Text.Read data OutFormat deriving (Eq,Show,Read) data Options = Options ^ output format } deriving (Eq,Show) defaultOptions :: Options defaultOptions = Options { optDumpParsed = False , optFormat = PRG , optFormatRaw = "" , optOutput = "" , optShowHelp = False , optShowSymtab = False , optShowVersion = False } |Option descriptions for GetOpt module options :: [OptDescr (Options -> Options)] options = [ Option ['h','?'] ["help"] (NoArg (\opts -> opts { optShowHelp = True })) "Print this help message." , Option ['v'] ["version"] (NoArg (\opts -> opts { optShowVersion = True })) "Print the version information." , Option ['s'] ["symtab"] (NoArg (\opts -> opts { optShowSymtab = True })) "Print the symbol table." , Option ['d'] ["dparse"] (NoArg (\opts -> opts { optDumpParsed = True })) "Print the parsed input program." , Option ['o'] ["output"] (ReqArg (\s opts -> opts { optOutput = s }) "FILE") ("Set output file. Defaults to '<input>.prg' or '<input>.hex'.") , Option ['f'] ["format"] (ReqArg (\s opts -> opts { optFormatRaw = s }) "FORMAT") ("Set output format to 'PRG' or 'HEX'. Defaults to '" ++ show (optFormat defaultOptions) ++ "'.") ] commandLineOptions :: [String] -> IO (Options, String) commandLineOptions argv = case getOpt Permute options argv of (o,n,[]) -> do when (optShowHelp o') showHelp when (optShowVersion o') showVersion file <- handleInputFile n opts <- handleOutputFormat o' >>= handleOutputFile file return (opts, file) where o' = foldl (flip id) defaultOptions o (_,_,errs) -> exitWithError $ concat (map ("Error: "++) $ nub errs) ++ usageInfo header options header :: String header = "Synopsis: asm6502 [options] <input file>" showHelp :: IO () showHelp = exitWithInfo (usageInfo header options) showVersion :: IO () showVersion = exitWithInfo "Asm6502 version 1" handleInputFile :: [String] -> IO String handleInputFile files = do case files of f:[] -> return $ makeValid f _ -> exitWithError "Error: please specify exactly one input file" handleOutputFormat :: Options -> IO Options handleOutputFormat opts | null format = return opts | otherwise = case readMaybe format of Just f -> return opts { optFormat = f } Nothing -> exitWithError $ "Error: illegal output format '" ++ format ++ "'" where format = map toUpper $ optFormatRaw opts for name of output file , generate one from input file if missing handleOutputFile :: FilePath -> Options -> IO Options handleOutputFile file opts | null output = return opts { optOutput = replaceExtension file $ map toLower $ show $ optFormat opts } | otherwise = return opts where output = optOutput opts
812088aa4fd00010ec7a25fd7d065d6c511c74299e89538ce515a917a8e6703d
pveber/biotk
random_dna_sequence.ml
module Dna_sequence = struct let random_base gc = match Float.(Random.float 1. > gc, Random.float 1. > 0.5) with false, false -> 'c' | false, true -> 'g' | true, false -> 'a' | true, true -> 't' let random n gc = String.init n ~f:(fun _ -> random_base gc) let random_base comp = if Array.length comp <> 4 then invalid_arg "random_base: expected array of size 4" ; match Owl.Stats.categorical_rvs comp with | 0 -> 'A' | 1 -> 'C' | 2 -> 'G' | 3 -> 'T' | _ -> assert false let markov0 n comp = String.init n ~f:(fun _ -> random_base comp ) end module Profile_matrix = struct let random ?(alpha = 1.) motif_length = let alpha = Array.init A.card ~f:(fun _ -> Owl.Stats.uniform_rvs ~a:0. ~b:alpha) in Array.init motif_length ~f:(fun _ -> Owl.Stats.dirichlet_rvs ~alpha ) let simulate_sequence eps = String.init (Array.length eps) ~f:(fun i -> Dna_sequence.random_base eps.(i) ) end
null
https://raw.githubusercontent.com/pveber/biotk/9e6fe7fc6fcda7fd91d4d637b66db5961a4a247e/lib/motif_inference/random_dna_sequence.ml
ocaml
module Dna_sequence = struct let random_base gc = match Float.(Random.float 1. > gc, Random.float 1. > 0.5) with false, false -> 'c' | false, true -> 'g' | true, false -> 'a' | true, true -> 't' let random n gc = String.init n ~f:(fun _ -> random_base gc) let random_base comp = if Array.length comp <> 4 then invalid_arg "random_base: expected array of size 4" ; match Owl.Stats.categorical_rvs comp with | 0 -> 'A' | 1 -> 'C' | 2 -> 'G' | 3 -> 'T' | _ -> assert false let markov0 n comp = String.init n ~f:(fun _ -> random_base comp ) end module Profile_matrix = struct let random ?(alpha = 1.) motif_length = let alpha = Array.init A.card ~f:(fun _ -> Owl.Stats.uniform_rvs ~a:0. ~b:alpha) in Array.init motif_length ~f:(fun _ -> Owl.Stats.dirichlet_rvs ~alpha ) let simulate_sequence eps = String.init (Array.length eps) ~f:(fun i -> Dna_sequence.random_base eps.(i) ) end
b7995da2acd6b56c85722169c36d2e499344827e69d8eae73e586d833a27cced
DK318/fp-hw1-tests
T7Spec.hs
module T7Spec where import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Hspec import Test.Tasty import Test.Tasty.Hedgehog import Test.Tasty.Hspec import HW1.T7 (DotString (..), Fun (..), Inclusive (..), ListPlus (..)) instance Eq a => Eq (ListPlus a) where (Last x) == (Last y) = x == y (x :+ xs) == (y :+ ys) | x == y = xs == ys | otherwise = False (==) _ _ = False instance Eq DotString where (DS a) == (DS b) = a == b instance (Eq a, Eq b) => Eq (Inclusive a b) where (This a) == (This b) = a == b (That a) == (That b) = a == b (Both a b) == (Both a' b') = a == a' && b == b' (==) _ _ = False listPlusFromList :: [a] -> ListPlus a listPlusFromList [x] = Last x listPlusFromList (x:xs) = x :+ listPlusFromList xs listPlusFromList _ = undefined genList :: Gen [Int] genList = Gen.list (Range.linear 1 500) Gen.enumBounded prop_listPlus :: Property prop_listPlus = property $ do a <- forAll genList b <- forAll genList c <- forAll genList let aPlus = listPlusFromList a bPlus = listPlusFromList b cPlus = listPlusFromList c (aPlus <> bPlus) <> cPlus === aPlus <> (bPlus <> cPlus) propertyListPlus :: IO TestTree propertyListPlus = return $ testProperty "ListPlus property" prop_listPlus genString :: Gen String genString = Gen.string (Range.linear 1 100) Gen.alphaNum genThis :: Gen (Inclusive String String) genThis = do This <$> genString genThat :: Gen (Inclusive String String) genThat = do That <$> genString genBoth :: Gen (Inclusive String String) genBoth = do str1 <- genString Both str1 <$> genString genInclusive :: Gen (Inclusive String String) genInclusive = Gen.choice [genThis, genThat, genBoth] prop_inclusive :: Property prop_inclusive = property $ do a <- forAll genInclusive b <- forAll genInclusive c <- forAll genInclusive (a <> b) <> c === a <> (b <> c) propertyInclusive :: IO TestTree propertyInclusive = return $ testProperty "Inclusive property" prop_inclusive genDotString :: Gen DotString genDotString = do DS <$> genString spec_DotString :: Spec spec_DotString = do describe "Statement tests" $ do it "Statement test 1" $ DS "person" <> DS "address" <> DS "city" `shouldBe` DS "person.address.city" hspecDotString :: IO TestTree hspecDotString = testSpec "DotString spec" spec_DotString prop_semigroupDotString :: Property prop_semigroupDotString = property $ do a <- forAll genDotString b <- forAll genDotString c <- forAll genDotString (a <> b) <> c === a <> (b <> c) propertySemigroupDotString :: IO TestTree propertySemigroupDotString = return $ testProperty "DotString semigroup" prop_semigroupDotString prop_monoidLeftDotString :: Property prop_monoidLeftDotString = property $ do a <- forAll genDotString mempty <> a === a propertyMonoidLeftDotString :: IO TestTree propertyMonoidLeftDotString = return $ testProperty "DotString left monoid" prop_monoidLeftDotString prop_monoidRightDotString :: Property prop_monoidRightDotString = property $ do a <- forAll genDotString a <> mempty === a propertyMonoidRightDotString :: IO TestTree propertyMonoidRightDotString = return $ testProperty "DotString right monoid" prop_monoidRightDotString add5 :: Fun Int add5 = F $ \a -> a + 5 mul2 :: Fun Int mul2 = F $ \a -> a * 2 div3 :: Fun Int div3 = F $ \a -> a `div` 3 apply :: Fun a -> a -> a apply (F f) = f spec_Fun :: Spec spec_Fun = do describe "Semigroup Fun" $ do it "Test 1" $ apply (mul2 <> add5) 16 `shouldBe` 42 it "Test 2" $ apply (mul2 <> mul2) 10 `shouldBe` 40 it "Test 3" $ apply ((mul2 <> add5) <> div3) 16 `shouldBe` apply (mul2 <> (add5 <> div3)) 16 describe "Monoid Fun" $ do it "Test 1" $ apply (mempty <> add5) 10 `shouldBe` 15 it "Test 2" $ apply (add5 <> mempty) 10 `shouldBe` 15 hspecFun :: IO TestTree hspecFun = testSpec "Fun tests" spec_Fun tests :: IO TestTree tests = do listPlus <- propertyListPlus inclusive <- propertyInclusive dsSpec <- hspecDotString dsSemi <- propertySemigroupDotString dsLeftMonoid <- propertyMonoidLeftDotString dsRightMonoid <- propertyMonoidRightDotString fun <- hspecFun return $ testGroup "HW1.T7" [listPlus, inclusive, dsSpec, dsSemi, dsLeftMonoid, dsRightMonoid, fun]
null
https://raw.githubusercontent.com/DK318/fp-hw1-tests/f6e10e712c98398d1e13913c886ea85cb611780a/test/T7/T7Spec.hs
haskell
module T7Spec where import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Hspec import Test.Tasty import Test.Tasty.Hedgehog import Test.Tasty.Hspec import HW1.T7 (DotString (..), Fun (..), Inclusive (..), ListPlus (..)) instance Eq a => Eq (ListPlus a) where (Last x) == (Last y) = x == y (x :+ xs) == (y :+ ys) | x == y = xs == ys | otherwise = False (==) _ _ = False instance Eq DotString where (DS a) == (DS b) = a == b instance (Eq a, Eq b) => Eq (Inclusive a b) where (This a) == (This b) = a == b (That a) == (That b) = a == b (Both a b) == (Both a' b') = a == a' && b == b' (==) _ _ = False listPlusFromList :: [a] -> ListPlus a listPlusFromList [x] = Last x listPlusFromList (x:xs) = x :+ listPlusFromList xs listPlusFromList _ = undefined genList :: Gen [Int] genList = Gen.list (Range.linear 1 500) Gen.enumBounded prop_listPlus :: Property prop_listPlus = property $ do a <- forAll genList b <- forAll genList c <- forAll genList let aPlus = listPlusFromList a bPlus = listPlusFromList b cPlus = listPlusFromList c (aPlus <> bPlus) <> cPlus === aPlus <> (bPlus <> cPlus) propertyListPlus :: IO TestTree propertyListPlus = return $ testProperty "ListPlus property" prop_listPlus genString :: Gen String genString = Gen.string (Range.linear 1 100) Gen.alphaNum genThis :: Gen (Inclusive String String) genThis = do This <$> genString genThat :: Gen (Inclusive String String) genThat = do That <$> genString genBoth :: Gen (Inclusive String String) genBoth = do str1 <- genString Both str1 <$> genString genInclusive :: Gen (Inclusive String String) genInclusive = Gen.choice [genThis, genThat, genBoth] prop_inclusive :: Property prop_inclusive = property $ do a <- forAll genInclusive b <- forAll genInclusive c <- forAll genInclusive (a <> b) <> c === a <> (b <> c) propertyInclusive :: IO TestTree propertyInclusive = return $ testProperty "Inclusive property" prop_inclusive genDotString :: Gen DotString genDotString = do DS <$> genString spec_DotString :: Spec spec_DotString = do describe "Statement tests" $ do it "Statement test 1" $ DS "person" <> DS "address" <> DS "city" `shouldBe` DS "person.address.city" hspecDotString :: IO TestTree hspecDotString = testSpec "DotString spec" spec_DotString prop_semigroupDotString :: Property prop_semigroupDotString = property $ do a <- forAll genDotString b <- forAll genDotString c <- forAll genDotString (a <> b) <> c === a <> (b <> c) propertySemigroupDotString :: IO TestTree propertySemigroupDotString = return $ testProperty "DotString semigroup" prop_semigroupDotString prop_monoidLeftDotString :: Property prop_monoidLeftDotString = property $ do a <- forAll genDotString mempty <> a === a propertyMonoidLeftDotString :: IO TestTree propertyMonoidLeftDotString = return $ testProperty "DotString left monoid" prop_monoidLeftDotString prop_monoidRightDotString :: Property prop_monoidRightDotString = property $ do a <- forAll genDotString a <> mempty === a propertyMonoidRightDotString :: IO TestTree propertyMonoidRightDotString = return $ testProperty "DotString right monoid" prop_monoidRightDotString add5 :: Fun Int add5 = F $ \a -> a + 5 mul2 :: Fun Int mul2 = F $ \a -> a * 2 div3 :: Fun Int div3 = F $ \a -> a `div` 3 apply :: Fun a -> a -> a apply (F f) = f spec_Fun :: Spec spec_Fun = do describe "Semigroup Fun" $ do it "Test 1" $ apply (mul2 <> add5) 16 `shouldBe` 42 it "Test 2" $ apply (mul2 <> mul2) 10 `shouldBe` 40 it "Test 3" $ apply ((mul2 <> add5) <> div3) 16 `shouldBe` apply (mul2 <> (add5 <> div3)) 16 describe "Monoid Fun" $ do it "Test 1" $ apply (mempty <> add5) 10 `shouldBe` 15 it "Test 2" $ apply (add5 <> mempty) 10 `shouldBe` 15 hspecFun :: IO TestTree hspecFun = testSpec "Fun tests" spec_Fun tests :: IO TestTree tests = do listPlus <- propertyListPlus inclusive <- propertyInclusive dsSpec <- hspecDotString dsSemi <- propertySemigroupDotString dsLeftMonoid <- propertyMonoidLeftDotString dsRightMonoid <- propertyMonoidRightDotString fun <- hspecFun return $ testGroup "HW1.T7" [listPlus, inclusive, dsSpec, dsSemi, dsLeftMonoid, dsRightMonoid, fun]
f96c32125d84d062d4aa1617deb073c1c97ae530cd1b9883c1359f6b3cf63422
ocaml-multicore/multicoretests
stm_tests.ml
open QCheck open STM * parallel STM tests of Ephemeron module Ephemeron . S = sig type key type ' a t val create : int - > ' a t val clear : ' a t - > unit val reset : ' a t - > unit val copy : ' a t - > ' a t val add : ' a t - > key - > ' a - > unit val remove : ' a t - > key - > unit val find : ' a t - > key - > ' a val find_opt : ' a t - > key - > ' a option val find_all : ' a t - > key - > ' a list val replace : ' a t - > key - > ' a - > unit val mem : ' a t - > key - > iter : ( key - > ' a - > unit ) - > ' a t - > unit val filter_map_inplace : ( key - > ' a - > ' a option ) - > ' a t - > unit val fold : ( key - > ' a - > ' b - > ' b ) - > ' a t - > ' b - > ' b val length : ' a t - > int val stats : ' a t - > Hashtbl.statistics val to_seq : ' a t - > ( key * ' a ) Seq.t val to_seq_keys : ' a t - > key Seq.t val to_seq_values : ' a t - > ' a Seq.t val add_seq : ' a t - > ( key * ' a ) Seq.t - > unit val replace_seq : ' a t - > ( key * ' a ) Seq.t - > unit val of_seq : ( key * ' a ) Seq.t - > ' a t val clean : ' a t - > unit remove all dead bindings . Done automatically during automatic resizing . val stats_alive : ' a t - > Hashtbl.statistics same as Hashtbl.SeededS.stats but only count the alive bindings module Ephemeron.S = sig type key type 'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit remove all dead bindings. Done automatically during automatic resizing. val stats_alive : 'a t -> Hashtbl.statistics same as Hashtbl.SeededS.stats but only count the alive bindings *) module EphemeronModel = struct module E = Ephemeron.K1.Make(struct type t = Char.t let equal = Char.equal let hash = Hashtbl.hash end) type sut = string E.t type state = (char * string) list type cmd = | Clear | Add of char * string | Remove of char | Find of char | Find_opt of char | Find_all of char | Replace of char * string | Mem of char | Length | Clean [@@deriving show { with_path = false } ] let init_sut () = E.create 42 let cleanup _ = () let arb_cmd s = let key = if s = [] then Gen.printable else Gen.(oneof [oneofl (List.map fst s); printable]) in let value = Gen.small_string ~gen:Gen.printable in QCheck.make ~print:show_cmd Gen.(frequency [ 1,return Clear; 3,map2 (fun k v -> Add (k, v)) key value; 3,map (fun k -> Remove k) key; 3,map (fun k -> Find k) key; 3,map (fun k -> Find_opt k) key; 3,map (fun k -> Find_all k) key; 3,map2 (fun k v -> Replace (k, v)) key value; 3,map (fun k -> Mem k) key; 3,return Length; 1,return Clean; ]) let next_state c s = match c with | Clear -> [] | Add (k, v) -> (k,v)::s | Remove k -> List.remove_assoc k s | Find _ | Find_opt _ | Find_all _ -> s | Replace (k,v) -> (k,v)::(List.remove_assoc k s) | Mem _ | Length | Clean -> s let run c e = match c with | Clear -> Res (unit, E.clear e) | Add (k, v) -> Res (unit, E.add e k v) | Remove k -> Res (unit, E.remove e k) | Find k -> Res (result string exn, protect (E.find e) k) | Find_opt k -> Res (option string, E.find_opt e k) | Find_all k -> Res (list string, E.find_all e k) | Replace (k,v) -> Res (unit, E.replace e k v) | Mem k -> Res (bool, E.mem e k) | Length -> Res (int, E.length e) | Clean -> Res (unit, E.clean e) let init_state = [] let precond _ _ = true let postcond c (s : state) res = match c,res with | Clear, Res ((Unit,_),_) -> true | Add (_,_), Res ((Unit,_),_) -> true | Remove _, Res ((Unit,_),_) -> true | Find k, Res ((Result (String,Exn),_),r) -> r = Error Not_found || r = protect (List.assoc k) s | Find_opt k, Res ((Option String,_),r) -> r = None || r = List.assoc_opt k s | Find_all k, Res ((List String,_),r) -> let filter = fun (k',v') -> if k' = k then Some v' else None in let vs_state = List.filter_map filter s in (* some entries may have been GC'ed - test only for inclusion *) List.for_all (fun v -> List.mem v vs_state) (List.sort String.compare r) | Replace (_,_), Res ((Unit,_),_) -> true | Mem k, Res ((Bool,_),r) -> r = false || r = List.mem_assoc k s (*effectively: no postcond*) | Length, Res ((Int,_),r) -> r <= List.length s | Clean, Res ((Unit,_),_) -> true | _ -> false end module ETest_seq = STM_sequential.Make(EphemeronModel) module ETest_dom = STM_domain.Make(EphemeronModel) ;; QCheck_base_runner.run_tests_main (let count = 1000 in [ ETest_seq.agree_test ~count ~name:"STM Ephemeron test sequential"; (* succeed *) ETest_dom.neg_agree_test_par ~count ~name:"STM Ephemeron test parallel"; (* fail *) ])
null
https://raw.githubusercontent.com/ocaml-multicore/multicoretests/e409e0e37c814ce42ad43563837a20695a45e5f8/src/ephemeron/stm_tests.ml
ocaml
some entries may have been GC'ed - test only for inclusion effectively: no postcond succeed fail
open QCheck open STM * parallel STM tests of Ephemeron module Ephemeron . S = sig type key type ' a t val create : int - > ' a t val clear : ' a t - > unit val reset : ' a t - > unit val copy : ' a t - > ' a t val add : ' a t - > key - > ' a - > unit val remove : ' a t - > key - > unit val find : ' a t - > key - > ' a val find_opt : ' a t - > key - > ' a option val find_all : ' a t - > key - > ' a list val replace : ' a t - > key - > ' a - > unit val mem : ' a t - > key - > iter : ( key - > ' a - > unit ) - > ' a t - > unit val filter_map_inplace : ( key - > ' a - > ' a option ) - > ' a t - > unit val fold : ( key - > ' a - > ' b - > ' b ) - > ' a t - > ' b - > ' b val length : ' a t - > int val stats : ' a t - > Hashtbl.statistics val to_seq : ' a t - > ( key * ' a ) Seq.t val to_seq_keys : ' a t - > key Seq.t val to_seq_values : ' a t - > ' a Seq.t val add_seq : ' a t - > ( key * ' a ) Seq.t - > unit val replace_seq : ' a t - > ( key * ' a ) Seq.t - > unit val of_seq : ( key * ' a ) Seq.t - > ' a t val clean : ' a t - > unit remove all dead bindings . Done automatically during automatic resizing . val stats_alive : ' a t - > Hashtbl.statistics same as Hashtbl.SeededS.stats but only count the alive bindings module Ephemeron.S = sig type key type 'a t val create : int -> 'a t val clear : 'a t -> unit val reset : 'a t -> unit val copy : 'a t -> 'a t val add : 'a t -> key -> 'a -> unit val remove : 'a t -> key -> unit val find : 'a t -> key -> 'a val find_opt : 'a t -> key -> 'a option val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit val mem : 'a t -> key -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val length : 'a t -> int val stats : 'a t -> Hashtbl.statistics val to_seq : 'a t -> (key * 'a) Seq.t val to_seq_keys : 'a t -> key Seq.t val to_seq_values : 'a t -> 'a Seq.t val add_seq : 'a t -> (key * 'a) Seq.t -> unit val replace_seq : 'a t -> (key * 'a) Seq.t -> unit val of_seq : (key * 'a) Seq.t -> 'a t val clean : 'a t -> unit remove all dead bindings. Done automatically during automatic resizing. val stats_alive : 'a t -> Hashtbl.statistics same as Hashtbl.SeededS.stats but only count the alive bindings *) module EphemeronModel = struct module E = Ephemeron.K1.Make(struct type t = Char.t let equal = Char.equal let hash = Hashtbl.hash end) type sut = string E.t type state = (char * string) list type cmd = | Clear | Add of char * string | Remove of char | Find of char | Find_opt of char | Find_all of char | Replace of char * string | Mem of char | Length | Clean [@@deriving show { with_path = false } ] let init_sut () = E.create 42 let cleanup _ = () let arb_cmd s = let key = if s = [] then Gen.printable else Gen.(oneof [oneofl (List.map fst s); printable]) in let value = Gen.small_string ~gen:Gen.printable in QCheck.make ~print:show_cmd Gen.(frequency [ 1,return Clear; 3,map2 (fun k v -> Add (k, v)) key value; 3,map (fun k -> Remove k) key; 3,map (fun k -> Find k) key; 3,map (fun k -> Find_opt k) key; 3,map (fun k -> Find_all k) key; 3,map2 (fun k v -> Replace (k, v)) key value; 3,map (fun k -> Mem k) key; 3,return Length; 1,return Clean; ]) let next_state c s = match c with | Clear -> [] | Add (k, v) -> (k,v)::s | Remove k -> List.remove_assoc k s | Find _ | Find_opt _ | Find_all _ -> s | Replace (k,v) -> (k,v)::(List.remove_assoc k s) | Mem _ | Length | Clean -> s let run c e = match c with | Clear -> Res (unit, E.clear e) | Add (k, v) -> Res (unit, E.add e k v) | Remove k -> Res (unit, E.remove e k) | Find k -> Res (result string exn, protect (E.find e) k) | Find_opt k -> Res (option string, E.find_opt e k) | Find_all k -> Res (list string, E.find_all e k) | Replace (k,v) -> Res (unit, E.replace e k v) | Mem k -> Res (bool, E.mem e k) | Length -> Res (int, E.length e) | Clean -> Res (unit, E.clean e) let init_state = [] let precond _ _ = true let postcond c (s : state) res = match c,res with | Clear, Res ((Unit,_),_) -> true | Add (_,_), Res ((Unit,_),_) -> true | Remove _, Res ((Unit,_),_) -> true | Find k, Res ((Result (String,Exn),_),r) -> r = Error Not_found || r = protect (List.assoc k) s | Find_opt k, Res ((Option String,_),r) -> r = None || r = List.assoc_opt k s | Find_all k, Res ((List String,_),r) -> let filter = fun (k',v') -> if k' = k then Some v' else None in let vs_state = List.filter_map filter s in List.for_all (fun v -> List.mem v vs_state) (List.sort String.compare r) | Replace (_,_), Res ((Unit,_),_) -> true | Length, Res ((Int,_),r) -> r <= List.length s | Clean, Res ((Unit,_),_) -> true | _ -> false end module ETest_seq = STM_sequential.Make(EphemeronModel) module ETest_dom = STM_domain.Make(EphemeronModel) ;; QCheck_base_runner.run_tests_main (let count = 1000 in ])
79bd403d4f01bbb620c43190e4d2440b6fe5b422ac0289907f3cdb3e26b684b0
locusmath/locus
object.clj
(ns locus.graph.core.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.limit.product :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.sequence.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.quiver.relation.binary.product :refer :all] [locus.set.quiver.relation.binary.br :refer :all] [locus.set.quiver.relation.binary.sr :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.quiver.binary.thin.object :refer :all])) ; Graphs: ; Let F be a presheaf, then F is naturally associated to a lattice of presheaves of graphs that have F as their underlying presheaf which we can call ) . This generalises the idea ; of a graph on a set to a graph on a presheaf. In the case of a set this returns an ordinary ; graph, in the case of a function this produces a graph homomorphism, and in general this ; produces a homomorphism of graphs. In accordance with presheaf theoretic foundations, everything ; is interpreted in terms of presheaves instead of sets. ; In presheaf topos theory, graphs can be understood by permutable quivers which are quivers ; with a single symmetric operation on their morphism set. Then graphs are simply the subcategory ; of the topos of permutable quivers consisting of thin permutable quivers. We distinguish between ; graphs and quivers so that we consider presheaves of graphs, while quivers are just certain ; presheaves of sets that can recover the data of graphs. (deftype SetGraph [vertices edges] ConcreteObject (underlying-set [this] vertices)) (derive SetGraph :locus.elementary.function.core.protocols/structured-set) ; Properties of graphs (defn graph-edges [^SetGraph graph] (.-edges graph)) (defn nonloop-graph-edges [^SetGraph graph] (set (filter (fn [edge] (not= (count edge) 1)) (graph-edges graph)))) (defn loop-graph-edges [^SetGraph graph] (set (filter (fn [edge] (= (count edge) 1)) (graph-edges graph)))) ; Irreflexive interior and reflexive closure for graphs (defn irreflexive-component-graph [graph] (->SetGraph (underlying-set graph) (nonloop-graph-edges graph))) (defn reflexive-closure-graph [graph] (let [coll (underlying-set graph)] (->SetGraph coll (union (set (map (fn [i] #{i}) coll)))))) ; Underlying relations, multirelations, and visualisations of graphs (defmethod underlying-relation SetGraph [^SetGraph graph] (apply union (map (fn [pair] (if (= (count pair) 1) (let [[a] (seq pair)] #{(list a a)}) (let [[a b] (seq pair)] #{(list a b) (list b a)}))) (graph-edges graph)))) (defmethod underlying-multirelation SetGraph [^SetGraph graph] (multiset (underlying-relation graph))) (defmethod visualize SetGraph [^SetGraph graph] (visualize (graph-edges graph))) ; Map graphs into the topos of quivers (defmethod to-quiver SetGraph [^SetGraph graph] (->ThinQuiver (underlying-set graph) (underlying-relation graph))) ; Conversion routines for undirected graphs (defmulti to-graph type) (defmethod to-graph SetGraph [^SetGraph graph] graph) (defmethod to-graph :locus.set.logic.core.set/universal [family] (->SetGraph (apply union family) family)) ; Graph order and size metrics (defn graph-order [graph] (count (underlying-set graph))) (defn graph-size [graph] (count (graph-edges graph))) ; Implementation of complementation for the different types of graph (defn complement-graph [graph] (SetGraph. (underlying-set graph) (difference (multiselection (underlying-set graph) #{1 2}) (graph-edges graph)))) (defn complement-simple-graph [graph] (SetGraph. (underlying-set graph) (difference (selections (underlying-set graph) 2) (graph-edges graph)))) ; Get the neighbours of an element of an undirected graph (defn containing-edges [graph x] (set (filter (fn [edge] (contains? edge x)) (graph-edges graph)))) (defn undirected-neighbours [graph x] (conj (apply union (filter (fn [edge] (contains? edge x)) (graph-edges graph))) x)) Construct a graph from a set system (defn graph ([family] (graph (apply union family) family)) ([coll family] (->SetGraph coll family))) (defn empty-graph [coll] (->SetGraph coll #{})) (defn complete-graph [coll] (->SetGraph coll (multiselection coll #{1 2}))) (defn complete-simple-graph [coll] (->SetGraph coll (selections coll 2))) (defn cycle-graph [coll] (cond (<= (count coll) 1) (empty-graph coll) (= (count coll) 2) (SetGraph. (set coll) #{(set coll)}) :else (->SetGraph (set coll) (set (map (fn [i] (if (= i (dec (count coll))) #{(nth coll i) (nth coll 0)} #{(nth coll i) (nth coll (inc i))})) (range (count coll))))))) (defn path-graph [coll] (->SetGraph (set coll) (map (fn [i] #{i (inc i)}) (if (empty? coll) '() (range (dec (count coll))))))) (defn star-graph [coll elem] (->SetGraph (conj coll elem) (set (map (fn [i] #{i elem}) coll)))) (defn line-graph [graph] (SetGraph. (graph-edges graph) (set (for [[a b] (cartesian-power (graph-edges graph) 2) :when (not (empty? (intersection a b)))] #{a b})))) (defn johnson-graph [coll k] (let [elems (selections coll k)] (SetGraph. elems (set (filter (fn [pair] (= (count (apply intersection pair)) (dec k))) (selections elems 2)))))) (defn kneser-graph [coll k] (let [elems (selections coll k)] (SetGraph. elems (set (filter (fn [pair] (empty? (apply intersection pair))) (selections elems 2)))))) ; The category of graphs is defined by a fundamental adjunction that is produced for each function ; which is defined by graph images and inverse images. (defmethod image [:locus.set.logic.structure.protocols/set-function SetGraph] [func graph] (->SetGraph (outputs func) (set (map (fn [edge] (set (map func edge))) (graph-edges graph))))) (defmethod inverse-image [:locus.set.logic.structure.protocols/set-function SetGraph] [func graph] (let [in (inputs func) edges (graph-edges graph)] (->SetGraph in (set (filter (fn [edge] (let [produced-edge (set (map func edge))] (contains? edges produced-edge))) (multiselection in #{1 2})))))) ; Create a restricted version of an undirected graph (defn restrict-graph [graph new-vertex-set] (->SetGraph new-vertex-set (set (filter (fn [edge] (superset? (list edge new-vertex-set))) (graph-edges graph))))) ; Ontology of graphs (defn graph? [obj] (= (type obj) SetGraph)) (defn simple-graph? [obj] (and (graph? obj) (empty? (loop-graph-edges graph)))) (defn empty-graph? [obj] (and (graph? obj) (empty? (graph-edges obj))))
null
https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/graph/core/object.clj
clojure
Graphs: Let F be a presheaf, then F is naturally associated to a lattice of presheaves of graphs that of a graph on a set to a graph on a presheaf. In the case of a set this returns an ordinary graph, in the case of a function this produces a graph homomorphism, and in general this produces a homomorphism of graphs. In accordance with presheaf theoretic foundations, everything is interpreted in terms of presheaves instead of sets. In presheaf topos theory, graphs can be understood by permutable quivers which are quivers with a single symmetric operation on their morphism set. Then graphs are simply the subcategory of the topos of permutable quivers consisting of thin permutable quivers. We distinguish between graphs and quivers so that we consider presheaves of graphs, while quivers are just certain presheaves of sets that can recover the data of graphs. Properties of graphs Irreflexive interior and reflexive closure for graphs Underlying relations, multirelations, and visualisations of graphs Map graphs into the topos of quivers Conversion routines for undirected graphs Graph order and size metrics Implementation of complementation for the different types of graph Get the neighbours of an element of an undirected graph The category of graphs is defined by a fundamental adjunction that is produced for each function which is defined by graph images and inverse images. Create a restricted version of an undirected graph Ontology of graphs
(ns locus.graph.core.object (:require [locus.set.logic.core.set :refer :all] [locus.set.logic.limit.product :refer :all] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.sequence.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.quiver.relation.binary.product :refer :all] [locus.set.quiver.relation.binary.br :refer :all] [locus.set.quiver.relation.binary.sr :refer :all] [locus.set.quiver.binary.core.object :refer :all] [locus.set.quiver.binary.thin.object :refer :all])) have F as their underlying presheaf which we can call ) . This generalises the idea (deftype SetGraph [vertices edges] ConcreteObject (underlying-set [this] vertices)) (derive SetGraph :locus.elementary.function.core.protocols/structured-set) (defn graph-edges [^SetGraph graph] (.-edges graph)) (defn nonloop-graph-edges [^SetGraph graph] (set (filter (fn [edge] (not= (count edge) 1)) (graph-edges graph)))) (defn loop-graph-edges [^SetGraph graph] (set (filter (fn [edge] (= (count edge) 1)) (graph-edges graph)))) (defn irreflexive-component-graph [graph] (->SetGraph (underlying-set graph) (nonloop-graph-edges graph))) (defn reflexive-closure-graph [graph] (let [coll (underlying-set graph)] (->SetGraph coll (union (set (map (fn [i] #{i}) coll)))))) (defmethod underlying-relation SetGraph [^SetGraph graph] (apply union (map (fn [pair] (if (= (count pair) 1) (let [[a] (seq pair)] #{(list a a)}) (let [[a b] (seq pair)] #{(list a b) (list b a)}))) (graph-edges graph)))) (defmethod underlying-multirelation SetGraph [^SetGraph graph] (multiset (underlying-relation graph))) (defmethod visualize SetGraph [^SetGraph graph] (visualize (graph-edges graph))) (defmethod to-quiver SetGraph [^SetGraph graph] (->ThinQuiver (underlying-set graph) (underlying-relation graph))) (defmulti to-graph type) (defmethod to-graph SetGraph [^SetGraph graph] graph) (defmethod to-graph :locus.set.logic.core.set/universal [family] (->SetGraph (apply union family) family)) (defn graph-order [graph] (count (underlying-set graph))) (defn graph-size [graph] (count (graph-edges graph))) (defn complement-graph [graph] (SetGraph. (underlying-set graph) (difference (multiselection (underlying-set graph) #{1 2}) (graph-edges graph)))) (defn complement-simple-graph [graph] (SetGraph. (underlying-set graph) (difference (selections (underlying-set graph) 2) (graph-edges graph)))) (defn containing-edges [graph x] (set (filter (fn [edge] (contains? edge x)) (graph-edges graph)))) (defn undirected-neighbours [graph x] (conj (apply union (filter (fn [edge] (contains? edge x)) (graph-edges graph))) x)) Construct a graph from a set system (defn graph ([family] (graph (apply union family) family)) ([coll family] (->SetGraph coll family))) (defn empty-graph [coll] (->SetGraph coll #{})) (defn complete-graph [coll] (->SetGraph coll (multiselection coll #{1 2}))) (defn complete-simple-graph [coll] (->SetGraph coll (selections coll 2))) (defn cycle-graph [coll] (cond (<= (count coll) 1) (empty-graph coll) (= (count coll) 2) (SetGraph. (set coll) #{(set coll)}) :else (->SetGraph (set coll) (set (map (fn [i] (if (= i (dec (count coll))) #{(nth coll i) (nth coll 0)} #{(nth coll i) (nth coll (inc i))})) (range (count coll))))))) (defn path-graph [coll] (->SetGraph (set coll) (map (fn [i] #{i (inc i)}) (if (empty? coll) '() (range (dec (count coll))))))) (defn star-graph [coll elem] (->SetGraph (conj coll elem) (set (map (fn [i] #{i elem}) coll)))) (defn line-graph [graph] (SetGraph. (graph-edges graph) (set (for [[a b] (cartesian-power (graph-edges graph) 2) :when (not (empty? (intersection a b)))] #{a b})))) (defn johnson-graph [coll k] (let [elems (selections coll k)] (SetGraph. elems (set (filter (fn [pair] (= (count (apply intersection pair)) (dec k))) (selections elems 2)))))) (defn kneser-graph [coll k] (let [elems (selections coll k)] (SetGraph. elems (set (filter (fn [pair] (empty? (apply intersection pair))) (selections elems 2)))))) (defmethod image [:locus.set.logic.structure.protocols/set-function SetGraph] [func graph] (->SetGraph (outputs func) (set (map (fn [edge] (set (map func edge))) (graph-edges graph))))) (defmethod inverse-image [:locus.set.logic.structure.protocols/set-function SetGraph] [func graph] (let [in (inputs func) edges (graph-edges graph)] (->SetGraph in (set (filter (fn [edge] (let [produced-edge (set (map func edge))] (contains? edges produced-edge))) (multiselection in #{1 2})))))) (defn restrict-graph [graph new-vertex-set] (->SetGraph new-vertex-set (set (filter (fn [edge] (superset? (list edge new-vertex-set))) (graph-edges graph))))) (defn graph? [obj] (= (type obj) SetGraph)) (defn simple-graph? [obj] (and (graph? obj) (empty? (loop-graph-edges graph)))) (defn empty-graph? [obj] (and (graph? obj) (empty? (graph-edges obj))))
2c146f27925f0f7d8bba9d48bb006d265c0ec006d8f7947f177186da2119cd78
evincarofautumn/kitten
Regeneralize.hs
| Module : Kitten . Regeneralize Description : Stack - generalization of types Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.Regeneralize Description : Stack-generalization of types Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} {-# LANGUAGE OverloadedStrings #-} module Kitten.Regeneralize ( regeneralize ) where import Control.Monad (when) import Control.Monad.Trans.Writer (Writer, runWriter, tell) import Data.Function (on) import Data.List (deleteBy) import Kitten.Kind (Kind) import Kitten.Name (Unqualified) import Kitten.Occurrences (occurrences) import Kitten.Type (Type(..), TypeId, Var(..)) import Kitten.TypeEnv (TypeEnv) import qualified Data.Map as Map import qualified Kitten.Free as Free import qualified Kitten.Type as Type -- | Because all functions are polymorphic with respect to the part of the stack -- they don't touch, all words of order n can be regeneralized to words of rank -- n with respect to the stack-kinded type variables. -- -- This means that if a stack-kinded (ρ) type variable occurs only twice in a -- type, in the bottommost position on both sides of a function arrow, then its -- scope can be reduced to only that function arrow by introducing a -- higher-ranked quantifier. This is a more conservative rule than used in -- \"Simple type inference for higher-order stack languages\". For example, the -- type of @map@: -- > map : : . ρ × List α × ( σ × α → σ × β ) → ρ × List β -- -- Can be regeneralized like so: -- > map : : ∀ραβ . ρ × List α × ( ∀σ . σ × α → σ × β ) → ρ × List β -- -- In order to correctly regeneralize a type, it needs to contain no -- higher-ranked quantifiers. regeneralize :: TypeEnv -> Type -> Type regeneralize tenv t = let (t', vars) = runWriter $ go t in foldr addForall t' $ foldr (deleteBy ((==) `on` fst)) (Map.toList (Free.tvks tenv t')) vars where addForall :: (TypeId, (Unqualified, Kind)) -> Type -> Type addForall (i, (name, k)) = Forall (Type.origin t) (Var name i k) go :: Type -> Writer [(TypeId, (Unqualified, Kind))] Type go t' = case t' of TypeConstructor _ "Fun" :@ a :@ b :@ e | TypeVar origin (Var name c k) <- bottommost a , TypeVar _ (Var _name d _) <- bottommost b , c == d -> do when (occurrences tenv c t == 2) $ tell [(c, (name, k))] a' <- go a b' <- go b e' <- go e return $ Forall origin (Var name c k) $ Type.fun origin a' b' e' c@(TypeConstructor _ "Prod") :@ a :@ b -> do a' <- go a b' <- go b return $ c :@ a' :@ b' -- FIXME: This should descend into the quantified type. Forall{} -> return t' a :@ b -> (:@) <$> go a <*> go b _ -> return t' bottommost :: Type -> Type bottommost (TypeConstructor _ "Prod" :@ a :@ _) = bottommost a bottommost a = a
null
https://raw.githubusercontent.com/evincarofautumn/kitten/a5301fe24dbb9ea91974abee73ad544156ee4722/lib/Kitten/Regeneralize.hs
haskell
# LANGUAGE OverloadedStrings # | Because all functions are polymorphic with respect to the part of the stack they don't touch, all words of order n can be regeneralized to words of rank n with respect to the stack-kinded type variables. This means that if a stack-kinded (ρ) type variable occurs only twice in a type, in the bottommost position on both sides of a function arrow, then its scope can be reduced to only that function arrow by introducing a higher-ranked quantifier. This is a more conservative rule than used in \"Simple type inference for higher-order stack languages\". For example, the type of @map@: Can be regeneralized like so: In order to correctly regeneralize a type, it needs to contain no higher-ranked quantifiers. FIXME: This should descend into the quantified type.
| Module : Kitten . Regeneralize Description : Stack - generalization of types Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.Regeneralize Description : Stack-generalization of types Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} module Kitten.Regeneralize ( regeneralize ) where import Control.Monad (when) import Control.Monad.Trans.Writer (Writer, runWriter, tell) import Data.Function (on) import Data.List (deleteBy) import Kitten.Kind (Kind) import Kitten.Name (Unqualified) import Kitten.Occurrences (occurrences) import Kitten.Type (Type(..), TypeId, Var(..)) import Kitten.TypeEnv (TypeEnv) import qualified Data.Map as Map import qualified Kitten.Free as Free import qualified Kitten.Type as Type > map : : . ρ × List α × ( σ × α → σ × β ) → ρ × List β > map : : ∀ραβ . ρ × List α × ( ∀σ . σ × α → σ × β ) → ρ × List β regeneralize :: TypeEnv -> Type -> Type regeneralize tenv t = let (t', vars) = runWriter $ go t in foldr addForall t' $ foldr (deleteBy ((==) `on` fst)) (Map.toList (Free.tvks tenv t')) vars where addForall :: (TypeId, (Unqualified, Kind)) -> Type -> Type addForall (i, (name, k)) = Forall (Type.origin t) (Var name i k) go :: Type -> Writer [(TypeId, (Unqualified, Kind))] Type go t' = case t' of TypeConstructor _ "Fun" :@ a :@ b :@ e | TypeVar origin (Var name c k) <- bottommost a , TypeVar _ (Var _name d _) <- bottommost b , c == d -> do when (occurrences tenv c t == 2) $ tell [(c, (name, k))] a' <- go a b' <- go b e' <- go e return $ Forall origin (Var name c k) $ Type.fun origin a' b' e' c@(TypeConstructor _ "Prod") :@ a :@ b -> do a' <- go a b' <- go b return $ c :@ a' :@ b' Forall{} -> return t' a :@ b -> (:@) <$> go a <*> go b _ -> return t' bottommost :: Type -> Type bottommost (TypeConstructor _ "Prod" :@ a :@ _) = bottommost a bottommost a = a
379a8bfbfca777e7c60ee231e20a62ce05687ef9b64c4a34e9a484da78ed494b
flyspeck/flyspeck
realax.ml
(* ========================================================================= *) (* Theory of real numbers. *) (* *) , University of Cambridge Computer Laboratory (* *) ( c ) Copyright , University of Cambridge 1998 ( c ) Copyright , 1998 - 2007 (* ========================================================================= *) open Parser include Lists (* ------------------------------------------------------------------------- *) (* The main infix overloaded operations *) (* ------------------------------------------------------------------------- *) parse_as_infix("++",(16,"right"));; parse_as_infix("**",(20,"right"));; parse_as_infix("<<=",(12,"right"));; parse_as_infix("===",(10,"right"));; parse_as_infix ("treal_mul",(20,"right"));; parse_as_infix ("treal_add",(16,"right"));; parse_as_infix ("treal_le",(12,"right"));; parse_as_infix ("treal_eq",(10,"right"));; make_overloadable "+" `:A->A->A`;; make_overloadable "-" `:A->A->A`;; make_overloadable "*" `:A->A->A`;; make_overloadable "/" `:A->A->A`;; make_overloadable "<" `:A->A->bool`;; make_overloadable "<=" `:A->A->bool`;; make_overloadable ">" `:A->A->bool`;; make_overloadable ">=" `:A->A->bool`;; make_overloadable "--" `:A->A`;; make_overloadable "pow" `:A->num->A`;; make_overloadable "inv" `:A->A`;; make_overloadable "abs" `:A->A`;; make_overloadable "max" `:A->A->A`;; make_overloadable "min" `:A->A->A`;; make_overloadable "&" `:num->A`;; do_list overload_interface ["+",`(+):num->num->num`; "-",`(-):num->num->num`; "*",`(*):num->num->num`; "<",`(<):num->num->bool`; "<=",`(<=):num->num->bool`; ">",`(>):num->num->bool`; ">=",`(>=):num->num->bool`];; let prioritize_num() = prioritize_overload(mk_type("num",[]));; (* ------------------------------------------------------------------------- *) (* Absolute distance function on the naturals. *) (* ------------------------------------------------------------------------- *) let dist = new_definition `dist(m,n) = (m - n) + (n - m)`;; (* ------------------------------------------------------------------------- *) (* Some easy theorems. *) (* ------------------------------------------------------------------------- *) let DIST_REFL = prove (`!n. dist(n,n) = 0`, REWRITE_TAC[dist; SUB_REFL; ADD_CLAUSES]);; let DIST_LZERO = prove (`!n. dist(0,n) = n`, REWRITE_TAC[dist; SUB_0; ADD_CLAUSES]);; let DIST_RZERO = prove (`!n. dist(n,0) = n`, REWRITE_TAC[dist; SUB_0; ADD_CLAUSES]);; let DIST_SYM = prove (`!m n. dist(m,n) = dist(n,m)`, REWRITE_TAC[dist] THEN MATCH_ACCEPT_TAC ADD_SYM);; let DIST_LADD = prove (`!m p n. dist(m + n,m + p) = dist(n,p)`, REWRITE_TAC[dist; SUB_ADD_LCANCEL]);; let DIST_RADD = prove (`!m p n. dist(m + p,n + p) = dist(m,n)`, REWRITE_TAC[dist; SUB_ADD_RCANCEL]);; let DIST_LADD_0 = prove (`!m n. dist(m + n,m) = n`, REWRITE_TAC[dist; ADD_SUB2; ADD_SUBR2; ADD_CLAUSES]);; let DIST_RADD_0 = prove (`!m n. dist(m,m + n) = n`, ONCE_REWRITE_TAC[DIST_SYM] THEN MATCH_ACCEPT_TAC DIST_LADD_0);; let DIST_LMUL = prove (`!m n p. m * dist(n,p) = dist(m * n,m * p)`, REWRITE_TAC[dist; LEFT_ADD_DISTRIB; LEFT_SUB_DISTRIB]);; let DIST_RMUL = prove (`!m n p. dist(m,n) * p = dist(m * p,n * p)`, REWRITE_TAC[dist; RIGHT_ADD_DISTRIB; RIGHT_SUB_DISTRIB]);; let DIST_EQ_0 = prove (`!m n. (dist(m,n) = 0) <=> (m = n)`, REWRITE_TAC[dist; ADD_EQ_0; SUB_EQ_0; LE_ANTISYM]);; (* ------------------------------------------------------------------------- *) (* Simplifying theorem about the distance operation. *) (* ------------------------------------------------------------------------- *) let DIST_ELIM_THM = prove (`P(dist(x,y)) <=> !d. ((x = y + d) ==> P(d)) /\ ((y = x + d) ==> P(d))`, DISJ_CASES_TAC(SPECL [`x:num`; `y:num`] LE_CASES) THEN POP_ASSUM(X_CHOOSE_THEN `e:num` SUBST1_TAC o REWRITE_RULE[LE_EXISTS]) THEN REWRITE_TAC[dist; ADD_SUB; ADD_SUB2; ADD_SUBR; ADD_SUBR2] THEN REWRITE_TAC[ADD_CLAUSES; EQ_ADD_LCANCEL] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [EQ_SYM_EQ] THEN REWRITE_TAC[GSYM ADD_ASSOC; EQ_ADD_LCANCEL_0; ADD_EQ_0] THEN ASM_CASES_TAC `e = 0` THEN ASM_REWRITE_TAC[] THEN EQ_TAC THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) (* Now some more theorems. *) (* ------------------------------------------------------------------------- *) let DIST_LE_CASES,DIST_ADDBOUND,DIST_TRIANGLE,DIST_ADD2,DIST_ADD2_REV = let DIST_ELIM_TAC = let conv = HIGHER_REWRITE_CONV[SUB_ELIM_THM; COND_ELIM_THM; DIST_ELIM_THM] false in CONV_TAC conv THEN TRY GEN_TAC THEN CONJ_TAC THEN DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN (let l,r = dest_eq (concl th) in if is_var l & not (vfree_in l r) then ALL_TAC else ASSUME_TAC th)) in let DIST_ELIM_TAC' = REPEAT STRIP_TAC THEN REPEAT DIST_ELIM_TAC THEN REWRITE_TAC[GSYM NOT_LT; LT_EXISTS] THEN DISCH_THEN(CHOOSE_THEN SUBST_ALL_TAC) THEN POP_ASSUM MP_TAC THEN CONV_TAC(LAND_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[ADD_CLAUSES; NOT_SUC] in let DIST_LE_CASES = prove (`!m n p. dist(m,n) <= p <=> (m <= n + p) /\ (n <= m + p)`, REPEAT GEN_TAC THEN REPEAT DIST_ELIM_TAC THEN REWRITE_TAC[GSYM ADD_ASSOC; LE_ADD; LE_ADD_LCANCEL]) and DIST_ADDBOUND = prove (`!m n. dist(m,n) <= m + n`, REPEAT GEN_TAC THEN DIST_ELIM_TAC THENL [ONCE_REWRITE_TAC[ADD_SYM]; ALL_TAC] THEN REWRITE_TAC[ADD_ASSOC; LE_ADDR]) and [DIST_TRIANGLE; DIST_ADD2; DIST_ADD2_REV] = (CONJUNCTS o prove) (`(!m n p. dist(m,p) <= dist(m,n) + dist(n,p)) /\ (!m n p q. dist(m + n,p + q) <= dist(m,p) + dist(n,q)) /\ (!m n p q. dist(m,p) <= dist(m + n,p + q) + dist(n,q))`, DIST_ELIM_TAC') in DIST_LE_CASES,DIST_ADDBOUND,DIST_TRIANGLE,DIST_ADD2,DIST_ADD2_REV;; let DIST_TRIANGLE_LE = prove (`!m n p q. dist(m,n) + dist(n,p) <= q ==> dist(m,p) <= q`, REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `dist(m,n) + dist(n,p)` THEN ASM_REWRITE_TAC[DIST_TRIANGLE]);; let DIST_TRIANGLES_LE = prove (`!m n p q r s. dist(m,n) <= r /\ dist(p,q) <= s ==> dist(m,p) <= dist(n,q) + r + s`, REPEAT STRIP_TAC THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `n:num` THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN REWRITE_TAC[GSYM ADD_ASSOC] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `q:num` THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN REWRITE_TAC[LE_ADD_LCANCEL] THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) (* Useful lemmas about bounds. *) (* ------------------------------------------------------------------------- *) let BOUNDS_LINEAR = prove (`!A B C. (!n. A * n <= B * n + C) <=> A <= B`, REPEAT GEN_TAC THEN EQ_TAC THENL [CONV_TAC CONTRAPOS_CONV THEN REWRITE_TAC[NOT_LE] THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LT_EXISTS]) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN DISCH_THEN(MP_TAC o SPEC `SUC C`) THEN REWRITE_TAC[NOT_LE; MULT_CLAUSES; ADD_CLAUSES; LT_SUC_LE] THEN REWRITE_TAC[ADD_ASSOC; LE_ADDR]; DISCH_THEN(CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LE_EXISTS]) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]);; let BOUNDS_LINEAR_0 = prove (`!A B. (!n. A * n <= B) <=> (A = 0)`, REPEAT GEN_TAC THEN MP_TAC(SPECL [`A:num`; `0`; `B:num`] BOUNDS_LINEAR) THEN REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LE]);; let BOUNDS_DIVIDED = prove (`!P. (?B. !n. P(n) <= B) <=> (?A B. !n. n * P(n) <= A * n + B)`, GEN_TAC THEN EQ_TAC THEN STRIP_TAC THENL [MAP_EVERY EXISTS_TAC [`B:num`; `0`] THEN GEN_TAC THEN REWRITE_TAC[ADD_CLAUSES] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; EXISTS_TAC `P(0) + A + B` THEN GEN_TAC THEN MP_TAC(SPECL [`n:num`; `(P:num->num) n`; `P(0) + A + B`] LE_MULT_LCANCEL) THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[LE_ADD] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [MULT_SYM] THEN REWRITE_TAC[GSYM ADD_ASSOC; LE_ADD_LCANCEL] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B * n` THEN REWRITE_TAC[LE_ADD] THEN UNDISCH_TAC `~(n = 0)` THEN SPEC_TAC(`n:num`,`n:num`) THEN INDUCT_TAC THEN ASM_REWRITE_TAC[MULT_CLAUSES; LE_ADD]]);; let BOUNDS_NOTZERO = prove (`!P A B. (P 0 0 = 0) /\ (!m n. P m n <= A * (m + n) + B) ==> (?B. !m n. P m n <= B * (m + n))`, REPEAT STRIP_TAC THEN EXISTS_TAC `A + B` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `m + n = 0` THENL [RULE_ASSUM_TAC(REWRITE_RULE[ADD_EQ_0]) THEN ASM_REWRITE_TAC[LE_0]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * (m + n) + B` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN UNDISCH_TAC `~(m + n = 0)` THEN SPEC_TAC(`m + n`,`p:num`) THEN INDUCT_TAC THEN REWRITE_TAC[MULT_CLAUSES; LE_ADD]]);; let BOUNDS_IGNORE = prove (`!P Q. (?B. !i. P(i) <= Q(i) + B) <=> (?B N. !i. N <= i ==> P(i) <= Q(i) + B)`, REPEAT GEN_TAC THEN EQ_TAC THEN STRIP_TAC THENL [EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]; POP_ASSUM MP_TAC THEN SPEC_TAC(`B:num`,`B:num`) THEN SPEC_TAC(`N:num`,`N:num`) THEN INDUCT_TAC THENL [REWRITE_TAC[LE_0] THEN GEN_TAC THEN DISCH_TAC THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]; GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN EXISTS_TAC `B + P(N:num)` THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN ASM_CASES_TAC `SUC N <= i` THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `Q(i:num) + B` THEN REWRITE_TAC[LE_ADD; ADD_ASSOC] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; UNDISCH_TAC `~(SUC N <= i)` THEN REWRITE_TAC[NOT_LE; LT] THEN ASM_REWRITE_TAC[GSYM NOT_LE] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[ADD_ASSOC] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[LE_ADD]]]]);; (* ------------------------------------------------------------------------- *) (* Define type of nearly additive functions. *) (* ------------------------------------------------------------------------- *) let is_nadd = new_definition `is_nadd x <=> (?B. !m n. dist(m * x(n),n * x(m)) <= B * (m + n))`;; let is_nadd_0 = prove (`is_nadd (\n. 0)`, REWRITE_TAC[is_nadd; MULT_CLAUSES; DIST_REFL; LE_0]);; let nadd_abs,nadd_rep = new_basic_type_definition "nadd" ("mk_nadd","dest_nadd") is_nadd_0;; override_interface ("fn",`dest_nadd`);; override_interface ("afn",`mk_nadd`);; (* ------------------------------------------------------------------------- *) (* Properties of nearly-additive functions. *) (* ------------------------------------------------------------------------- *) let NADD_CAUCHY = prove (`!x. ?B. !m n. dist(m * fn x n,n * fn x m) <= B * (m + n)`, REWRITE_TAC[GSYM is_nadd; nadd_rep; nadd_abs; ETA_AX]);; let NADD_BOUND = prove (`!x. ?A B. !n. fn x n <= A * n + B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN MAP_EVERY EXISTS_TAC [`B + fn x 1`; `B:num`] THEN GEN_TAC THEN POP_ASSUM(MP_TAC o SPECL [`n:num`; `1`]) THEN REWRITE_TAC[DIST_LE_CASES; MULT_CLAUSES] THEN DISCH_THEN(MP_TAC o CONJUNCT2) THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; MULT_CLAUSES] THEN REWRITE_TAC[ADD_AC; MULT_AC]);; let NADD_MULTIPLICATIVE = prove (`!x. ?B. !m n. dist(fn x (m * n),m * fn x n) <= B * m + B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B + fn x 0` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `n = 0` THENL [MATCH_MP_TAC (LE_IMP DIST_ADDBOUND) THEN ASM_REWRITE_TAC[MULT_CLAUSES; RIGHT_ADD_DISTRIB; MULT_AC] THEN REWRITE_TAC[LE_EXISTS] THEN CONV_TAC(ONCE_DEPTH_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[GSYM EXISTS_REFL]; UNDISCH_TAC `~(n = 0)`] THEN REWRITE_TAC[TAUT `(~a ==> b) <=> a \/ b`; GSYM LE_MULT_LCANCEL; DIST_LMUL] THEN REWRITE_TAC[MULT_ASSOC] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN POP_ASSUM(MATCH_MP_TAC o LE_IMP) THEN REWRITE_TAC[LE_EXISTS; RIGHT_ADD_DISTRIB; LEFT_ADD_DISTRIB; MULT_AC] THEN CONV_TAC(ONCE_DEPTH_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[GSYM EXISTS_REFL]);; let NADD_ADDITIVE = prove (`!x. ?B. !m n. dist(fn x (m + n),fn x m + fn x n) <= B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN EXISTS_TAC `3 * B + fn x 0` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `m + n = 0` THENL [RULE_ASSUM_TAC(REWRITE_RULE[ADD_EQ_0]) THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[ADD_CLAUSES; DIST_LADD_0; LE_ADDR]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `3 * B` THEN REWRITE_TAC[LE_ADD] THEN UNDISCH_TAC `~(m + n = 0)`] THEN REWRITE_TAC[TAUT `(~a ==> b) <=> a \/ b`; GSYM LE_MULT_LCANCEL] THEN REWRITE_TAC[DIST_LMUL; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC(LE_IMP DIST_ADD2) THEN SUBGOAL_THEN `(m + n) * 3 * B = B * (m + m + n) + B * (n + m + n)` SUBST1_TAC THENL [REWRITE_TAC[SYM(REWRITE_CONV [ARITH] `1 + 1 + 1`)] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LEFT_ADD_DISTRIB; MULT_CLAUSES] THEN REWRITE_TAC[MULT_AC] THEN CONV_TAC NUM_CANCEL_CONV THEN REFL_TAC; MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]]);; let NADD_SUC = prove (`!x. ?B. !n. dist(fn x (SUC n),fn x n) <= B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_ADDITIVE) THEN EXISTS_TAC `B + fn x 1` THEN GEN_TAC THEN MATCH_MP_TAC(LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x n + fn x 1` THEN ASM_REWRITE_TAC[ADD1] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[DIST_LADD_0; LE_REFL]);; let NADD_DIST_LEMMA = prove (`!x. ?B. !m n. dist(fn x (m + n),fn x m) <= B * n`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_SUC) THEN EXISTS_TAC `B:num` THEN GEN_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; DIST_REFL; LE_0] THEN MATCH_MP_TAC(LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (m + n)` THEN REWRITE_TAC[ADD1; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[GSYM ADD1; MULT_CLAUSES]);; let NADD_DIST = prove (`!x. ?B. !m n. dist(fn x m,fn x n) <= B * dist(m,n)`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_DIST_LEMMA) THEN EXISTS_TAC `B:num` THEN REPEAT GEN_TAC THEN DISJ_CASES_THEN MP_TAC (SPECL [`m:num`; `n:num`] LE_CASES) THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o ONCE_REWRITE_RULE[LE_EXISTS]) THENL [ONCE_REWRITE_TAC[DIST_SYM]; ALL_TAC] THEN ASM_REWRITE_TAC[DIST_LADD_0]);; let NADD_ALTMUL = prove (`!x y. ?A B. !n. dist(n * fn x (fn y n),fn x n * fn y n) <= A * n + B`, REPEAT GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN MP_TAC(SPEC `y:nadd` NADD_BOUND) THEN DISCH_THEN(X_CHOOSE_THEN `M:num` (X_CHOOSE_TAC `L:num`)) THEN MAP_EVERY EXISTS_TAC [`B * (1 + M)`; `B * L`] THEN GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o RAND_CONV) [MULT_SYM] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B * (n + fn y n)` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC[MULT_CLAUSES; GSYM ADD_ASSOC; LE_ADD_LCANCEL] THEN ASM_REWRITE_TAC[GSYM LEFT_ADD_DISTRIB; GSYM MULT_ASSOC; LE_MULT_LCANCEL]);; (* ------------------------------------------------------------------------- *) Definition of the equivalence relation and proof that it * is * one . (* ------------------------------------------------------------------------- *) override_interface ("===",`(nadd_eq):nadd->nadd->bool`);; let nadd_eq = new_definition `x === y <=> ?B. !n. dist(fn x n,fn y n) <= B`;; let NADD_EQ_REFL = prove (`!x. x === x`, GEN_TAC THEN REWRITE_TAC[nadd_eq; DIST_REFL; LE_0]);; let NADD_EQ_SYM = prove (`!x y. x === y <=> y === x`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [DIST_SYM] THEN REFL_TAC);; let NADD_EQ_TRANS = prove (`!x y z. x === y /\ y === z ==> x === z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn y n` THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) (* Injection of the natural numbers. *) (* ------------------------------------------------------------------------- *) override_interface ("&",`nadd_of_num:num->nadd`);; let nadd_of_num = new_definition `&k = afn(\n. k * n)`;; let NADD_OF_NUM = prove (`!k. fn(&k) = \n. k * n`, REWRITE_TAC[nadd_of_num; GSYM nadd_rep; is_nadd] THEN REWRITE_TAC[DIST_REFL; LE_0; MULT_AC]);; let NADD_OF_NUM_WELLDEF = prove (`!m n. (m = n) ==> &m === &n`, REPEAT GEN_TAC THEN DISCH_THEN SUBST1_TAC THEN MATCH_ACCEPT_TAC NADD_EQ_REFL);; let NADD_OF_NUM_EQ = prove (`!m n. (&m === &n) <=> (m = n)`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[NADD_OF_NUM_WELLDEF] THEN REWRITE_TAC[nadd_eq; NADD_OF_NUM] THEN REWRITE_TAC[GSYM DIST_RMUL; BOUNDS_LINEAR_0; DIST_EQ_0]);; (* ------------------------------------------------------------------------- *) (* Definition of (reflexive) ordering and the only special property needed. *) (* ------------------------------------------------------------------------- *) override_interface ("<<=",`nadd_le:nadd->nadd->bool`);; let nadd_le = new_definition `x <<= y <=> ?B. !n. fn x n <= fn y n + B`;; let NADD_LE_WELLDEF_LEMMA = prove (`!x x' y y'. x === x' /\ y === y' /\ x <<= y ==> x' <<= y'`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le] THEN REWRITE_TAC[DIST_LE_CASES; FORALL_AND_THM] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) MP_TAC) THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B2:num`) MP_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN EXISTS_TAC `(B2 + B) + B1` THEN X_GEN_TAC `n:num` THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP o CONJUNCT2) THEN REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL]);; let NADD_LE_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x <<= y <=> x' <<= y')`, REPEAT STRIP_TAC THEN EQ_TAC THEN DISCH_TAC THEN MATCH_MP_TAC NADD_LE_WELLDEF_LEMMA THEN ASM_REWRITE_TAC[] THENL [MAP_EVERY EXISTS_TAC [`x:nadd`; `y:nadd`]; MAP_EVERY EXISTS_TAC [`x':nadd`; `y':nadd`] THEN ONCE_REWRITE_TAC[NADD_EQ_SYM]] THEN ASM_REWRITE_TAC[]);; let NADD_LE_REFL = prove (`!x. x <<= x`, REWRITE_TAC[nadd_le; LE_ADD]);; let NADD_LE_TRANS = prove (`!x y z. x <<= y /\ y <<= z ==> x <<= z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) MP_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `B2:num`) THEN EXISTS_TAC `B2 + B1` THEN GEN_TAC THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL]);; let NADD_LE_ANTISYM = prove (`!x y. x <<= y /\ y <<= x <=> (x === y)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; nadd_eq; DIST_LE_CASES] THEN EQ_TAC THENL [DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN GEN_TAC THEN CONJ_TAC THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL; LE_ADD; LE_ADDR]; DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN CONJ_TAC THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]]);; let NADD_LE_TOTAL_LEMMA = prove (`!x y. ~(x <<= y) ==> !B. ?n. ~(n = 0) /\ fn y n + B < fn x n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NOT_FORALL_THM; NOT_EXISTS_THM] THEN REWRITE_TAC[NOT_LE] THEN DISCH_TAC THEN GEN_TAC THEN POP_ASSUM(X_CHOOSE_TAC `n:num` o SPEC `B + fn x 0`) THEN EXISTS_TAC `n:num` THEN POP_ASSUM MP_TAC THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[NOT_LT; ADD_ASSOC; LE_ADDR] THEN CONV_TAC CONTRAPOS_CONV THEN REWRITE_TAC[NOT_LT] THEN DISCH_THEN(MATCH_MP_TAC o LE_IMP) THEN REWRITE_TAC[ADD_ASSOC; LE_ADD]);; let NADD_LE_TOTAL = prove (`!x y. x <<= y \/ y <<= x`, REPEAT GEN_TAC THEN GEN_REWRITE_TAC I [TAUT `a <=> ~ ~ a`] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN PURE_ONCE_REWRITE_TAC[DE_MORGAN_THM] THEN DISCH_THEN(MP_TAC o end_itlist CONJ o map (MATCH_MP NADD_LE_TOTAL_LEMMA) o CONJUNCTS) THEN REWRITE_TAC[AND_FORALL_THM] THEN DISCH_THEN(MP_TAC o SPEC `B1 + B2`) THEN REWRITE_TAC[RIGHT_AND_EXISTS_THM] THEN REWRITE_TAC[LEFT_AND_EXISTS_THM] THEN DISCH_THEN(X_CHOOSE_THEN `m:num` (X_CHOOSE_THEN `n:num` MP_TAC)) THEN DISCH_THEN(MP_TAC o MATCH_MP (ITAUT `(~a /\ b) /\ (~c /\ d) ==> ~(c \/ ~b) /\ ~(a \/ ~d)`)) THEN REWRITE_TAC[NOT_LT; GSYM LE_MULT_LCANCEL] THEN REWRITE_TAC[NOT_LE] THEN DISCH_THEN(MP_TAC o MATCH_MP LT_ADD2) THEN REWRITE_TAC[NOT_LT] THEN REWRITE_TAC[LEFT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b + c) + (d + e + f) = (d + b + e) + (a + c + f)`] THEN MATCH_MP_TAC LE_ADD2 THEN REWRITE_TAC[GSYM RIGHT_ADD_DISTRIB] THEN CONJ_TAC THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [MULT_SYM] THEN RULE_ASSUM_TAC(REWRITE_RULE[DIST_LE_CASES]) THEN ASM_REWRITE_TAC[]);; let NADD_ARCH = prove (`!x. ?n. x <<= &n`, REWRITE_TAC[nadd_le; NADD_OF_NUM; NADD_BOUND]);; let NADD_OF_NUM_LE = prove (`!m n. (&m <<= &n) <=> m <= n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_OF_NUM] THEN REWRITE_TAC[BOUNDS_LINEAR]);; (* ------------------------------------------------------------------------- *) (* Addition. *) (* ------------------------------------------------------------------------- *) override_interface ("++",`nadd_add:nadd->nadd->nadd`);; let nadd_add = new_definition `x ++ y = afn(\n. fn x n + fn y n)`;; let NADD_ADD = prove (`!x y. fn(x ++ y) = \n. fn x n + fn y n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_add; GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B1 + B2` THEN MAP_EVERY X_GEN_TAC [`m:num`; `n:num`] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC (LE_IMP DIST_ADD2) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; let NADD_ADD_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x ++ y === x' ++ y')`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC (LE_IMP DIST_ADD2) THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) (* Basic properties of addition. *) (* ------------------------------------------------------------------------- *) let NADD_ADD_SYM = prove (`!x y. (x ++ y) === (y ++ x)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_add] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [ADD_SYM] THEN REWRITE_TAC[NADD_EQ_REFL]);; let NADD_ADD_ASSOC = prove (`!x y z. (x ++ (y ++ z)) === ((x ++ y) ++ z)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[nadd_add] THEN REWRITE_TAC[NADD_ADD; ADD_ASSOC; NADD_EQ_REFL]);; let NADD_ADD_LID = prove (`!x. (&0 ++ x) === x`, GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD; NADD_OF_NUM] THEN REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; DIST_REFL; LE_0]);; let NADD_ADD_LCANCEL = prove (`!x y z. (x ++ y) === (x ++ z) ==> y === z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD; DIST_LADD]);; let NADD_LE_ADD = prove (`!x y. x <<= (x ++ y)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_ADD] THEN EXISTS_TAC `0` THEN REWRITE_TAC[ADD_CLAUSES; LE_ADD]);; let NADD_LE_EXISTS = prove (`!x y. x <<= y ==> ?d. y === x ++ d`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le] THEN DISCH_THEN(X_CHOOSE_THEN `B:num` MP_TAC) THEN REWRITE_TAC[LE_EXISTS; SKOLEM_THM] THEN DISCH_THEN(X_CHOOSE_THEN `d:num->num` (ASSUME_TAC o GSYM)) THEN EXISTS_TAC `afn d` THEN REWRITE_TAC[nadd_eq; NADD_ADD] THEN EXISTS_TAC `B:num` THEN X_GEN_TAC `n:num` THEN SUBGOAL_THEN `fn(afn d) = d` SUBST1_TAC THENL [REWRITE_TAC[GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B1 + (B2 + B)` THEN REPEAT GEN_TAC THEN MATCH_MP_TAC(LE_IMP DIST_ADD2_REV) THEN MAP_EVERY EXISTS_TAC [`m * fn x n`; `n * fn x m`] THEN ONCE_REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_REWRITE_TAC[GSYM LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC(LE_IMP DIST_ADD2) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_REWRITE_TAC[] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [MULT_SYM] THEN REWRITE_TAC[GSYM DIST_LMUL; DIST_ADDBOUND; LE_MULT_LCANCEL]; ASM_REWRITE_TAC[DIST_RADD_0; LE_REFL]]);; let NADD_OF_NUM_ADD = prove (`!m n. &m ++ &n === &(m + n)`, REWRITE_TAC[nadd_eq; NADD_OF_NUM; NADD_ADD] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; DIST_REFL; LE_0]);; (* ------------------------------------------------------------------------- *) (* Multiplication. *) (* ------------------------------------------------------------------------- *) override_interface ("**",`nadd_mul:nadd->nadd->nadd`);; let nadd_mul = new_definition `x ** y = afn(\n. fn x (fn y n))`;; let NADD_MUL = prove (`!x y. fn(x ** y) = \n. fn x (fn y n)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_mul; GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B:num` (SPEC `y:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `C:num` (SPEC `x:nadd` NADD_DIST) THEN X_CHOOSE_TAC `D:num` (SPEC `x:nadd` NADD_MULTIPLICATIVE) THEN MATCH_MP_TAC BOUNDS_NOTZERO THEN REWRITE_TAC[MULT_CLAUSES; DIST_REFL] THEN MAP_EVERY EXISTS_TAC [`D + C * B`; `D + D`] THEN REPEAT GEN_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(D * m + D) + (D * n + D) + C * B * (m + n)` THEN CONJ_TAC THENL [MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (m * fn y n)` THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (n * fn y m)` THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `C * dist(m * fn y n,n * fn y m)` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; MATCH_MP_TAC EQ_IMP_LE THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; MULT_ASSOC; ADD_AC]]);; (* ------------------------------------------------------------------------- *) (* Properties of multiplication. *) (* ------------------------------------------------------------------------- *) let NADD_MUL_SYM = prove (`!x y. (x ** y) === (y ** x)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN X_CHOOSE_THEN `A1:num` MP_TAC (SPECL [`x:nadd`; `y:nadd`] NADD_ALTMUL) THEN DISCH_THEN(X_CHOOSE_TAC `B1:num`) THEN X_CHOOSE_THEN `A2:num` MP_TAC (SPECL [`y:nadd`; `x:nadd`] NADD_ALTMUL) THEN DISCH_THEN(X_CHOOSE_TAC `B2:num`) THEN REWRITE_TAC[BOUNDS_DIVIDED] THEN REWRITE_TAC[DIST_LMUL] THEN MAP_EVERY EXISTS_TAC [`A1 + A2`; `B1 + B2`] THEN GEN_TAC THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b) + (c + d) = (a + c) + (b + d)`] THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x n * fn y n` THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN ONCE_REWRITE_TAC [DIST_SYM] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 RAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[]);; let NADD_MUL_ASSOC = prove (`!x y z. (x ** (y ** z)) === ((x ** y) ** z)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[nadd_mul] THEN REWRITE_TAC[NADD_MUL; NADD_EQ_REFL]);; let NADD_MUL_LID = prove (`!x. (&1 ** x) === x`, REWRITE_TAC[NADD_OF_NUM; nadd_mul; MULT_CLAUSES] THEN REWRITE_TAC[nadd_abs; NADD_EQ_REFL; ETA_AX]);; let NADD_LDISTRIB = prove (`!x y z. x ** (y ++ z) === (x ** y) ++ (x ** z)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN REWRITE_TAC[NADD_ADD; NADD_MUL] THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_ADDITIVE) THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]);; let NADD_MUL_WELLDEF_LEMMA = prove (`!x y y'. y === y' ==> (x ** y) === (x ** y')`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN DISCH_THEN(X_CHOOSE_TAC `B1:num`) THEN X_CHOOSE_TAC `B2:num` (SPEC `x:nadd` NADD_DIST) THEN EXISTS_TAC `B2 * B1` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B2 * dist(fn y n,fn y' n)` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]);; let NADD_MUL_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x ** y) === (x' ** y')`, REPEAT GEN_TAC THEN STRIP_TAC THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `x' ** y` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ** x'` THEN REWRITE_TAC[NADD_MUL_SYM] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ** x` THEN REWRITE_TAC[NADD_MUL_SYM]; ALL_TAC] THEN MATCH_MP_TAC NADD_MUL_WELLDEF_LEMMA THEN ASM_REWRITE_TAC[]);; let NADD_OF_NUM_MUL = prove (`!m n. &m ** &n === &(m * n)`, REWRITE_TAC[nadd_eq; NADD_OF_NUM; NADD_MUL] THEN REWRITE_TAC[MULT_ASSOC; DIST_REFL; LE_0]);; (* ------------------------------------------------------------------------- *) (* A few handy lemmas. *) (* ------------------------------------------------------------------------- *) let NADD_LE_0 = prove (`!x. &0 <<= x`, GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_OF_NUM; MULT_CLAUSES; LE_0]);; let NADD_EQ_IMP_LE = prove (`!x y. x === y ==> x <<= y`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le; DIST_LE_CASES] THEN DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]);; let NADD_LE_LMUL = prove (`!x y z. y <<= z ==> (x ** y) <<= (x ** z)`, REPEAT GEN_TAC THEN DISCH_THEN(X_CHOOSE_TAC `d:nadd` o MATCH_MP NADD_LE_EXISTS) THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `x ** y ++ x ** d` THEN REWRITE_TAC[NADD_LE_ADD] THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `x ** (y ++ d)` THEN ONCE_REWRITE_TAC[NADD_EQ_SYM] THEN REWRITE_TAC[NADD_LDISTRIB] THEN MATCH_MP_TAC NADD_MUL_WELLDEF THEN ASM_REWRITE_TAC[NADD_EQ_REFL]);; let NADD_LE_RMUL = prove (`!x y z. x <<= y ==> (x ** z) <<= (y ** z)`, MESON_TAC[NADD_LE_LMUL; NADD_LE_WELLDEF; NADD_MUL_SYM]);; let NADD_LE_RADD = prove (`!x y z. x ++ z <<= y ++ z <=> x <<= y`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_ADD] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o RAND_CONV) [ADD_SYM] THEN REFL_TAC);; let NADD_LE_LADD = prove (`!x y z. x ++ y <<= x ++ z <=> y <<= z`, MESON_TAC[NADD_LE_RADD; NADD_ADD_SYM; NADD_LE_WELLDEF]);; let NADD_RDISTRIB = prove (`!x y z. (x ++ y) ** z === x ** z ++ y ** z`, MESON_TAC[NADD_LDISTRIB; NADD_MUL_SYM; NADD_ADD_WELLDEF; NADD_EQ_TRANS; NADD_EQ_REFL; NADD_EQ_SYM]);; (* ------------------------------------------------------------------------- *) The property in a more useful form . (* ------------------------------------------------------------------------- *) let NADD_ARCH_MULT = prove (`!x k. ~(x === &0) ==> ?N. &k <<= &N ** x`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le; NOT_EXISTS_THM] THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN DISCH_THEN(MP_TAC o SPEC `B + k`) THEN REWRITE_TAC[NOT_FORALL_THM; NADD_OF_NUM] THEN REWRITE_TAC[MULT_CLAUSES; DIST_RZERO; NOT_LE] THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN MAP_EVERY EXISTS_TAC [`N:num`; `B * N`] THEN X_GEN_TAC `i:num` THEN REWRITE_TAC[NADD_MUL; NADD_OF_NUM] THEN MATCH_MP_TAC(GEN_ALL(fst(EQ_IMP_RULE(SPEC_ALL LE_ADD_RCANCEL)))) THEN EXISTS_TAC `B * i` THEN REWRITE_TAC[GSYM ADD_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `i * fn x N` THEN RULE_ASSUM_TAC(REWRITE_RULE[DIST_LE_CASES]) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[GSYM RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN REWRITE_TAC[LE_MULT_RCANCEL] THEN DISJ1_TAC THEN MATCH_MP_TAC LT_IMP_LE THEN ONCE_REWRITE_TAC[ADD_SYM] THEN FIRST_ASSUM ACCEPT_TAC);; let NADD_ARCH_ZERO = prove (`!x k. (!n. &n ** x <<= k) ==> (x === &0)`, REPEAT GEN_TAC THEN CONV_TAC CONTRAPOS_CONV THEN DISCH_TAC THEN REWRITE_TAC[NOT_FORALL_THM] THEN X_CHOOSE_TAC `p:num` (SPEC `k:nadd` NADD_ARCH) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(X_CHOOSE_TAC `N:num` o SPEC `p:num`) THEN EXISTS_TAC `N + 1` THEN DISCH_TAC THEN UNDISCH_TAC `~(x === &0)` THEN REWRITE_TAC[GSYM NADD_LE_ANTISYM; NADD_LE_0] THEN MATCH_MP_TAC(GEN_ALL(fst(EQ_IMP_RULE(SPEC_ALL NADD_LE_RADD)))) THEN EXISTS_TAC `&N ** x` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `k:nadd` THEN CONJ_TAC THENL [SUBGOAL_THEN `&(N + 1) ** x === x ++ &N ** x` MP_TAC THENL [ONCE_REWRITE_TAC[ADD_SYM] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `&1 ** x ++ &N ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&1 ++ &N) ** x` THEN CONJ_TAC THENL [MESON_TAC[NADD_OF_NUM_ADD; NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_EQ_SYM]; MESON_TAC[NADD_RDISTRIB; NADD_MUL_SYM; NADD_EQ_SYM; NADD_EQ_TRANS]]; MESON_TAC[NADD_ADD_WELLDEF; NADD_EQ_REFL; NADD_MUL_LID]]; ASM_MESON_TAC[NADD_LE_WELLDEF; NADD_EQ_REFL]]; ASM_MESON_TAC[NADD_LE_TRANS; NADD_LE_WELLDEF; NADD_EQ_REFL; NADD_ADD_LID]]);; let NADD_ARCH_LEMMA = prove (`!x y z. (!n. &n ** x <<= &n ** y ++ z) ==> x <<= y`, REPEAT STRIP_TAC THEN DISJ_CASES_TAC(SPECL [`x:nadd`; `y:nadd`] NADD_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM(X_CHOOSE_TAC `d:nadd` o MATCH_MP NADD_LE_EXISTS) THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ++ d` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ++ &0` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_ADD_WELLDEF THEN REWRITE_TAC[NADD_EQ_REFL] THEN MATCH_MP_TAC NADD_ARCH_ZERO THEN EXISTS_TAC `z:nadd` THEN ASM_MESON_TAC[NADD_MUL_WELLDEF; NADD_LE_WELLDEF; NADD_LDISTRIB; NADD_LE_LADD; NADD_EQ_REFL]; ASM_MESON_TAC[NADD_ADD_LID; NADD_ADD_WELLDEF; NADD_EQ_TRANS; NADD_ADD_SYM]]);; (* ------------------------------------------------------------------------- *) Completeness . (* ------------------------------------------------------------------------- *) let NADD_COMPLETE = prove (`!P. (?x. P x) /\ (?M. !x. P x ==> x <<= M) ==> ?M. (!x. P x ==> x <<= M) /\ !M'. (!x. P x ==> x <<= M') ==> M <<= M'`, GEN_TAC THEN DISCH_THEN (CONJUNCTS_THEN2 (X_CHOOSE_TAC `a:nadd`) (X_CHOOSE_TAC `m:nadd`)) THEN SUBGOAL_THEN `!n. ?r. (?x. P x /\ &r <<= &n ** x) /\ !r'. (?x. P x /\ &r' <<= &n ** x) ==> r' <= r` MP_TAC THENL [GEN_TAC THEN REWRITE_TAC[GSYM num_MAX] THEN CONJ_TAC THENL [MAP_EVERY EXISTS_TAC [`0`; `a:nadd`] THEN ASM_REWRITE_TAC[NADD_LE_0]; X_CHOOSE_TAC `N:num` (SPEC `m:nadd` NADD_ARCH) THEN EXISTS_TAC `n * N` THEN X_GEN_TAC `p:num` THEN DISCH_THEN(X_CHOOSE_THEN `w:nadd` STRIP_ASSUME_TAC) THEN ONCE_REWRITE_TAC[GSYM NADD_OF_NUM_LE] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** w` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &N` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_LMUL THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `m:nadd` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_ACCEPT_TAC NADD_OF_NUM_MUL]]; ONCE_REWRITE_TAC[SKOLEM_THM] THEN DISCH_THEN(X_CHOOSE_THEN `r:num->num` (fun th -> let th1,th2 = CONJ_PAIR(SPEC `n:num` th) in MAP_EVERY (MP_TAC o GEN `n:num`) [th1; th2])) THEN DISCH_THEN(MP_TAC o GEN `n:num` o SPECL [`n:num`; `SUC(r(n:num))`]) THEN REWRITE_TAC[LE_SUC_LT; LT_REFL; NOT_EXISTS_THM] THEN DISCH_THEN(ASSUME_TAC o GENL [`n:num`; `x:nadd`] o MATCH_MP (ITAUT `(a \/ b) /\ ~(c /\ b) ==> c ==> a`) o CONJ (SPECL [`&n ** x`; `&(SUC(r(n:num)))`] NADD_LE_TOTAL) o SPEC_ALL) THEN DISCH_TAC] THEN SUBGOAL_THEN `!n i. i * r(n) <= n * r(i) + n` ASSUME_TAC THENL [REPEAT GEN_TAC THEN FIRST_ASSUM(X_CHOOSE_THEN `x:nadd` STRIP_ASSUME_TAC o SPEC `n:num`) THEN ONCE_REWRITE_TAC[GSYM NADD_OF_NUM_LE] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&i ** &n ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&i ** &(r(n:num))` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_IMP_LE THEN ONCE_REWRITE_TAC[NADD_EQ_SYM] THEN MATCH_ACCEPT_TAC NADD_OF_NUM_MUL; MATCH_MP_TAC NADD_LE_LMUL THEN ASM_REWRITE_TAC[]]; MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &(SUC(r(i:num)))` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &i ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&i ** &n) ** x` THEN REWRITE_TAC[NADD_MUL_ASSOC] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&n ** &i) ** x` THEN REWRITE_TAC[ONCE_REWRITE_RULE[NADD_EQ_SYM] NADD_MUL_ASSOC] THEN MATCH_MP_TAC NADD_MUL_WELLDEF THEN REWRITE_TAC[NADD_MUL_SYM; NADD_EQ_REFL]; MATCH_MP_TAC NADD_LE_LMUL THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]; ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[GSYM MULT_SUC] THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN REWRITE_TAC[NADD_OF_NUM_MUL]]]; ALL_TAC] THEN EXISTS_TAC `afn r` THEN SUBGOAL_THEN `fn(afn r) = r` ASSUME_TAC THENL [REWRITE_TAC[GSYM nadd_rep] THEN REWRITE_TAC[is_nadd; DIST_LE_CASES] THEN EXISTS_TAC `1` THEN REWRITE_TAC[MULT_CLAUSES] THEN REWRITE_TAC[FORALL_AND_THM] THEN GEN_REWRITE_TAC RAND_CONV [SWAP_FORALL_THM] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o funpow 2 RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[] THEN MAP_EVERY X_GEN_TAC [`i:num`; `n:num`] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n * r(i:num) + n` THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD]; ALL_TAC] THEN CONJ_TAC THENL [X_GEN_TAC `x:nadd` THEN DISCH_TAC THEN MATCH_MP_TAC NADD_ARCH_LEMMA THEN EXISTS_TAC `&2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&(SUC(r(n:num)))` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; ASM_REWRITE_TAC[nadd_le; NADD_ADD; NADD_MUL; NADD_OF_NUM] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[ADD1; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC[MULT_2; MULT_CLAUSES; ADD_ASSOC; LE_ADD_RCANCEL] THEN REWRITE_TAC[GSYM ADD_ASSOC] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN MAP_EVERY EXISTS_TAC [`0`; `n:num`] THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n * r(i:num) + n` THEN ASM_REWRITE_TAC[LE_ADD_LCANCEL; ADD_CLAUSES]]; X_GEN_TAC `z:nadd` THEN DISCH_TAC THEN MATCH_MP_TAC NADD_ARCH_LEMMA THEN EXISTS_TAC `&1` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&(r(n:num)) ++ &1` THEN CONJ_TAC THENL [ASM_REWRITE_TAC[nadd_le; NADD_ADD; NADD_MUL; NADD_OF_NUM] THEN EXISTS_TAC `0` THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN GEN_TAC THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[]; REWRITE_TAC[NADD_LE_RADD] THEN FIRST_ASSUM(X_CHOOSE_THEN `x:nadd` MP_TAC o SPEC `n:num`) THEN DISCH_THEN STRIP_ASSUME_TAC THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** x` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_LE_LMUL THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]]);; (* ------------------------------------------------------------------------- *) (* A bit more on nearly-multiplicative functions. *) (* ------------------------------------------------------------------------- *) let NADD_UBOUND = prove (`!x. ?B N. !n. N <= n ==> fn x n <= B * n`, GEN_TAC THEN X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`) (SPEC `x:nadd` NADD_BOUND) THEN EXISTS_TAC `A1 + A2` THEN EXISTS_TAC `1` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A1 * n + A2` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN GEN_REWRITE_TAC LAND_CONV [GSYM(el 3 (CONJUNCTS MULT_CLAUSES))] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]);; let NADD_NONZERO = prove (`!x. ~(x === &0) ==> ?N. !n. N <= n ==> ~(fn x n = 0)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(MP_TAC o SPEC `1`) THEN REWRITE_TAC[nadd_le; NADD_MUL; NADD_OF_NUM; MULT_CLAUSES] THEN DISCH_THEN(X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`)) THEN EXISTS_TAC `A2 + 1` THEN X_GEN_TAC `n:num` THEN REPEAT DISCH_TAC THEN FIRST_ASSUM(UNDISCH_TAC o check is_forall o concl) THEN REWRITE_TAC[NOT_FORALL_THM; NOT_LE; GSYM LE_SUC_LT; ADD1] THEN EXISTS_TAC `n:num` THEN ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]);; let NADD_LBOUND = prove (`!x. ~(x === &0) ==> ?A N. !n. N <= n ==> n <= A * fn x n`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(X_CHOOSE_TAC `N:num` o MATCH_MP NADD_NONZERO) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(MP_TAC o SPEC `1`) THEN REWRITE_TAC[nadd_le; NADD_MUL; NADD_OF_NUM; MULT_CLAUSES] THEN DISCH_THEN(X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`)) THEN EXISTS_TAC `A1 + A2` THEN EXISTS_TAC `N:num` THEN GEN_TAC THEN DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A1 * fn x n + A2` THEN ASM_REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN GEN_REWRITE_TAC LAND_CONV [GSYM(el 3 (CONJUNCTS MULT_CLAUSES))] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN REWRITE_TAC[GSYM(REWRITE_CONV[ARITH_SUC] `SUC 0`)] THEN ASM_REWRITE_TAC[GSYM NOT_LT; LT]);; (* ------------------------------------------------------------------------- *) (* Auxiliary function for the multiplicative inverse. *) (* ------------------------------------------------------------------------- *) let nadd_rinv = new_definition `nadd_rinv(x) = \n. (n * n) DIV (fn x n)`;; let NADD_MUL_LINV_LEMMA0 = prove (`!x. ~(x === &0) ==> ?A B. !n. nadd_rinv x n <= A * n + B`, GEN_TAC THEN DISCH_TAC THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_LBOUND) THEN DISCH_THEN(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `N:num`)) THEN MAP_EVERY EXISTS_TAC [`A:num`; `0`; `SUC N`] THEN GEN_TAC THEN DISCH_TAC THEN REWRITE_TAC[ADD_CLAUSES] THEN MP_TAC(SPECL [`nadd_rinv x n`; `A * n`; `n:num`] LE_MULT_RCANCEL) THEN UNDISCH_TAC `SUC N <= n` THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[LE; NOT_SUC] THEN DISCH_TAC THEN DISCH_THEN(SUBST1_TAC o SYM) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `nadd_rinv x n * A * fn x n` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL] THEN CONJ_TAC THENL [DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC N` THEN ASM_REWRITE_TAC[LE; LE_REFL]; GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN REWRITE_TAC[GSYM MULT_ASSOC; LE_MULT_LCANCEL] THEN DISJ2_TAC THEN ASM_CASES_TAC `fn x n = 0` THEN ASM_REWRITE_TAC[MULT_CLAUSES; LE_0; nadd_rinv] THEN FIRST_ASSUM(MP_TAC o MATCH_MP DIVISION) THEN DISCH_THEN(fun t -> GEN_REWRITE_TAC RAND_CONV [CONJUNCT1(SPEC_ALL t)]) THEN GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN REWRITE_TAC[LE_ADD]]);; let NADD_MUL_LINV_LEMMA1 = prove (`!x n. ~(fn x n = 0) ==> dist(fn x n * nadd_rinv(x) n, n * n) <= fn x n`, REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP DIVISION) THEN DISCH_THEN(CONJUNCTS_THEN2 SUBST1_TAC ASSUME_TAC o SPEC `n * n`) THEN REWRITE_TAC[nadd_rinv] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN REWRITE_TAC[DIST_RADD_0] THEN MATCH_MP_TAC LT_IMP_LE THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; let NADD_MUL_LINV_LEMMA2 = prove (`!x. ~(x === &0) ==> ?N. !n. N <= n ==> dist(fn x n * nadd_rinv(x) n, n * n) <= fn x n`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_NONZERO) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC NADD_MUL_LINV_LEMMA1 THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; let NADD_MUL_LINV_LEMMA3 = prove (`!x. ~(x === &0) ==> ?N. !m n. N <= n ==> dist(m * fn x m * fn x n * nadd_rinv(x) n, m * fn x m * n * n) <= m * fn x m * fn x n`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA2) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN REWRITE_TAC[GSYM DIST_LMUL; MULT_ASSOC] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; let NADD_MUL_LINV_LEMMA4 = prove (`!x. ~(x === &0) ==> ?N. !m n. N <= m /\ N <= n ==> (fn x m * fn x n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= (m * n) * dist(m * fn x n,n * fn x m) + (fn x m * fn x n) * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA3) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN REWRITE_TAC[DIST_LMUL; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [DIST_SYM] THEN MATCH_MP_TAC DIST_TRIANGLES_LE THEN CONJ_TAC THENL [ANTE_RES_THEN(MP_TAC o SPEC `m:num`) (ASSUME `N <= n`); ANTE_RES_THEN(MP_TAC o SPEC `n:num`) (ASSUME `N <= m`)] THEN MATCH_MP_TAC EQ_IMP THEN REWRITE_TAC[MULT_AC]);; let NADD_MUL_LINV_LEMMA5 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> (fn x m * fn x n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m * n) * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA4) THEN DISCH_THEN(X_CHOOSE_TAC `N1:num`) THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_THEN `B2:num` (X_CHOOSE_TAC `N2:num`) (SPEC `x:nadd` NADD_UBOUND) THEN EXISTS_TAC `B1 + B2 * B2` THEN EXISTS_TAC `N1 + N2` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(m * n) * dist(m * fn x n,n * fn x m) + (fn x m * fn x n) * (m + n)` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]; REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_ADD2] THEN CONJ_TAC THENL [GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN GEN_REWRITE_TAC RAND_CONV [GSYM MULT_ASSOC] THEN GEN_REWRITE_TAC (funpow 2 RAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; ONCE_REWRITE_TAC[AC MULT_AC `(a * b) * (c * d) * e = ((a * c) * (b * d)) * e`] THEN REWRITE_TAC[LE_MULT_RCANCEL] THEN DISJ1_TAC THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]]);; let NADD_MUL_LINV_LEMMA6 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> (m * n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m * n) * (m + n)`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA5) THEN DISCH_THEN(X_CHOOSE_THEN `B1:num` (X_CHOOSE_TAC `N1:num`)) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_LBOUND) THEN DISCH_THEN(X_CHOOSE_THEN `B2:num` (X_CHOOSE_TAC `N2:num`)) THEN EXISTS_TAC `B1 * B2 * B2` THEN EXISTS_TAC `N1 + N2` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(B2 * B2) * (fn x m * fn x n) * dist (m * nadd_rinv x n,n * nadd_rinv x m)` THEN CONJ_TAC THENL [REWRITE_TAC[MULT_ASSOC; LE_MULT_RCANCEL] THEN DISJ1_TAC THEN ONCE_REWRITE_TAC[AC MULT_AC `((a * b) * c) * d = (a * c) * (b * d)`] THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN FIRST_ASSUM MATCH_MP_TAC; ONCE_REWRITE_TAC[AC MULT_AC `(a * b * c) * (d * e) * f = (b * c) * (a * (d * e) * f)`] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN CONJ_TAC] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]);; let NADD_MUL_LINV_LEMMA7 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA6) THEN DISCH_THEN(X_CHOOSE_THEN `B:num` (X_CHOOSE_TAC `N:num`)) THEN MAP_EVERY EXISTS_TAC [`B:num`; `N + 1`] THEN MAP_EVERY X_GEN_TAC [`m:num`; `n:num`] THEN STRIP_TAC THEN SUBGOAL_THEN `N <= m /\ N <= n` MP_TAC THENL [CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N + 1` THEN ASM_REWRITE_TAC[LE_ADD]; DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN ONCE_REWRITE_TAC[AC MULT_AC `a * b * c = b * a * c`] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISCH_THEN(DISJ_CASES_THEN2 MP_TAC ACCEPT_TAC) THEN CONV_TAC CONTRAPOS_CONV THEN DISCH_THEN(K ALL_TAC) THEN ONCE_REWRITE_TAC[GSYM(CONJUNCT1 LE)] THEN REWRITE_TAC[NOT_LE; GSYM LE_SUC_LT] THEN REWRITE_TAC[EQT_ELIM(REWRITE_CONV[ARITH] `SUC 0 = 1 * 1`)] THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N + 1` THEN ASM_REWRITE_TAC[LE_ADDR]]);; let NADD_MUL_LINV_LEMMA7a = prove (`!x. ~(x === &0) ==> !N. ?A B. !m n. m <= N ==> dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= A * n + B`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA0) THEN DISCH_THEN(X_CHOOSE_THEN `A0:num` (X_CHOOSE_TAC `B0:num`)) THEN INDUCT_TAC THENL [MAP_EVERY EXISTS_TAC [`nadd_rinv x 0`; `0`] THEN REPEAT GEN_TAC THEN REWRITE_TAC[LE] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[MULT_CLAUSES; DIST_LZERO; ADD_CLAUSES] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN MATCH_ACCEPT_TAC LE_REFL; FIRST_ASSUM(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `B:num`)) THEN EXISTS_TAC `A + (nadd_rinv(x)(SUC N) + SUC N * A0)` THEN EXISTS_TAC `SUC N * B0 + B` THEN REPEAT GEN_TAC THEN REWRITE_TAC[LE] THEN DISCH_THEN(DISJ_CASES_THEN2 SUBST1_TAC ASSUME_TAC) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC N * nadd_rinv x n + n * nadd_rinv x (SUC N)` THEN REWRITE_TAC[DIST_ADDBOUND] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b + c) + d + e = (c + d) + (b + a + e)`] THEN MATCH_MP_TAC LE_ADD2 THEN CONJ_TAC THENL [REWRITE_TAC[GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN MATCH_ACCEPT_TAC LE_ADD]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]]]);; let NADD_MUL_LINV_LEMMA8 = prove (`!x. ~(x === &0) ==> ?B. !m n. dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m + n)`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA7) THEN DISCH_THEN(X_CHOOSE_THEN `B0:num` (X_CHOOSE_TAC `N:num`)) THEN FIRST_ASSUM(MP_TAC o SPEC `N:num` o MATCH_MP NADD_MUL_LINV_LEMMA7a) THEN DISCH_THEN(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `B:num`)) THEN MATCH_MP_TAC BOUNDS_NOTZERO THEN REWRITE_TAC[DIST_REFL] THEN EXISTS_TAC `A + B0` THEN EXISTS_TAC `B:num` THEN REPEAT GEN_TAC THEN DISJ_CASES_THEN2 ASSUME_TAC MP_TAC (SPECL [`N:num`; `m:num`] LE_CASES) THENL [DISJ_CASES_THEN2 ASSUME_TAC MP_TAC (SPECL [`N:num`; `n:num`] LE_CASES) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B0 * (m + n)` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; GEN_REWRITE_TAC (RAND_CONV o funpow 2 LAND_CONV) [ADD_SYM] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]; DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * m + B` THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]; DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL] THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]);; (* ------------------------------------------------------------------------- *) (* Now the multiplicative inverse proper. *) (* ------------------------------------------------------------------------- *) let nadd_inv = new_definition `nadd_inv(x) = if x === &0 then &0 else afn(nadd_rinv x)`;; override_interface ("inv",`nadd_inv:nadd->nadd`);; let NADD_INV = prove (`!x. fn(nadd_inv x) = if x === &0 then (\n. 0) else nadd_rinv x`, GEN_TAC THEN REWRITE_TAC[nadd_inv] THEN ASM_CASES_TAC `x === &0` THEN ASM_REWRITE_TAC[NADD_OF_NUM; MULT_CLAUSES] THEN REWRITE_TAC[GSYM nadd_rep; is_nadd] THEN MATCH_MP_TAC NADD_MUL_LINV_LEMMA8 THEN POP_ASSUM ACCEPT_TAC);; let NADD_MUL_LINV = prove (`!x. ~(x === &0) ==> inv(x) ** x === &1`, GEN_TAC THEN DISCH_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN ONCE_REWRITE_TAC[BOUNDS_DIVIDED] THEN X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `B1:num`) (SPECL [`inv(x)`; `x:nadd`] NADD_ALTMUL) THEN REWRITE_TAC[DIST_LMUL; NADD_OF_NUM; MULT_CLAUSES] THEN FIRST_ASSUM(X_CHOOSE_TAC `N:num` o MATCH_MP NADD_MUL_LINV_LEMMA2) THEN X_CHOOSE_THEN `A':num` (X_CHOOSE_TAC `B':num`) (SPEC `x:nadd` NADD_BOUND) THEN SUBGOAL_THEN `?A2 B2. !n. dist(fn x n * nadd_rinv x n,n * n) <= A2 * n + B2` STRIP_ASSUME_TAC THENL [EXISTS_TAC `A':num` THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN MAP_EVERY EXISTS_TAC [`B':num`; `N:num`] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fn x n` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MAP_EVERY EXISTS_TAC [`A1 + A2`; `B1 + B2`] THEN GEN_TAC THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `fn (inv x) n * fn x n` THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b) + c + d = (a + c) + (b + d)`] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[NADD_INV]]);; let NADD_INV_0 = prove (`inv(&0) === &0`, REWRITE_TAC[nadd_inv; NADD_EQ_REFL]);; (* ------------------------------------------------------------------------- *) (* Welldefinedness follows from already established principles because if *) x = y then y ' = y ' 1 = y ' ( x ' x ) = y ' ( x ' y ) = ( y ' y ) x ' = 1 x ' = x ' (* ------------------------------------------------------------------------- *) let NADD_INV_WELLDEF = prove (`!x y. x === y ==> inv(x) === inv(y)`, let TAC tm ths = MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC tm THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC ths] in REPEAT STRIP_TAC THEN ASM_CASES_TAC `x === &0` THENL [SUBGOAL_THEN `y === &0` ASSUME_TAC THENL [ASM_MESON_TAC[NADD_EQ_TRANS; NADD_EQ_SYM]; ASM_REWRITE_TAC[nadd_inv; NADD_EQ_REFL]]; SUBGOAL_THEN `~(y === &0)` ASSUME_TAC THENL [ASM_MESON_TAC[NADD_EQ_TRANS; NADD_EQ_SYM]; ALL_TAC]] THEN TAC `inv(y) ** &1` [NADD_MUL_SYM; NADD_MUL_LID; NADD_EQ_TRANS] THEN TAC `inv(y) ** (inv(x) ** x)` [NADD_MUL_LINV; NADD_MUL_WELLDEF; NADD_EQ_REFL] THEN TAC `inv(y) ** (inv(x) ** y)` [NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_EQ_SYM] THEN TAC `(inv(y) ** y) ** inv(x)` [NADD_MUL_ASSOC; NADD_MUL_SYM; NADD_EQ_TRANS; NADD_MUL_WELLDEF; NADD_EQ_REFL] THEN ASM_MESON_TAC[NADD_MUL_LINV; NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_MUL_LID; NADD_EQ_TRANS; NADD_EQ_SYM]);; (* ------------------------------------------------------------------------- *) (* Definition of the new type. *) (* ------------------------------------------------------------------------- *) let hreal_tybij = define_quotient_type "hreal" ("mk_hreal","dest_hreal") `(===)`;; do_list overload_interface ["+",`hreal_add:hreal->hreal->hreal`; "*",`hreal_mul:hreal->hreal->hreal`; "<=",`hreal_le:hreal->hreal->bool`];; do_list override_interface ["&",`hreal_of_num:num->hreal`; "inv",`hreal_inv:hreal->hreal`];; let hreal_of_num,hreal_of_num_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_of_num" NADD_OF_NUM_WELLDEF;; let hreal_add,hreal_add_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_add" NADD_ADD_WELLDEF;; let hreal_mul,hreal_mul_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_mul" NADD_MUL_WELLDEF;; let hreal_le,hreal_le_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_le" NADD_LE_WELLDEF;; let hreal_inv,hreal_inv_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_inv" NADD_INV_WELLDEF;; let HREAL_COMPLETE = let th1 = ASSUME `(P:nadd->bool) = (\x. Q(mk_hreal((===) x)))` in let th2 = BETA_RULE(AP_THM th1 `x:nadd`) in let th3 = lift_theorem hreal_tybij (NADD_EQ_REFL,NADD_EQ_SYM,NADD_EQ_TRANS) [hreal_of_num_th; hreal_add_th; hreal_mul_th; hreal_le_th; th2] (SPEC_ALL NADD_COMPLETE) in let th4 = MATCH_MP (DISCH_ALL th3) (REFL `\x. Q(mk_hreal((===) x)):bool`) in CONV_RULE(GEN_ALPHA_CONV `P:hreal->bool`) (GEN_ALL th4);; let [HREAL_OF_NUM_EQ; HREAL_OF_NUM_LE; HREAL_OF_NUM_ADD; HREAL_OF_NUM_MUL; HREAL_LE_REFL; HREAL_LE_TRANS; HREAL_LE_ANTISYM; HREAL_LE_TOTAL; HREAL_LE_ADD; HREAL_LE_EXISTS; HREAL_ARCH; HREAL_ADD_SYM; HREAL_ADD_ASSOC; HREAL_ADD_LID; HREAL_ADD_LCANCEL; HREAL_MUL_SYM; HREAL_MUL_ASSOC; HREAL_MUL_LID; HREAL_ADD_LDISTRIB; HREAL_MUL_LINV; HREAL_INV_0] = map (lift_theorem hreal_tybij (NADD_EQ_REFL,NADD_EQ_SYM,NADD_EQ_TRANS) [hreal_of_num_th; hreal_add_th; hreal_mul_th; hreal_le_th; hreal_inv_th]) [NADD_OF_NUM_EQ; NADD_OF_NUM_LE; NADD_OF_NUM_ADD; NADD_OF_NUM_MUL; NADD_LE_REFL; NADD_LE_TRANS; NADD_LE_ANTISYM; NADD_LE_TOTAL; NADD_LE_ADD; NADD_LE_EXISTS; NADD_ARCH; NADD_ADD_SYM; NADD_ADD_ASSOC; NADD_ADD_LID; NADD_ADD_LCANCEL; NADD_MUL_SYM; NADD_MUL_ASSOC; NADD_MUL_LID; NADD_LDISTRIB; NADD_MUL_LINV; NADD_INV_0];; (* ------------------------------------------------------------------------- *) (* Consequential theorems needed later. *) (* ------------------------------------------------------------------------- *) let HREAL_LE_EXISTS_DEF = prove (`!m n. m <= n <=> ?d. n = m + d`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS] THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC) THEN REWRITE_TAC[HREAL_LE_ADD]);; let HREAL_EQ_ADD_LCANCEL = prove (`!m n p. (m + n = m + p) <=> (n = p)`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[HREAL_ADD_LCANCEL] THEN DISCH_THEN SUBST1_TAC THEN REFL_TAC);; let HREAL_EQ_ADD_RCANCEL = prove (`!m n p. (m + p = n + p) <=> (m = n)`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL]);; let HREAL_LE_ADD_LCANCEL = prove (`!m n p. (m + n <= m + p) <=> (n <= p)`, REWRITE_TAC[HREAL_LE_EXISTS_DEF; GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL]);; let HREAL_LE_ADD_RCANCEL = prove (`!m n p. (m + p <= n + p) <=> (m <= n)`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN MATCH_ACCEPT_TAC HREAL_LE_ADD_LCANCEL);; let HREAL_ADD_RID = prove (`!n. n + &0 = n`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN MATCH_ACCEPT_TAC HREAL_ADD_LID);; let HREAL_ADD_RDISTRIB = prove (`!m n p. (m + n) * p = m * p + n * p`, ONCE_REWRITE_TAC[HREAL_MUL_SYM] THEN MATCH_ACCEPT_TAC HREAL_ADD_LDISTRIB);; let HREAL_MUL_LZERO = prove (`!m. &0 * m = &0`, GEN_TAC THEN MP_TAC(SPECL [`&0`; `&1`; `m:hreal`] HREAL_ADD_RDISTRIB) THEN REWRITE_TAC[HREAL_ADD_LID] THEN GEN_REWRITE_TAC (funpow 2 LAND_CONV) [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL] THEN DISCH_THEN(ACCEPT_TAC o SYM));; let HREAL_MUL_RZERO = prove (`!m. m * &0 = &0`, ONCE_REWRITE_TAC[HREAL_MUL_SYM] THEN MATCH_ACCEPT_TAC HREAL_MUL_LZERO);; let HREAL_ADD_AC = prove (`(m + n = n + m) /\ ((m + n) + p = m + (n + p)) /\ (m + (n + p) = n + (m + p))`, REWRITE_TAC[HREAL_ADD_ASSOC; EQT_INTRO(SPEC_ALL HREAL_ADD_SYM)] THEN AP_THM_TAC THEN AP_TERM_TAC THEN MATCH_ACCEPT_TAC HREAL_ADD_SYM);; let HREAL_LE_ADD2 = prove (`!a b c d. a <= b /\ c <= d ==> a + c <= b + d`, REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS_DEF] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `d1:hreal`) (X_CHOOSE_TAC `d2:hreal`)) THEN EXISTS_TAC `d1 + d2` THEN ASM_REWRITE_TAC[HREAL_ADD_AC]);; let HREAL_LE_MUL_RCANCEL_IMP = prove (`!a b c. a <= b ==> a * c <= b * c`, REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS_DEF] THEN DISCH_THEN(X_CHOOSE_THEN `d:hreal` SUBST1_TAC) THEN EXISTS_TAC `d * c` THEN REWRITE_TAC[HREAL_ADD_RDISTRIB]);; (* ------------------------------------------------------------------------- *) (* Define operations on representatives of signed reals. *) (* ------------------------------------------------------------------------- *) let treal_of_num = new_definition `treal_of_num n = (&n, &0)`;; let treal_neg = new_definition `treal_neg ((x:hreal),(y:hreal)) = (y,x)`;; let treal_add = new_definition `(x1,y1) treal_add (x2,y2) = (x1 + x2, y1 + y2)`;; let treal_mul = new_definition `(x1,y1) treal_mul (x2,y2) = ((x1 * x2) + (y1 * y2),(x1 * y2) + (y1 * x2))`;; let treal_le = new_definition `(x1,y1) treal_le (x2,y2) <=> x1 + y2 <= x2 + y1`;; let treal_inv = new_definition `treal_inv(x,y) = if x = y then (&0, &0) else if y <= x then (inv(@d. x = y + d), &0) else (&0, inv(@d. y = x + d))`;; (* ------------------------------------------------------------------------- *) (* Define the equivalence relation and prove it *is* one. *) (* ------------------------------------------------------------------------- *) let treal_eq = new_definition `(x1,y1) treal_eq (x2,y2) <=> (x1 + y2 = x2 + y1)`;; let TREAL_EQ_REFL = prove (`!x. x treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq]);; let TREAL_EQ_SYM = prove (`!x y. x treal_eq y <=> y treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq; EQ_SYM_EQ]);; let TREAL_EQ_TRANS = prove (`!x y z. x treal_eq y /\ y treal_eq z ==> x treal_eq z`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq] THEN REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MK_COMB o (AP_TERM `(+)` F_F I) o CONJ_PAIR) THEN GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_ASSOC; HREAL_EQ_ADD_RCANCEL] THEN DISCH_THEN(MATCH_ACCEPT_TAC o ONCE_REWRITE_RULE[HREAL_ADD_SYM]));; (* ------------------------------------------------------------------------- *) (* Useful to avoid unnecessary use of the equivalence relation. *) (* ------------------------------------------------------------------------- *) let TREAL_EQ_AP = prove (`!x y. (x = y) ==> x treal_eq y`, SIMP_TAC[TREAL_EQ_REFL]);; (* ------------------------------------------------------------------------- *) (* Commutativity properties for injector. *) (* ------------------------------------------------------------------------- *) let TREAL_OF_NUM_EQ = prove (`!m n. (treal_of_num m treal_eq treal_of_num n) <=> (m = n)`, REWRITE_TAC[treal_of_num; treal_eq; HREAL_OF_NUM_EQ; HREAL_ADD_RID]);; let TREAL_OF_NUM_LE = prove (`!m n. (treal_of_num m treal_le treal_of_num n) <=> m <= n`, REWRITE_TAC[treal_of_num; treal_le; HREAL_OF_NUM_LE; HREAL_ADD_RID]);; let TREAL_OF_NUM_ADD = prove (`!m n. (treal_of_num m treal_add treal_of_num n) treal_eq (treal_of_num(m + n))`, REWRITE_TAC[treal_of_num; treal_eq; treal_add; HREAL_OF_NUM_ADD; HREAL_ADD_RID; ADD_CLAUSES]);; let TREAL_OF_NUM_MUL = prove (`!m n. (treal_of_num m treal_mul treal_of_num n) treal_eq (treal_of_num(m * n))`, REWRITE_TAC[treal_of_num; treal_eq; treal_mul; HREAL_OF_NUM_MUL; HREAL_MUL_RZERO; HREAL_MUL_LZERO; HREAL_ADD_RID; HREAL_ADD_LID; HREAL_ADD_RID; MULT_CLAUSES]);; (* ------------------------------------------------------------------------- *) (* Strong forms of equality are useful to simplify welldefinedness proofs. *) (* ------------------------------------------------------------------------- *) let TREAL_ADD_SYM_EQ = prove (`!x y. x treal_add y = y treal_add x`, REWRITE_TAC[FORALL_PAIR_THM; treal_add; PAIR_EQ; HREAL_ADD_SYM]);; let TREAL_MUL_SYM_EQ = prove (`!x y. x treal_mul y = y treal_mul x`, REWRITE_TAC[FORALL_PAIR_THM; treal_mul; HREAL_MUL_SYM; HREAL_ADD_SYM]);; (* ------------------------------------------------------------------------- *) (* Prove the properties of operations on representatives. *) (* ------------------------------------------------------------------------- *) let TREAL_ADD_SYM = prove (`!x y. (x treal_add y) treal_eq (y treal_add x)`, REPEAT GEN_TAC THEN MATCH_MP_TAC TREAL_EQ_AP THEN MATCH_ACCEPT_TAC TREAL_ADD_SYM_EQ);; let TREAL_ADD_ASSOC = prove (`!x y z. (x treal_add (y treal_add z)) treal_eq ((x treal_add y) treal_add z)`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_add; HREAL_ADD_ASSOC]);; let TREAL_ADD_LID = prove (`!x. ((treal_of_num 0) treal_add x) treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_of_num; treal_add; treal_eq; HREAL_ADD_LID]);; let TREAL_ADD_LINV = prove (`!x. ((treal_neg x) treal_add x) treal_eq (treal_of_num 0)`, REWRITE_TAC[FORALL_PAIR_THM; treal_neg; treal_add; treal_eq; treal_of_num; HREAL_ADD_LID; HREAL_ADD_RID; HREAL_ADD_SYM]);; let TREAL_MUL_SYM = prove (`!x y. (x treal_mul y) treal_eq (y treal_mul x)`, SIMP_TAC[TREAL_EQ_AP; TREAL_MUL_SYM_EQ]);; let TREAL_MUL_ASSOC = prove (`!x y z. (x treal_mul (y treal_mul z)) treal_eq ((x treal_mul y) treal_mul z)`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_mul; HREAL_ADD_LDISTRIB; HREAL_ADD_RDISTRIB; GSYM HREAL_MUL_ASSOC; HREAL_ADD_AC]);; let TREAL_MUL_LID = prove (`!x. ((treal_of_num 1) treal_mul x) treal_eq x`, SIMP_TAC[FORALL_PAIR_THM; treal_of_num; treal_mul; treal_eq] THEN REWRITE_TAC[HREAL_MUL_LZERO; HREAL_MUL_LID; HREAL_ADD_LID; HREAL_ADD_RID]);; let TREAL_ADD_LDISTRIB = prove (`!x y z. (x treal_mul (y treal_add z)) treal_eq ((x treal_mul y) treal_add (x treal_mul z))`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_mul; treal_add; HREAL_ADD_LDISTRIB; PAIR_EQ; HREAL_ADD_AC]);; let TREAL_LE_REFL = prove (`!x. x treal_le x`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; HREAL_LE_REFL]);; let TREAL_LE_ANTISYM = prove (`!x y. x treal_le y /\ y treal_le x <=> (x treal_eq y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; treal_eq; HREAL_LE_ANTISYM]);; let TREAL_LE_TRANS = prove (`!x y z. x treal_le y /\ y treal_le z ==> x treal_le z`, REWRITE_TAC[FORALL_PAIR_THM; treal_le] THEN REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP HREAL_LE_ADD2) THEN GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_ASSOC; HREAL_LE_ADD_RCANCEL] THEN DISCH_THEN(MATCH_ACCEPT_TAC o ONCE_REWRITE_RULE[HREAL_ADD_SYM]));; let TREAL_LE_TOTAL = prove (`!x y. x treal_le y \/ y treal_le x`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; HREAL_LE_TOTAL]);; let TREAL_LE_LADD_IMP = prove (`!x y z. (y treal_le z) ==> (x treal_add y) treal_le (x treal_add z)`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; treal_add] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL] THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL]);; let TREAL_LE_MUL = prove (`!x y. (treal_of_num 0) treal_le x /\ (treal_of_num 0) treal_le y ==> (treal_of_num 0) treal_le (x treal_mul y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_of_num; treal_le; treal_mul] THEN REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o MATCH_MP HREAL_LE_EXISTS) THEN REWRITE_TAC[HREAL_ADD_LDISTRIB; HREAL_LE_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN GEN_REWRITE_TAC RAND_CONV [HREAL_ADD_SYM] THEN ASM_REWRITE_TAC[HREAL_LE_ADD_LCANCEL] THEN MATCH_MP_TAC HREAL_LE_MUL_RCANCEL_IMP THEN ASM_REWRITE_TAC[]);; let TREAL_INV_0 = prove (`treal_inv (treal_of_num 0) treal_eq (treal_of_num 0)`, REWRITE_TAC[treal_inv; treal_eq; treal_of_num]);; let TREAL_MUL_LINV = prove (`!x. ~(x treal_eq treal_of_num 0) ==> (treal_inv(x) treal_mul x) treal_eq (treal_of_num 1)`, REWRITE_TAC[FORALL_PAIR_THM] THEN MAP_EVERY X_GEN_TAC [`x:hreal`; `y:hreal`] THEN PURE_REWRITE_TAC[treal_eq; treal_of_num; treal_mul; treal_inv] THEN PURE_REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_TAC THEN PURE_ASM_REWRITE_TAC[COND_CLAUSES] THEN COND_CASES_TAC THEN PURE_REWRITE_TAC[treal_mul; treal_eq] THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID; HREAL_MUL_LZERO; HREAL_MUL_RZERO] THENL [ALL_TAC; DISJ_CASES_THEN MP_TAC(SPECL [`x:hreal`; `y:hreal`] HREAL_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN DISCH_TAC] THEN FIRST_ASSUM(MP_TAC o MATCH_MP HREAL_LE_EXISTS) THEN DISCH_THEN(MP_TAC o SELECT_RULE) THEN DISCH_THEN(fun th -> ASSUME_TAC (SYM th) THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [th]) THEN REWRITE_TAC[HREAL_ADD_LDISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [HREAL_ADD_SYM] THEN AP_TERM_TAC THEN MATCH_MP_TAC HREAL_MUL_LINV THEN DISCH_THEN SUBST_ALL_TAC THEN FIRST_ASSUM(UNDISCH_TAC o check is_eq o concl) THEN ASM_REWRITE_TAC[HREAL_ADD_RID] THEN PURE_ONCE_REWRITE_TAC[EQ_SYM_EQ] THEN ASM_REWRITE_TAC[]);; (* ------------------------------------------------------------------------- *) (* Show that the operations respect the equivalence relation. *) (* ------------------------------------------------------------------------- *) let TREAL_OF_NUM_WELLDEF = prove (`!m n. (m = n) ==> (treal_of_num m) treal_eq (treal_of_num n)`, REPEAT GEN_TAC THEN DISCH_THEN SUBST1_TAC THEN MATCH_ACCEPT_TAC TREAL_EQ_REFL);; let TREAL_NEG_WELLDEF = prove (`!x1 x2. x1 treal_eq x2 ==> (treal_neg x1) treal_eq (treal_neg x2)`, REWRITE_TAC[FORALL_PAIR_THM; treal_neg; treal_eq] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN ASM_REWRITE_TAC[]);; let TREAL_ADD_WELLDEFR = prove (`!x1 x2 y. x1 treal_eq x2 ==> (x1 treal_add y) treal_eq (x2 treal_add y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_add; treal_eq] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL; HREAL_ADD_ASSOC] THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL; HREAL_ADD_ASSOC]);; let TREAL_ADD_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_add y1) treal_eq (x2 treal_add y2)`, REPEAT GEN_TAC THEN DISCH_TAC THEN MATCH_MP_TAC TREAL_EQ_TRANS THEN EXISTS_TAC `x1 treal_add y2` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[TREAL_ADD_SYM_EQ]; ALL_TAC] THEN MATCH_MP_TAC TREAL_ADD_WELLDEFR THEN ASM_REWRITE_TAC[]);; let TREAL_MUL_WELLDEFR = prove (`!x1 x2 y. x1 treal_eq x2 ==> (x1 treal_mul y) treal_eq (x2 treal_mul y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_mul; treal_eq] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[AC HREAL_ADD_AC `(a + b) + (c + d) = (a + d) + (b + c)`] THEN REWRITE_TAC[GSYM HREAL_ADD_RDISTRIB] THEN DISCH_TAC THEN ASM_REWRITE_TAC[] THEN AP_TERM_TAC THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN POP_ASSUM SUBST1_TAC THEN REFL_TAC);; let TREAL_MUL_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_mul y1) treal_eq (x2 treal_mul y2)`, REPEAT GEN_TAC THEN DISCH_TAC THEN MATCH_MP_TAC TREAL_EQ_TRANS THEN EXISTS_TAC `x1 treal_mul y2` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[TREAL_MUL_SYM_EQ]; ALL_TAC] THEN MATCH_MP_TAC TREAL_MUL_WELLDEFR THEN ASM_REWRITE_TAC[]);; let TREAL_EQ_IMP_LE = prove (`!x y. x treal_eq y ==> x treal_le y`, SIMP_TAC[FORALL_PAIR_THM; treal_eq; treal_le; HREAL_LE_REFL]);; let TREAL_LE_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_le y1 <=> x2 treal_le y2)`, REPEAT (STRIP_TAC ORELSE EQ_TAC) THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `y1:hreal#hreal` THEN CONJ_TAC THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `x1:hreal#hreal` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC TREAL_EQ_IMP_LE THEN ONCE_REWRITE_TAC[TREAL_EQ_SYM]; MATCH_MP_TAC TREAL_EQ_IMP_LE]; MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `y2:hreal#hreal` THEN CONJ_TAC THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `x2:hreal#hreal` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC TREAL_EQ_IMP_LE; MATCH_MP_TAC TREAL_EQ_IMP_LE THEN ONCE_REWRITE_TAC[TREAL_EQ_SYM]]] THEN ASM_REWRITE_TAC[]);; let TREAL_INV_WELLDEF = prove (`!x y. x treal_eq y ==> (treal_inv x) treal_eq (treal_inv y)`, let lemma = prove (`(@d. x = x + d) = &0`, MATCH_MP_TAC SELECT_UNIQUE THEN BETA_TAC THEN GEN_TAC THEN GEN_REWRITE_TAC (funpow 2 LAND_CONV) [GSYM HREAL_ADD_RID] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL] THEN MATCH_ACCEPT_TAC EQ_SYM_EQ) in REWRITE_TAC[FORALL_PAIR_THM] THEN MAP_EVERY X_GEN_TAC [`x1:hreal`; `x2:hreal`; `y1:hreal`; `y2:hreal`] THEN PURE_REWRITE_TAC[treal_eq; treal_inv] THEN ASM_CASES_TAC `x1 :hreal = x2` THEN ASM_CASES_TAC `y1 :hreal = y2` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[TREAL_EQ_REFL] THEN DISCH_THEN(MP_TAC o GEN_REWRITE_RULE RAND_CONV [HREAL_ADD_SYM]) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; HREAL_EQ_ADD_RCANCEL] THEN DISCH_TAC THEN ASM_REWRITE_TAC[HREAL_LE_REFL; lemma; HREAL_INV_0;TREAL_EQ_REFL] THEN ASM_CASES_TAC `x2 <= x1` THEN ASM_REWRITE_TAC[] THENL [FIRST_ASSUM(ASSUME_TAC o SYM o SELECT_RULE o MATCH_MP HREAL_LE_EXISTS) THEN UNDISCH_TAC `x1 + y2 = x2 + y1` THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD] THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV o RAND_CONV o BINDER_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; TREAL_EQ_REFL]; DISJ_CASES_THEN MP_TAC (SPECL [`x1:hreal`; `x2:hreal`] HREAL_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN DISCH_TAC THEN FIRST_ASSUM(ASSUME_TAC o SYM o SELECT_RULE o MATCH_MP HREAL_LE_EXISTS) THEN UNDISCH_TAC `x1 + y2 = x2 + y1` THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD] THEN COND_CASES_TAC THENL [UNDISCH_TAC `(@d. x2 = x1 + d) + y1 <= y1:hreal` THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD_LCANCEL] THEN DISCH_TAC THEN SUBGOAL_THEN `(@d. x2 = x1 + d) = &0` MP_TAC THENL [ASM_REWRITE_TAC[GSYM HREAL_LE_ANTISYM] THEN GEN_REWRITE_TAC RAND_CONV [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_LE_ADD]; DISCH_THEN SUBST_ALL_TAC THEN UNDISCH_TAC `x1 + & 0 = x2` THEN ASM_REWRITE_TAC[HREAL_ADD_RID]]; GEN_REWRITE_TAC (funpow 3 RAND_CONV o BINDER_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; TREAL_EQ_REFL]]]);; (* ------------------------------------------------------------------------- *) (* Now define the quotient type -- the reals at last! *) (* ------------------------------------------------------------------------- *) let real_tybij = define_quotient_type "real" ("mk_real","dest_real") `(treal_eq)`;; let real_of_num,real_of_num_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_of_num" TREAL_OF_NUM_WELLDEF;; let real_neg,real_neg_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_neg" TREAL_NEG_WELLDEF;; let real_add,real_add_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_add" TREAL_ADD_WELLDEF;; let real_mul,real_mul_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_mul" TREAL_MUL_WELLDEF;; let real_le,real_le_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_le" TREAL_LE_WELLDEF;; let real_inv,real_inv_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_inv" TREAL_INV_WELLDEF;; let [REAL_ADD_SYM; REAL_ADD_ASSOC; REAL_ADD_LID; REAL_ADD_LINV; REAL_MUL_SYM; REAL_MUL_ASSOC; REAL_MUL_LID; REAL_ADD_LDISTRIB; REAL_LE_REFL; REAL_LE_ANTISYM; REAL_LE_TRANS; REAL_LE_TOTAL; REAL_LE_LADD_IMP; REAL_LE_MUL; REAL_INV_0; REAL_MUL_LINV; REAL_OF_NUM_EQ; REAL_OF_NUM_LE; REAL_OF_NUM_ADD; REAL_OF_NUM_MUL] = map (lift_theorem real_tybij (TREAL_EQ_REFL,TREAL_EQ_SYM,TREAL_EQ_TRANS) [real_of_num_th; real_neg_th; real_add_th; real_mul_th; real_le_th; real_inv_th]) [TREAL_ADD_SYM; TREAL_ADD_ASSOC; TREAL_ADD_LID; TREAL_ADD_LINV; TREAL_MUL_SYM; TREAL_MUL_ASSOC; TREAL_MUL_LID; TREAL_ADD_LDISTRIB; TREAL_LE_REFL; TREAL_LE_ANTISYM; TREAL_LE_TRANS; TREAL_LE_TOTAL; TREAL_LE_LADD_IMP; TREAL_LE_MUL; TREAL_INV_0; TREAL_MUL_LINV; TREAL_OF_NUM_EQ; TREAL_OF_NUM_LE; TREAL_OF_NUM_ADD; TREAL_OF_NUM_MUL];; (* ------------------------------------------------------------------------- *) (* Set up a friendly interface. *) (* ------------------------------------------------------------------------- *) parse_as_prefix "--";; parse_as_infix ("/",(22,"left"));; parse_as_infix ("pow",(24,"left"));; do_list overload_interface ["+",`real_add:real->real->real`; "-",`real_sub:real->real->real`; "*",`real_mul:real->real->real`; "/",`real_div:real->real->real`; "<",`real_lt:real->real->bool`; "<=",`real_le:real->real->bool`; ">",`real_gt:real->real->bool`; ">=",`real_ge:real->real->bool`; "--",`real_neg:real->real`; "pow",`real_pow:real->num->real`; "inv",`real_inv:real->real`; "abs",`real_abs:real->real`; "max",`real_max:real->real->real`; "min",`real_min:real->real->real`; "&",`real_of_num:num->real`];; let prioritize_real() = prioritize_overload(mk_type("real",[]));; (* ------------------------------------------------------------------------- *) (* Additional definitions. *) (* ------------------------------------------------------------------------- *) let real_sub = new_definition `x - y = x + --y`;; let real_lt = new_definition `x < y <=> ~(y <= x)`;; let real_ge = new_definition `x >= y <=> y <= x`;; let real_gt = new_definition `x > y <=> y < x`;; let real_abs = new_definition `abs(x) = if &0 <= x then x else --x`;; let real_pow = new_recursive_definition num_RECURSION `(x pow 0 = &1) /\ (!n. x pow (SUC n) = x * (x pow n))`;; let real_div = new_definition `x / y = x * inv(y)`;; let real_max = new_definition `real_max m n = if m <= n then n else m`;; let real_min = new_definition `real_min m n = if m <= n then m else n`;; (*----------------------------------------------------------------------------*) (* Derive the supremum property for an arbitrary bounded nonempty set *) (*----------------------------------------------------------------------------*) let REAL_HREAL_LEMMA1 = prove (`?r:hreal->real. (!x. &0 <= x <=> ?y. x = r y) /\ (!y z. y <= z <=> r y <= r z)`, EXISTS_TAC `\y. mk_real((treal_eq)(y,hreal_of_num 0))` THEN REWRITE_TAC[GSYM real_le_th] THEN REWRITE_TAC[treal_le; HREAL_ADD_LID; HREAL_ADD_RID] THEN GEN_TAC THEN EQ_TAC THENL [MP_TAC(INST [`dest_real x`,`r:hreal#hreal->bool`] (snd real_tybij)) THEN REWRITE_TAC[fst real_tybij] THEN DISCH_THEN(X_CHOOSE_THEN `p:hreal#hreal` MP_TAC) THEN DISCH_THEN(MP_TAC o AP_TERM `mk_real`) THEN REWRITE_TAC[fst real_tybij] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[GSYM real_of_num_th; GSYM real_le_th] THEN SUBST1_TAC(GSYM(ISPEC `p:hreal#hreal` PAIR)) THEN PURE_REWRITE_TAC[treal_of_num; treal_le] THEN PURE_REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_THEN(X_CHOOSE_THEN `d:hreal` SUBST1_TAC o MATCH_MP HREAL_LE_EXISTS) THEN EXISTS_TAC `d:hreal` THEN AP_TERM_TAC THEN ONCE_REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `q:hreal#hreal` THEN SUBST1_TAC(GSYM(ISPEC `q:hreal#hreal` PAIR)) THEN PURE_REWRITE_TAC[treal_eq] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_RID]; DISCH_THEN(CHOOSE_THEN SUBST1_TAC) THEN REWRITE_TAC[GSYM real_of_num_th; GSYM real_le_th] THEN REWRITE_TAC[treal_of_num; treal_le] THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN GEN_REWRITE_TAC RAND_CONV [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_LE_ADD]]);; let REAL_HREAL_LEMMA2 = prove (`?h r. (!x:hreal. h(r x) = x) /\ (!x. &0 <= x ==> (r(h x) = x)) /\ (!x:hreal. &0 <= r x) /\ (!x y. x <= y <=> r x <= r y)`, STRIP_ASSUME_TAC REAL_HREAL_LEMMA1 THEN EXISTS_TAC `\x:real. @y:hreal. x = r y` THEN EXISTS_TAC `r:hreal->real` THEN ASM_REWRITE_TAC[BETA_THM] THEN SUBGOAL_THEN `!y z. ((r:hreal->real) y = r z) <=> (y = z)` ASSUME_TAC THENL [ASM_REWRITE_TAC[GSYM REAL_LE_ANTISYM; GSYM HREAL_LE_ANTISYM]; ALL_TAC] THEN ASM_REWRITE_TAC[GEN_REWRITE_RULE (LAND_CONV o BINDER_CONV) [EQ_SYM_EQ] (SPEC_ALL SELECT_REFL); GSYM EXISTS_REFL] THEN GEN_TAC THEN DISCH_THEN(ACCEPT_TAC o SYM o SELECT_RULE));; let REAL_COMPLETE_SOMEPOS = prove (`!P. (?x. P x /\ &0 <= x) /\ (?M. !x. P x ==> x <= M) ==> ?M. (!x. P x ==> x <= M) /\ !M'. (!x. P x ==> x <= M') ==> M <= M'`, REPEAT STRIP_TAC THEN STRIP_ASSUME_TAC REAL_HREAL_LEMMA2 THEN MP_TAC(SPEC `\y:hreal. (P:real->bool)(r y)` HREAL_COMPLETE) THEN BETA_TAC THEN W(C SUBGOAL_THEN MP_TAC o funpow 2 (fst o dest_imp) o snd) THENL [CONJ_TAC THENL [EXISTS_TAC `(h:real->hreal) x` THEN UNDISCH_TAC `(P:real->bool) x` THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; EXISTS_TAC `(h:real->hreal) M` THEN X_GEN_TAC `y:hreal` THEN DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `x:real` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]; MATCH_MP_TAC(TAUT `(b ==> c) ==> a ==> (a ==> b) ==> c`) THEN DISCH_THEN(X_CHOOSE_THEN `B:hreal` STRIP_ASSUME_TAC)] THEN EXISTS_TAC `(r:hreal->real) B` THEN CONJ_TAC THENL [X_GEN_TAC `z:real` THEN DISCH_TAC THEN DISJ_CASES_TAC(SPECL [`&0`; `z:real`] REAL_LE_TOTAL) THENL [ANTE_RES_THEN(SUBST1_TAC o SYM) (ASSUME `&0 <= z`) THEN FIRST_ASSUM(fun th -> GEN_REWRITE_TAC I [GSYM th]) THEN FIRST_ASSUM MATCH_MP_TAC THEN UNDISCH_TAC `(P:real->bool) z` THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `&0` THEN ASM_REWRITE_TAC[]]; X_GEN_TAC `C:real` THEN DISCH_TAC THEN SUBGOAL_THEN `B:hreal <= (h(C:real))` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN SUBGOAL_THEN `(r:hreal->real)(h C) = C` (fun th -> ASM_REWRITE_TAC[th]); ASM_REWRITE_TAC[] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC] THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `x:real` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]);; let REAL_COMPLETE = prove (`!P. (?x. P x) /\ (?M. !x. P x ==> x <= M) ==> ?M. (!x. P x ==> x <= M) /\ !M'. (!x. P x ==> x <= M') ==> M <= M'`, let lemma = prove (`y = (y - x) + x`, REWRITE_TAC[real_sub; GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[REAL_ADD_LID]) in REPEAT STRIP_TAC THEN DISJ_CASES_TAC (SPECL [`&0`; `x:real`] REAL_LE_TOTAL) THENL [MATCH_MP_TAC REAL_COMPLETE_SOMEPOS THEN CONJ_TAC THENL [EXISTS_TAC `x:real`; EXISTS_TAC `M:real`] THEN ASM_REWRITE_TAC[]; FIRST_ASSUM(MP_TAC o MATCH_MP REAL_LE_LADD_IMP) THEN DISCH_THEN(MP_TAC o SPEC `--x`) THEN REWRITE_TAC[REAL_ADD_LINV] THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[REAL_ADD_LID] THEN DISCH_TAC THEN MP_TAC(SPEC `\y. P(y + x) :bool` REAL_COMPLETE_SOMEPOS) THEN BETA_TAC THEN W(C SUBGOAL_THEN MP_TAC o funpow 2 (fst o dest_imp) o snd) THENL [CONJ_TAC THENL [EXISTS_TAC `&0` THEN ASM_REWRITE_TAC[REAL_LE_REFL; REAL_ADD_LID]; EXISTS_TAC `M + --x` THEN GEN_TAC THEN DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN DISCH_THEN(MP_TAC o SPEC `--x` o MATCH_MP REAL_LE_LADD_IMP) THEN DISCH_THEN(MP_TAC o ONCE_REWRITE_RULE[REAL_ADD_SYM]) THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]; MATCH_MP_TAC(TAUT `(b ==> c) ==> a ==> (a ==> b) ==> c`) THEN DISCH_THEN(X_CHOOSE_THEN `B:real` STRIP_ASSUME_TAC)] THEN EXISTS_TAC `B + x` THEN CONJ_TAC THENL [GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [lemma] THEN DISCH_THEN(ANTE_RES_THEN (MP_TAC o SPEC `x:real` o MATCH_MP REAL_LE_LADD_IMP)) THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub; GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN ASM_REWRITE_TAC[]; REPEAT STRIP_TAC THEN SUBGOAL_THEN `B <= M' - x` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN X_GEN_TAC `z:real` THEN DISCH_TAC THEN SUBGOAL_THEN `z + x <= M'` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; DISCH_THEN(MP_TAC o SPEC `--x` o MATCH_MP REAL_LE_LADD_IMP) THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub] THEN MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]; DISCH_THEN(MP_TAC o SPEC `x:real` o MATCH_MP REAL_LE_LADD_IMP) THEN MATCH_MP_TAC EQ_IMP THEN BINOP_TAC THENL [MATCH_ACCEPT_TAC REAL_ADD_SYM; ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub] THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]]]]);; do_list reduce_interface ["+",`hreal_add:hreal->hreal->hreal`; "*",`hreal_mul:hreal->hreal->hreal`; "<=",`hreal_le:hreal->hreal->bool`; "inv",`hreal_inv:hreal->hreal`];; do_list remove_interface ["**"; "++"; "<<="; "==="; "fn"; "afn"];; print_endline "realax.ml loaded"
null
https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/azure/hol-light-nat/realax.ml
ocaml
========================================================================= Theory of real numbers. ========================================================================= ------------------------------------------------------------------------- The main infix overloaded operations ------------------------------------------------------------------------- ):num->num->num`; "<",`(<):num->num->bool`; "<=",`(<=):num->num->bool`; ">",`(>):num->num->bool`; ">=",`(>=):num->num->bool`];; let prioritize_num() = prioritize_overload(mk_type("num",[]));; (* ------------------------------------------------------------------------- Absolute distance function on the naturals. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Some easy theorems. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Simplifying theorem about the distance operation. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Now some more theorems. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Useful lemmas about bounds. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Define type of nearly additive functions. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Properties of nearly-additive functions. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Injection of the natural numbers. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Definition of (reflexive) ordering and the only special property needed. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Addition. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Basic properties of addition. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Multiplication. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Properties of multiplication. ------------------------------------------------------------------------- ------------------------------------------------------------------------- A few handy lemmas. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- A bit more on nearly-multiplicative functions. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Auxiliary function for the multiplicative inverse. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Now the multiplicative inverse proper. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Welldefinedness follows from already established principles because if ------------------------------------------------------------------------- ------------------------------------------------------------------------- Definition of the new type. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Consequential theorems needed later. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Define operations on representatives of signed reals. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Define the equivalence relation and prove it *is* one. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Useful to avoid unnecessary use of the equivalence relation. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Commutativity properties for injector. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Strong forms of equality are useful to simplify welldefinedness proofs. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Prove the properties of operations on representatives. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Show that the operations respect the equivalence relation. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Now define the quotient type -- the reals at last! ------------------------------------------------------------------------- ------------------------------------------------------------------------- Set up a friendly interface. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Additional definitions. ------------------------------------------------------------------------- ---------------------------------------------------------------------------- Derive the supremum property for an arbitrary bounded nonempty set ----------------------------------------------------------------------------
, University of Cambridge Computer Laboratory ( c ) Copyright , University of Cambridge 1998 ( c ) Copyright , 1998 - 2007 open Parser include Lists parse_as_infix("++",(16,"right"));; parse_as_infix("**",(20,"right"));; parse_as_infix("<<=",(12,"right"));; parse_as_infix("===",(10,"right"));; parse_as_infix ("treal_mul",(20,"right"));; parse_as_infix ("treal_add",(16,"right"));; parse_as_infix ("treal_le",(12,"right"));; parse_as_infix ("treal_eq",(10,"right"));; make_overloadable "+" `:A->A->A`;; make_overloadable "-" `:A->A->A`;; make_overloadable "*" `:A->A->A`;; make_overloadable "/" `:A->A->A`;; make_overloadable "<" `:A->A->bool`;; make_overloadable "<=" `:A->A->bool`;; make_overloadable ">" `:A->A->bool`;; make_overloadable ">=" `:A->A->bool`;; make_overloadable "--" `:A->A`;; make_overloadable "pow" `:A->num->A`;; make_overloadable "inv" `:A->A`;; make_overloadable "abs" `:A->A`;; make_overloadable "max" `:A->A->A`;; make_overloadable "min" `:A->A->A`;; make_overloadable "&" `:num->A`;; do_list overload_interface ["+",`(+):num->num->num`; "-",`(-):num->num->num`; let dist = new_definition `dist(m,n) = (m - n) + (n - m)`;; let DIST_REFL = prove (`!n. dist(n,n) = 0`, REWRITE_TAC[dist; SUB_REFL; ADD_CLAUSES]);; let DIST_LZERO = prove (`!n. dist(0,n) = n`, REWRITE_TAC[dist; SUB_0; ADD_CLAUSES]);; let DIST_RZERO = prove (`!n. dist(n,0) = n`, REWRITE_TAC[dist; SUB_0; ADD_CLAUSES]);; let DIST_SYM = prove (`!m n. dist(m,n) = dist(n,m)`, REWRITE_TAC[dist] THEN MATCH_ACCEPT_TAC ADD_SYM);; let DIST_LADD = prove (`!m p n. dist(m + n,m + p) = dist(n,p)`, REWRITE_TAC[dist; SUB_ADD_LCANCEL]);; let DIST_RADD = prove (`!m p n. dist(m + p,n + p) = dist(m,n)`, REWRITE_TAC[dist; SUB_ADD_RCANCEL]);; let DIST_LADD_0 = prove (`!m n. dist(m + n,m) = n`, REWRITE_TAC[dist; ADD_SUB2; ADD_SUBR2; ADD_CLAUSES]);; let DIST_RADD_0 = prove (`!m n. dist(m,m + n) = n`, ONCE_REWRITE_TAC[DIST_SYM] THEN MATCH_ACCEPT_TAC DIST_LADD_0);; let DIST_LMUL = prove (`!m n p. m * dist(n,p) = dist(m * n,m * p)`, REWRITE_TAC[dist; LEFT_ADD_DISTRIB; LEFT_SUB_DISTRIB]);; let DIST_RMUL = prove (`!m n p. dist(m,n) * p = dist(m * p,n * p)`, REWRITE_TAC[dist; RIGHT_ADD_DISTRIB; RIGHT_SUB_DISTRIB]);; let DIST_EQ_0 = prove (`!m n. (dist(m,n) = 0) <=> (m = n)`, REWRITE_TAC[dist; ADD_EQ_0; SUB_EQ_0; LE_ANTISYM]);; let DIST_ELIM_THM = prove (`P(dist(x,y)) <=> !d. ((x = y + d) ==> P(d)) /\ ((y = x + d) ==> P(d))`, DISJ_CASES_TAC(SPECL [`x:num`; `y:num`] LE_CASES) THEN POP_ASSUM(X_CHOOSE_THEN `e:num` SUBST1_TAC o REWRITE_RULE[LE_EXISTS]) THEN REWRITE_TAC[dist; ADD_SUB; ADD_SUB2; ADD_SUBR; ADD_SUBR2] THEN REWRITE_TAC[ADD_CLAUSES; EQ_ADD_LCANCEL] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [EQ_SYM_EQ] THEN REWRITE_TAC[GSYM ADD_ASSOC; EQ_ADD_LCANCEL_0; ADD_EQ_0] THEN ASM_CASES_TAC `e = 0` THEN ASM_REWRITE_TAC[] THEN EQ_TAC THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; let DIST_LE_CASES,DIST_ADDBOUND,DIST_TRIANGLE,DIST_ADD2,DIST_ADD2_REV = let DIST_ELIM_TAC = let conv = HIGHER_REWRITE_CONV[SUB_ELIM_THM; COND_ELIM_THM; DIST_ELIM_THM] false in CONV_TAC conv THEN TRY GEN_TAC THEN CONJ_TAC THEN DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN (let l,r = dest_eq (concl th) in if is_var l & not (vfree_in l r) then ALL_TAC else ASSUME_TAC th)) in let DIST_ELIM_TAC' = REPEAT STRIP_TAC THEN REPEAT DIST_ELIM_TAC THEN REWRITE_TAC[GSYM NOT_LT; LT_EXISTS] THEN DISCH_THEN(CHOOSE_THEN SUBST_ALL_TAC) THEN POP_ASSUM MP_TAC THEN CONV_TAC(LAND_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[ADD_CLAUSES; NOT_SUC] in let DIST_LE_CASES = prove (`!m n p. dist(m,n) <= p <=> (m <= n + p) /\ (n <= m + p)`, REPEAT GEN_TAC THEN REPEAT DIST_ELIM_TAC THEN REWRITE_TAC[GSYM ADD_ASSOC; LE_ADD; LE_ADD_LCANCEL]) and DIST_ADDBOUND = prove (`!m n. dist(m,n) <= m + n`, REPEAT GEN_TAC THEN DIST_ELIM_TAC THENL [ONCE_REWRITE_TAC[ADD_SYM]; ALL_TAC] THEN REWRITE_TAC[ADD_ASSOC; LE_ADDR]) and [DIST_TRIANGLE; DIST_ADD2; DIST_ADD2_REV] = (CONJUNCTS o prove) (`(!m n p. dist(m,p) <= dist(m,n) + dist(n,p)) /\ (!m n p q. dist(m + n,p + q) <= dist(m,p) + dist(n,q)) /\ (!m n p q. dist(m,p) <= dist(m + n,p + q) + dist(n,q))`, DIST_ELIM_TAC') in DIST_LE_CASES,DIST_ADDBOUND,DIST_TRIANGLE,DIST_ADD2,DIST_ADD2_REV;; let DIST_TRIANGLE_LE = prove (`!m n p q. dist(m,n) + dist(n,p) <= q ==> dist(m,p) <= q`, REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `dist(m,n) + dist(n,p)` THEN ASM_REWRITE_TAC[DIST_TRIANGLE]);; let DIST_TRIANGLES_LE = prove (`!m n p q r s. dist(m,n) <= r /\ dist(p,q) <= s ==> dist(m,p) <= dist(n,q) + r + s`, REPEAT STRIP_TAC THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `n:num` THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN REWRITE_TAC[GSYM ADD_ASSOC] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `q:num` THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN REWRITE_TAC[LE_ADD_LCANCEL] THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[]);; let BOUNDS_LINEAR = prove (`!A B C. (!n. A * n <= B * n + C) <=> A <= B`, REPEAT GEN_TAC THEN EQ_TAC THENL [CONV_TAC CONTRAPOS_CONV THEN REWRITE_TAC[NOT_LE] THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LT_EXISTS]) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN DISCH_THEN(MP_TAC o SPEC `SUC C`) THEN REWRITE_TAC[NOT_LE; MULT_CLAUSES; ADD_CLAUSES; LT_SUC_LE] THEN REWRITE_TAC[ADD_ASSOC; LE_ADDR]; DISCH_THEN(CHOOSE_THEN SUBST1_TAC o REWRITE_RULE[LE_EXISTS]) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]);; let BOUNDS_LINEAR_0 = prove (`!A B. (!n. A * n <= B) <=> (A = 0)`, REPEAT GEN_TAC THEN MP_TAC(SPECL [`A:num`; `0`; `B:num`] BOUNDS_LINEAR) THEN REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; LE]);; let BOUNDS_DIVIDED = prove (`!P. (?B. !n. P(n) <= B) <=> (?A B. !n. n * P(n) <= A * n + B)`, GEN_TAC THEN EQ_TAC THEN STRIP_TAC THENL [MAP_EVERY EXISTS_TAC [`B:num`; `0`] THEN GEN_TAC THEN REWRITE_TAC[ADD_CLAUSES] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; EXISTS_TAC `P(0) + A + B` THEN GEN_TAC THEN MP_TAC(SPECL [`n:num`; `(P:num->num) n`; `P(0) + A + B`] LE_MULT_LCANCEL) THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[LE_ADD] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [MULT_SYM] THEN REWRITE_TAC[GSYM ADD_ASSOC; LE_ADD_LCANCEL] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B * n` THEN REWRITE_TAC[LE_ADD] THEN UNDISCH_TAC `~(n = 0)` THEN SPEC_TAC(`n:num`,`n:num`) THEN INDUCT_TAC THEN ASM_REWRITE_TAC[MULT_CLAUSES; LE_ADD]]);; let BOUNDS_NOTZERO = prove (`!P A B. (P 0 0 = 0) /\ (!m n. P m n <= A * (m + n) + B) ==> (?B. !m n. P m n <= B * (m + n))`, REPEAT STRIP_TAC THEN EXISTS_TAC `A + B` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `m + n = 0` THENL [RULE_ASSUM_TAC(REWRITE_RULE[ADD_EQ_0]) THEN ASM_REWRITE_TAC[LE_0]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * (m + n) + B` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN UNDISCH_TAC `~(m + n = 0)` THEN SPEC_TAC(`m + n`,`p:num`) THEN INDUCT_TAC THEN REWRITE_TAC[MULT_CLAUSES; LE_ADD]]);; let BOUNDS_IGNORE = prove (`!P Q. (?B. !i. P(i) <= Q(i) + B) <=> (?B N. !i. N <= i ==> P(i) <= Q(i) + B)`, REPEAT GEN_TAC THEN EQ_TAC THEN STRIP_TAC THENL [EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]; POP_ASSUM MP_TAC THEN SPEC_TAC(`B:num`,`B:num`) THEN SPEC_TAC(`N:num`,`N:num`) THEN INDUCT_TAC THENL [REWRITE_TAC[LE_0] THEN GEN_TAC THEN DISCH_TAC THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]; GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN EXISTS_TAC `B + P(N:num)` THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN ASM_CASES_TAC `SUC N <= i` THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `Q(i:num) + B` THEN REWRITE_TAC[LE_ADD; ADD_ASSOC] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; UNDISCH_TAC `~(SUC N <= i)` THEN REWRITE_TAC[NOT_LE; LT] THEN ASM_REWRITE_TAC[GSYM NOT_LE] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[ADD_ASSOC] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[LE_ADD]]]]);; let is_nadd = new_definition `is_nadd x <=> (?B. !m n. dist(m * x(n),n * x(m)) <= B * (m + n))`;; let is_nadd_0 = prove (`is_nadd (\n. 0)`, REWRITE_TAC[is_nadd; MULT_CLAUSES; DIST_REFL; LE_0]);; let nadd_abs,nadd_rep = new_basic_type_definition "nadd" ("mk_nadd","dest_nadd") is_nadd_0;; override_interface ("fn",`dest_nadd`);; override_interface ("afn",`mk_nadd`);; let NADD_CAUCHY = prove (`!x. ?B. !m n. dist(m * fn x n,n * fn x m) <= B * (m + n)`, REWRITE_TAC[GSYM is_nadd; nadd_rep; nadd_abs; ETA_AX]);; let NADD_BOUND = prove (`!x. ?A B. !n. fn x n <= A * n + B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN MAP_EVERY EXISTS_TAC [`B + fn x 1`; `B:num`] THEN GEN_TAC THEN POP_ASSUM(MP_TAC o SPECL [`n:num`; `1`]) THEN REWRITE_TAC[DIST_LE_CASES; MULT_CLAUSES] THEN DISCH_THEN(MP_TAC o CONJUNCT2) THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; MULT_CLAUSES] THEN REWRITE_TAC[ADD_AC; MULT_AC]);; let NADD_MULTIPLICATIVE = prove (`!x. ?B. !m n. dist(fn x (m * n),m * fn x n) <= B * m + B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B + fn x 0` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `n = 0` THENL [MATCH_MP_TAC (LE_IMP DIST_ADDBOUND) THEN ASM_REWRITE_TAC[MULT_CLAUSES; RIGHT_ADD_DISTRIB; MULT_AC] THEN REWRITE_TAC[LE_EXISTS] THEN CONV_TAC(ONCE_DEPTH_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[GSYM EXISTS_REFL]; UNDISCH_TAC `~(n = 0)`] THEN REWRITE_TAC[TAUT `(~a ==> b) <=> a \/ b`; GSYM LE_MULT_LCANCEL; DIST_LMUL] THEN REWRITE_TAC[MULT_ASSOC] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN POP_ASSUM(MATCH_MP_TAC o LE_IMP) THEN REWRITE_TAC[LE_EXISTS; RIGHT_ADD_DISTRIB; LEFT_ADD_DISTRIB; MULT_AC] THEN CONV_TAC(ONCE_DEPTH_CONV NUM_CANCEL_CONV) THEN REWRITE_TAC[GSYM EXISTS_REFL]);; let NADD_ADDITIVE = prove (`!x. ?B. !m n. dist(fn x (m + n),fn x m + fn x n) <= B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN EXISTS_TAC `3 * B + fn x 0` THEN REPEAT GEN_TAC THEN ASM_CASES_TAC `m + n = 0` THENL [RULE_ASSUM_TAC(REWRITE_RULE[ADD_EQ_0]) THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[ADD_CLAUSES; DIST_LADD_0; LE_ADDR]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `3 * B` THEN REWRITE_TAC[LE_ADD] THEN UNDISCH_TAC `~(m + n = 0)`] THEN REWRITE_TAC[TAUT `(~a ==> b) <=> a \/ b`; GSYM LE_MULT_LCANCEL] THEN REWRITE_TAC[DIST_LMUL; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC(LE_IMP DIST_ADD2) THEN SUBGOAL_THEN `(m + n) * 3 * B = B * (m + m + n) + B * (n + m + n)` SUBST1_TAC THENL [REWRITE_TAC[SYM(REWRITE_CONV [ARITH] `1 + 1 + 1`)] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LEFT_ADD_DISTRIB; MULT_CLAUSES] THEN REWRITE_TAC[MULT_AC] THEN CONV_TAC NUM_CANCEL_CONV THEN REFL_TAC; MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]]);; let NADD_SUC = prove (`!x. ?B. !n. dist(fn x (SUC n),fn x n) <= B`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_ADDITIVE) THEN EXISTS_TAC `B + fn x 1` THEN GEN_TAC THEN MATCH_MP_TAC(LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x n + fn x 1` THEN ASM_REWRITE_TAC[ADD1] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[DIST_LADD_0; LE_REFL]);; let NADD_DIST_LEMMA = prove (`!x. ?B. !m n. dist(fn x (m + n),fn x m) <= B * n`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_SUC) THEN EXISTS_TAC `B:num` THEN GEN_TAC THEN INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; DIST_REFL; LE_0] THEN MATCH_MP_TAC(LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (m + n)` THEN REWRITE_TAC[ADD1; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[GSYM ADD1; MULT_CLAUSES]);; let NADD_DIST = prove (`!x. ?B. !m n. dist(fn x m,fn x n) <= B * dist(m,n)`, GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_DIST_LEMMA) THEN EXISTS_TAC `B:num` THEN REPEAT GEN_TAC THEN DISJ_CASES_THEN MP_TAC (SPECL [`m:num`; `n:num`] LE_CASES) THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o ONCE_REWRITE_RULE[LE_EXISTS]) THENL [ONCE_REWRITE_TAC[DIST_SYM]; ALL_TAC] THEN ASM_REWRITE_TAC[DIST_LADD_0]);; let NADD_ALTMUL = prove (`!x y. ?A B. !n. dist(n * fn x (fn y n),fn x n * fn y n) <= A * n + B`, REPEAT GEN_TAC THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN MP_TAC(SPEC `y:nadd` NADD_BOUND) THEN DISCH_THEN(X_CHOOSE_THEN `M:num` (X_CHOOSE_TAC `L:num`)) THEN MAP_EVERY EXISTS_TAC [`B * (1 + M)`; `B * L`] THEN GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o RAND_CONV) [MULT_SYM] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B * (n + fn y n)` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC[MULT_CLAUSES; GSYM ADD_ASSOC; LE_ADD_LCANCEL] THEN ASM_REWRITE_TAC[GSYM LEFT_ADD_DISTRIB; GSYM MULT_ASSOC; LE_MULT_LCANCEL]);; Definition of the equivalence relation and proof that it * is * one . override_interface ("===",`(nadd_eq):nadd->nadd->bool`);; let nadd_eq = new_definition `x === y <=> ?B. !n. dist(fn x n,fn y n) <= B`;; let NADD_EQ_REFL = prove (`!x. x === x`, GEN_TAC THEN REWRITE_TAC[nadd_eq; DIST_REFL; LE_0]);; let NADD_EQ_SYM = prove (`!x y. x === y <=> y === x`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [DIST_SYM] THEN REFL_TAC);; let NADD_EQ_TRANS = prove (`!x y z. x === y /\ y === z ==> x === z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn y n` THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; override_interface ("&",`nadd_of_num:num->nadd`);; let nadd_of_num = new_definition `&k = afn(\n. k * n)`;; let NADD_OF_NUM = prove (`!k. fn(&k) = \n. k * n`, REWRITE_TAC[nadd_of_num; GSYM nadd_rep; is_nadd] THEN REWRITE_TAC[DIST_REFL; LE_0; MULT_AC]);; let NADD_OF_NUM_WELLDEF = prove (`!m n. (m = n) ==> &m === &n`, REPEAT GEN_TAC THEN DISCH_THEN SUBST1_TAC THEN MATCH_ACCEPT_TAC NADD_EQ_REFL);; let NADD_OF_NUM_EQ = prove (`!m n. (&m === &n) <=> (m = n)`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[NADD_OF_NUM_WELLDEF] THEN REWRITE_TAC[nadd_eq; NADD_OF_NUM] THEN REWRITE_TAC[GSYM DIST_RMUL; BOUNDS_LINEAR_0; DIST_EQ_0]);; override_interface ("<<=",`nadd_le:nadd->nadd->bool`);; let nadd_le = new_definition `x <<= y <=> ?B. !n. fn x n <= fn y n + B`;; let NADD_LE_WELLDEF_LEMMA = prove (`!x x' y y'. x === x' /\ y === y' /\ x <<= y ==> x' <<= y'`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le] THEN REWRITE_TAC[DIST_LE_CASES; FORALL_AND_THM] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) MP_TAC) THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B2:num`) MP_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN EXISTS_TAC `(B2 + B) + B1` THEN X_GEN_TAC `n:num` THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP o CONJUNCT2) THEN REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL]);; let NADD_LE_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x <<= y <=> x' <<= y')`, REPEAT STRIP_TAC THEN EQ_TAC THEN DISCH_TAC THEN MATCH_MP_TAC NADD_LE_WELLDEF_LEMMA THEN ASM_REWRITE_TAC[] THENL [MAP_EVERY EXISTS_TAC [`x:nadd`; `y:nadd`]; MAP_EVERY EXISTS_TAC [`x':nadd`; `y':nadd`] THEN ONCE_REWRITE_TAC[NADD_EQ_SYM]] THEN ASM_REWRITE_TAC[]);; let NADD_LE_REFL = prove (`!x. x <<= x`, REWRITE_TAC[nadd_le; LE_ADD]);; let NADD_LE_TRANS = prove (`!x y z. x <<= y /\ y <<= z ==> x <<= z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) MP_TAC) THEN DISCH_THEN(X_CHOOSE_TAC `B2:num`) THEN EXISTS_TAC `B2 + B1` THEN GEN_TAC THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL]);; let NADD_LE_ANTISYM = prove (`!x y. x <<= y /\ y <<= x <=> (x === y)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; nadd_eq; DIST_LE_CASES] THEN EQ_TAC THENL [DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN GEN_TAC THEN CONJ_TAC THEN FIRST_ASSUM(MATCH_MP_TAC o LE_IMP) THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL; LE_ADD; LE_ADDR]; DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN CONJ_TAC THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]]);; let NADD_LE_TOTAL_LEMMA = prove (`!x y. ~(x <<= y) ==> !B. ?n. ~(n = 0) /\ fn y n + B < fn x n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NOT_FORALL_THM; NOT_EXISTS_THM] THEN REWRITE_TAC[NOT_LE] THEN DISCH_TAC THEN GEN_TAC THEN POP_ASSUM(X_CHOOSE_TAC `n:num` o SPEC `B + fn x 0`) THEN EXISTS_TAC `n:num` THEN POP_ASSUM MP_TAC THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[NOT_LT; ADD_ASSOC; LE_ADDR] THEN CONV_TAC CONTRAPOS_CONV THEN REWRITE_TAC[NOT_LT] THEN DISCH_THEN(MATCH_MP_TAC o LE_IMP) THEN REWRITE_TAC[ADD_ASSOC; LE_ADD]);; let NADD_LE_TOTAL = prove (`!x y. x <<= y \/ y <<= x`, REPEAT GEN_TAC THEN GEN_REWRITE_TAC I [TAUT `a <=> ~ ~ a`] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN PURE_ONCE_REWRITE_TAC[DE_MORGAN_THM] THEN DISCH_THEN(MP_TAC o end_itlist CONJ o map (MATCH_MP NADD_LE_TOTAL_LEMMA) o CONJUNCTS) THEN REWRITE_TAC[AND_FORALL_THM] THEN DISCH_THEN(MP_TAC o SPEC `B1 + B2`) THEN REWRITE_TAC[RIGHT_AND_EXISTS_THM] THEN REWRITE_TAC[LEFT_AND_EXISTS_THM] THEN DISCH_THEN(X_CHOOSE_THEN `m:num` (X_CHOOSE_THEN `n:num` MP_TAC)) THEN DISCH_THEN(MP_TAC o MATCH_MP (ITAUT `(~a /\ b) /\ (~c /\ d) ==> ~(c \/ ~b) /\ ~(a \/ ~d)`)) THEN REWRITE_TAC[NOT_LT; GSYM LE_MULT_LCANCEL] THEN REWRITE_TAC[NOT_LE] THEN DISCH_THEN(MP_TAC o MATCH_MP LT_ADD2) THEN REWRITE_TAC[NOT_LT] THEN REWRITE_TAC[LEFT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b + c) + (d + e + f) = (d + b + e) + (a + c + f)`] THEN MATCH_MP_TAC LE_ADD2 THEN REWRITE_TAC[GSYM RIGHT_ADD_DISTRIB] THEN CONJ_TAC THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [MULT_SYM] THEN RULE_ASSUM_TAC(REWRITE_RULE[DIST_LE_CASES]) THEN ASM_REWRITE_TAC[]);; let NADD_ARCH = prove (`!x. ?n. x <<= &n`, REWRITE_TAC[nadd_le; NADD_OF_NUM; NADD_BOUND]);; let NADD_OF_NUM_LE = prove (`!m n. (&m <<= &n) <=> m <= n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_OF_NUM] THEN REWRITE_TAC[BOUNDS_LINEAR]);; override_interface ("++",`nadd_add:nadd->nadd->nadd`);; let nadd_add = new_definition `x ++ y = afn(\n. fn x n + fn y n)`;; let NADD_ADD = prove (`!x y. fn(x ++ y) = \n. fn x n + fn y n`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_add; GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B1 + B2` THEN MAP_EVERY X_GEN_TAC [`m:num`; `n:num`] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC (LE_IMP DIST_ADD2) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; let NADD_ADD_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x ++ y === x' ++ y')`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `B1:num`) (X_CHOOSE_TAC `B2:num`)) THEN EXISTS_TAC `B1 + B2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC (LE_IMP DIST_ADD2) THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[]);; let NADD_ADD_SYM = prove (`!x y. (x ++ y) === (y ++ x)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_add] THEN GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [ADD_SYM] THEN REWRITE_TAC[NADD_EQ_REFL]);; let NADD_ADD_ASSOC = prove (`!x y z. (x ++ (y ++ z)) === ((x ++ y) ++ z)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[nadd_add] THEN REWRITE_TAC[NADD_ADD; ADD_ASSOC; NADD_EQ_REFL]);; let NADD_ADD_LID = prove (`!x. (&0 ++ x) === x`, GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD; NADD_OF_NUM] THEN REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES; DIST_REFL; LE_0]);; let NADD_ADD_LCANCEL = prove (`!x y z. (x ++ y) === (x ++ z) ==> y === z`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_ADD; DIST_LADD]);; let NADD_LE_ADD = prove (`!x y. x <<= (x ++ y)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_ADD] THEN EXISTS_TAC `0` THEN REWRITE_TAC[ADD_CLAUSES; LE_ADD]);; let NADD_LE_EXISTS = prove (`!x y. x <<= y ==> ?d. y === x ++ d`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le] THEN DISCH_THEN(X_CHOOSE_THEN `B:num` MP_TAC) THEN REWRITE_TAC[LE_EXISTS; SKOLEM_THM] THEN DISCH_THEN(X_CHOOSE_THEN `d:num->num` (ASSUME_TAC o GSYM)) THEN EXISTS_TAC `afn d` THEN REWRITE_TAC[nadd_eq; NADD_ADD] THEN EXISTS_TAC `B:num` THEN X_GEN_TAC `n:num` THEN SUBGOAL_THEN `fn(afn d) = d` SUBST1_TAC THENL [REWRITE_TAC[GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `B2:num` (SPEC `y:nadd` NADD_CAUCHY) THEN EXISTS_TAC `B1 + (B2 + B)` THEN REPEAT GEN_TAC THEN MATCH_MP_TAC(LE_IMP DIST_ADD2_REV) THEN MAP_EVERY EXISTS_TAC [`m * fn x n`; `n * fn x m`] THEN ONCE_REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_REWRITE_TAC[GSYM LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC(LE_IMP DIST_ADD2) THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [ADD_SYM] THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ASM_REWRITE_TAC[] THEN GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [MULT_SYM] THEN REWRITE_TAC[GSYM DIST_LMUL; DIST_ADDBOUND; LE_MULT_LCANCEL]; ASM_REWRITE_TAC[DIST_RADD_0; LE_REFL]]);; let NADD_OF_NUM_ADD = prove (`!m n. &m ++ &n === &(m + n)`, REWRITE_TAC[nadd_eq; NADD_OF_NUM; NADD_ADD] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; DIST_REFL; LE_0]);; override_interface ("**",`nadd_mul:nadd->nadd->nadd`);; let nadd_mul = new_definition `x ** y = afn(\n. fn x (fn y n))`;; let NADD_MUL = prove (`!x y. fn(x ** y) = \n. fn x (fn y n)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_mul; GSYM nadd_rep; is_nadd] THEN X_CHOOSE_TAC `B:num` (SPEC `y:nadd` NADD_CAUCHY) THEN X_CHOOSE_TAC `C:num` (SPEC `x:nadd` NADD_DIST) THEN X_CHOOSE_TAC `D:num` (SPEC `x:nadd` NADD_MULTIPLICATIVE) THEN MATCH_MP_TAC BOUNDS_NOTZERO THEN REWRITE_TAC[MULT_CLAUSES; DIST_REFL] THEN MAP_EVERY EXISTS_TAC [`D + C * B`; `D + D`] THEN REPEAT GEN_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(D * m + D) + (D * n + D) + C * B * (m + n)` THEN CONJ_TAC THENL [MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (m * fn y n)` THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x (n * fn y m)` THEN MATCH_MP_TAC LE_ADD2 THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `C * dist(m * fn y n,n * fn y m)` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; MATCH_MP_TAC EQ_IMP_LE THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; MULT_ASSOC; ADD_AC]]);; let NADD_MUL_SYM = prove (`!x y. (x ** y) === (y ** x)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN X_CHOOSE_THEN `A1:num` MP_TAC (SPECL [`x:nadd`; `y:nadd`] NADD_ALTMUL) THEN DISCH_THEN(X_CHOOSE_TAC `B1:num`) THEN X_CHOOSE_THEN `A2:num` MP_TAC (SPECL [`y:nadd`; `x:nadd`] NADD_ALTMUL) THEN DISCH_THEN(X_CHOOSE_TAC `B2:num`) THEN REWRITE_TAC[BOUNDS_DIVIDED] THEN REWRITE_TAC[DIST_LMUL] THEN MAP_EVERY EXISTS_TAC [`A1 + A2`; `B1 + B2`] THEN GEN_TAC THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b) + (c + d) = (a + c) + (b + d)`] THEN MATCH_MP_TAC (LE_IMP DIST_TRIANGLE) THEN EXISTS_TAC `fn x n * fn y n` THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN ONCE_REWRITE_TAC [DIST_SYM] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 RAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[]);; let NADD_MUL_ASSOC = prove (`!x y z. (x ** (y ** z)) === ((x ** y) ** z)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[nadd_mul] THEN REWRITE_TAC[NADD_MUL; NADD_EQ_REFL]);; let NADD_MUL_LID = prove (`!x. (&1 ** x) === x`, REWRITE_TAC[NADD_OF_NUM; nadd_mul; MULT_CLAUSES] THEN REWRITE_TAC[nadd_abs; NADD_EQ_REFL; ETA_AX]);; let NADD_LDISTRIB = prove (`!x y z. x ** (y ++ z) === (x ** y) ++ (x ** z)`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq] THEN REWRITE_TAC[NADD_ADD; NADD_MUL] THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_ADDITIVE) THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]);; let NADD_MUL_WELLDEF_LEMMA = prove (`!x y y'. y === y' ==> (x ** y) === (x ** y')`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN DISCH_THEN(X_CHOOSE_TAC `B1:num`) THEN X_CHOOSE_TAC `B2:num` (SPEC `x:nadd` NADD_DIST) THEN EXISTS_TAC `B2 * B1` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B2 * dist(fn y n,fn y' n)` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]);; let NADD_MUL_WELLDEF = prove (`!x x' y y'. x === x' /\ y === y' ==> (x ** y) === (x' ** y')`, REPEAT GEN_TAC THEN STRIP_TAC THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `x' ** y` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ** x'` THEN REWRITE_TAC[NADD_MUL_SYM] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ** x` THEN REWRITE_TAC[NADD_MUL_SYM]; ALL_TAC] THEN MATCH_MP_TAC NADD_MUL_WELLDEF_LEMMA THEN ASM_REWRITE_TAC[]);; let NADD_OF_NUM_MUL = prove (`!m n. &m ** &n === &(m * n)`, REWRITE_TAC[nadd_eq; NADD_OF_NUM; NADD_MUL] THEN REWRITE_TAC[MULT_ASSOC; DIST_REFL; LE_0]);; let NADD_LE_0 = prove (`!x. &0 <<= x`, GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_OF_NUM; MULT_CLAUSES; LE_0]);; let NADD_EQ_IMP_LE = prove (`!x y. x === y ==> x <<= y`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le; DIST_LE_CASES] THEN DISCH_THEN(X_CHOOSE_TAC `B:num`) THEN EXISTS_TAC `B:num` THEN ASM_REWRITE_TAC[]);; let NADD_LE_LMUL = prove (`!x y z. y <<= z ==> (x ** y) <<= (x ** z)`, REPEAT GEN_TAC THEN DISCH_THEN(X_CHOOSE_TAC `d:nadd` o MATCH_MP NADD_LE_EXISTS) THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `x ** y ++ x ** d` THEN REWRITE_TAC[NADD_LE_ADD] THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `x ** (y ++ d)` THEN ONCE_REWRITE_TAC[NADD_EQ_SYM] THEN REWRITE_TAC[NADD_LDISTRIB] THEN MATCH_MP_TAC NADD_MUL_WELLDEF THEN ASM_REWRITE_TAC[NADD_EQ_REFL]);; let NADD_LE_RMUL = prove (`!x y z. x <<= y ==> (x ** z) <<= (y ** z)`, MESON_TAC[NADD_LE_LMUL; NADD_LE_WELLDEF; NADD_MUL_SYM]);; let NADD_LE_RADD = prove (`!x y z. x ++ z <<= y ++ z <=> x <<= y`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_le; NADD_ADD] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o RAND_CONV) [ADD_SYM] THEN REFL_TAC);; let NADD_LE_LADD = prove (`!x y z. x ++ y <<= x ++ z <=> y <<= z`, MESON_TAC[NADD_LE_RADD; NADD_ADD_SYM; NADD_LE_WELLDEF]);; let NADD_RDISTRIB = prove (`!x y z. (x ++ y) ** z === x ** z ++ y ** z`, MESON_TAC[NADD_LDISTRIB; NADD_MUL_SYM; NADD_ADD_WELLDEF; NADD_EQ_TRANS; NADD_EQ_REFL; NADD_EQ_SYM]);; The property in a more useful form . let NADD_ARCH_MULT = prove (`!x k. ~(x === &0) ==> ?N. &k <<= &N ** x`, REPEAT GEN_TAC THEN REWRITE_TAC[nadd_eq; nadd_le; NOT_EXISTS_THM] THEN X_CHOOSE_TAC `B:num` (SPEC `x:nadd` NADD_CAUCHY) THEN DISCH_THEN(MP_TAC o SPEC `B + k`) THEN REWRITE_TAC[NOT_FORALL_THM; NADD_OF_NUM] THEN REWRITE_TAC[MULT_CLAUSES; DIST_RZERO; NOT_LE] THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN MAP_EVERY EXISTS_TAC [`N:num`; `B * N`] THEN X_GEN_TAC `i:num` THEN REWRITE_TAC[NADD_MUL; NADD_OF_NUM] THEN MATCH_MP_TAC(GEN_ALL(fst(EQ_IMP_RULE(SPEC_ALL LE_ADD_RCANCEL)))) THEN EXISTS_TAC `B * i` THEN REWRITE_TAC[GSYM ADD_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `i * fn x N` THEN RULE_ASSUM_TAC(REWRITE_RULE[DIST_LE_CASES]) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[GSYM RIGHT_ADD_DISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN REWRITE_TAC[LE_MULT_RCANCEL] THEN DISJ1_TAC THEN MATCH_MP_TAC LT_IMP_LE THEN ONCE_REWRITE_TAC[ADD_SYM] THEN FIRST_ASSUM ACCEPT_TAC);; let NADD_ARCH_ZERO = prove (`!x k. (!n. &n ** x <<= k) ==> (x === &0)`, REPEAT GEN_TAC THEN CONV_TAC CONTRAPOS_CONV THEN DISCH_TAC THEN REWRITE_TAC[NOT_FORALL_THM] THEN X_CHOOSE_TAC `p:num` (SPEC `k:nadd` NADD_ARCH) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(X_CHOOSE_TAC `N:num` o SPEC `p:num`) THEN EXISTS_TAC `N + 1` THEN DISCH_TAC THEN UNDISCH_TAC `~(x === &0)` THEN REWRITE_TAC[GSYM NADD_LE_ANTISYM; NADD_LE_0] THEN MATCH_MP_TAC(GEN_ALL(fst(EQ_IMP_RULE(SPEC_ALL NADD_LE_RADD)))) THEN EXISTS_TAC `&N ** x` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `k:nadd` THEN CONJ_TAC THENL [SUBGOAL_THEN `&(N + 1) ** x === x ++ &N ** x` MP_TAC THENL [ONCE_REWRITE_TAC[ADD_SYM] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `&1 ** x ++ &N ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&1 ++ &N) ** x` THEN CONJ_TAC THENL [MESON_TAC[NADD_OF_NUM_ADD; NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_EQ_SYM]; MESON_TAC[NADD_RDISTRIB; NADD_MUL_SYM; NADD_EQ_SYM; NADD_EQ_TRANS]]; MESON_TAC[NADD_ADD_WELLDEF; NADD_EQ_REFL; NADD_MUL_LID]]; ASM_MESON_TAC[NADD_LE_WELLDEF; NADD_EQ_REFL]]; ASM_MESON_TAC[NADD_LE_TRANS; NADD_LE_WELLDEF; NADD_EQ_REFL; NADD_ADD_LID]]);; let NADD_ARCH_LEMMA = prove (`!x y z. (!n. &n ** x <<= &n ** y ++ z) ==> x <<= y`, REPEAT STRIP_TAC THEN DISJ_CASES_TAC(SPECL [`x:nadd`; `y:nadd`] NADD_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM(X_CHOOSE_TAC `d:nadd` o MATCH_MP NADD_LE_EXISTS) THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ++ d` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `y ++ &0` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_ADD_WELLDEF THEN REWRITE_TAC[NADD_EQ_REFL] THEN MATCH_MP_TAC NADD_ARCH_ZERO THEN EXISTS_TAC `z:nadd` THEN ASM_MESON_TAC[NADD_MUL_WELLDEF; NADD_LE_WELLDEF; NADD_LDISTRIB; NADD_LE_LADD; NADD_EQ_REFL]; ASM_MESON_TAC[NADD_ADD_LID; NADD_ADD_WELLDEF; NADD_EQ_TRANS; NADD_ADD_SYM]]);; Completeness . let NADD_COMPLETE = prove (`!P. (?x. P x) /\ (?M. !x. P x ==> x <<= M) ==> ?M. (!x. P x ==> x <<= M) /\ !M'. (!x. P x ==> x <<= M') ==> M <<= M'`, GEN_TAC THEN DISCH_THEN (CONJUNCTS_THEN2 (X_CHOOSE_TAC `a:nadd`) (X_CHOOSE_TAC `m:nadd`)) THEN SUBGOAL_THEN `!n. ?r. (?x. P x /\ &r <<= &n ** x) /\ !r'. (?x. P x /\ &r' <<= &n ** x) ==> r' <= r` MP_TAC THENL [GEN_TAC THEN REWRITE_TAC[GSYM num_MAX] THEN CONJ_TAC THENL [MAP_EVERY EXISTS_TAC [`0`; `a:nadd`] THEN ASM_REWRITE_TAC[NADD_LE_0]; X_CHOOSE_TAC `N:num` (SPEC `m:nadd` NADD_ARCH) THEN EXISTS_TAC `n * N` THEN X_GEN_TAC `p:num` THEN DISCH_THEN(X_CHOOSE_THEN `w:nadd` STRIP_ASSUME_TAC) THEN ONCE_REWRITE_TAC[GSYM NADD_OF_NUM_LE] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** w` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &N` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_LMUL THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `m:nadd` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_ACCEPT_TAC NADD_OF_NUM_MUL]]; ONCE_REWRITE_TAC[SKOLEM_THM] THEN DISCH_THEN(X_CHOOSE_THEN `r:num->num` (fun th -> let th1,th2 = CONJ_PAIR(SPEC `n:num` th) in MAP_EVERY (MP_TAC o GEN `n:num`) [th1; th2])) THEN DISCH_THEN(MP_TAC o GEN `n:num` o SPECL [`n:num`; `SUC(r(n:num))`]) THEN REWRITE_TAC[LE_SUC_LT; LT_REFL; NOT_EXISTS_THM] THEN DISCH_THEN(ASSUME_TAC o GENL [`n:num`; `x:nadd`] o MATCH_MP (ITAUT `(a \/ b) /\ ~(c /\ b) ==> c ==> a`) o CONJ (SPECL [`&n ** x`; `&(SUC(r(n:num)))`] NADD_LE_TOTAL) o SPEC_ALL) THEN DISCH_TAC] THEN SUBGOAL_THEN `!n i. i * r(n) <= n * r(i) + n` ASSUME_TAC THENL [REPEAT GEN_TAC THEN FIRST_ASSUM(X_CHOOSE_THEN `x:nadd` STRIP_ASSUME_TAC o SPEC `n:num`) THEN ONCE_REWRITE_TAC[GSYM NADD_OF_NUM_LE] THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&i ** &n ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&i ** &(r(n:num))` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_IMP_LE THEN ONCE_REWRITE_TAC[NADD_EQ_SYM] THEN MATCH_ACCEPT_TAC NADD_OF_NUM_MUL; MATCH_MP_TAC NADD_LE_LMUL THEN ASM_REWRITE_TAC[]]; MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &(SUC(r(i:num)))` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** &i ** x` THEN CONJ_TAC THENL [MATCH_MP_TAC NADD_EQ_IMP_LE THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&i ** &n) ** x` THEN REWRITE_TAC[NADD_MUL_ASSOC] THEN MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC `(&n ** &i) ** x` THEN REWRITE_TAC[ONCE_REWRITE_RULE[NADD_EQ_SYM] NADD_MUL_ASSOC] THEN MATCH_MP_TAC NADD_MUL_WELLDEF THEN REWRITE_TAC[NADD_MUL_SYM; NADD_EQ_REFL]; MATCH_MP_TAC NADD_LE_LMUL THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]; ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[GSYM MULT_SUC] THEN MATCH_MP_TAC NADD_EQ_IMP_LE THEN REWRITE_TAC[NADD_OF_NUM_MUL]]]; ALL_TAC] THEN EXISTS_TAC `afn r` THEN SUBGOAL_THEN `fn(afn r) = r` ASSUME_TAC THENL [REWRITE_TAC[GSYM nadd_rep] THEN REWRITE_TAC[is_nadd; DIST_LE_CASES] THEN EXISTS_TAC `1` THEN REWRITE_TAC[MULT_CLAUSES] THEN REWRITE_TAC[FORALL_AND_THM] THEN GEN_REWRITE_TAC RAND_CONV [SWAP_FORALL_THM] THEN GEN_REWRITE_TAC (LAND_CONV o funpow 2 BINDER_CONV o funpow 2 RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[] THEN MAP_EVERY X_GEN_TAC [`i:num`; `n:num`] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n * r(i:num) + n` THEN ASM_REWRITE_TAC[ADD_ASSOC; LE_ADD]; ALL_TAC] THEN CONJ_TAC THENL [X_GEN_TAC `x:nadd` THEN DISCH_TAC THEN MATCH_MP_TAC NADD_ARCH_LEMMA THEN EXISTS_TAC `&2` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&(SUC(r(n:num)))` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; ASM_REWRITE_TAC[nadd_le; NADD_ADD; NADD_MUL; NADD_OF_NUM] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN REWRITE_TAC[ADD1; RIGHT_ADD_DISTRIB] THEN REWRITE_TAC[MULT_2; MULT_CLAUSES; ADD_ASSOC; LE_ADD_RCANCEL] THEN REWRITE_TAC[GSYM ADD_ASSOC] THEN ONCE_REWRITE_TAC[ADD_SYM] THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN MAP_EVERY EXISTS_TAC [`0`; `n:num`] THEN X_GEN_TAC `i:num` THEN DISCH_TAC THEN GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `n * r(i:num) + n` THEN ASM_REWRITE_TAC[LE_ADD_LCANCEL; ADD_CLAUSES]]; X_GEN_TAC `z:nadd` THEN DISCH_TAC THEN MATCH_MP_TAC NADD_ARCH_LEMMA THEN EXISTS_TAC `&1` THEN X_GEN_TAC `n:num` THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&(r(n:num)) ++ &1` THEN CONJ_TAC THENL [ASM_REWRITE_TAC[nadd_le; NADD_ADD; NADD_MUL; NADD_OF_NUM] THEN EXISTS_TAC `0` THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES] THEN GEN_TAC THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[]; REWRITE_TAC[NADD_LE_RADD] THEN FIRST_ASSUM(X_CHOOSE_THEN `x:nadd` MP_TAC o SPEC `n:num`) THEN DISCH_THEN STRIP_ASSUME_TAC THEN MATCH_MP_TAC NADD_LE_TRANS THEN EXISTS_TAC `&n ** x` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC NADD_LE_LMUL THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]]);; let NADD_UBOUND = prove (`!x. ?B N. !n. N <= n ==> fn x n <= B * n`, GEN_TAC THEN X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`) (SPEC `x:nadd` NADD_BOUND) THEN EXISTS_TAC `A1 + A2` THEN EXISTS_TAC `1` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A1 * n + A2` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN GEN_REWRITE_TAC LAND_CONV [GSYM(el 3 (CONJUNCTS MULT_CLAUSES))] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]);; let NADD_NONZERO = prove (`!x. ~(x === &0) ==> ?N. !n. N <= n ==> ~(fn x n = 0)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(MP_TAC o SPEC `1`) THEN REWRITE_TAC[nadd_le; NADD_MUL; NADD_OF_NUM; MULT_CLAUSES] THEN DISCH_THEN(X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`)) THEN EXISTS_TAC `A2 + 1` THEN X_GEN_TAC `n:num` THEN REPEAT DISCH_TAC THEN FIRST_ASSUM(UNDISCH_TAC o check is_forall o concl) THEN REWRITE_TAC[NOT_FORALL_THM; NOT_LE; GSYM LE_SUC_LT; ADD1] THEN EXISTS_TAC `n:num` THEN ASM_REWRITE_TAC[MULT_CLAUSES; ADD_CLAUSES]);; let NADD_LBOUND = prove (`!x. ~(x === &0) ==> ?A N. !n. N <= n ==> n <= A * fn x n`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(X_CHOOSE_TAC `N:num` o MATCH_MP NADD_NONZERO) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_ARCH_MULT) THEN DISCH_THEN(MP_TAC o SPEC `1`) THEN REWRITE_TAC[nadd_le; NADD_MUL; NADD_OF_NUM; MULT_CLAUSES] THEN DISCH_THEN(X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `A2:num`)) THEN EXISTS_TAC `A1 + A2` THEN EXISTS_TAC `N:num` THEN GEN_TAC THEN DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A1 * fn x n + A2` THEN ASM_REWRITE_TAC[RIGHT_ADD_DISTRIB; LE_ADD_LCANCEL] THEN GEN_REWRITE_TAC LAND_CONV [GSYM(el 3 (CONJUNCTS MULT_CLAUSES))] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN REWRITE_TAC[GSYM(REWRITE_CONV[ARITH_SUC] `SUC 0`)] THEN ASM_REWRITE_TAC[GSYM NOT_LT; LT]);; let nadd_rinv = new_definition `nadd_rinv(x) = \n. (n * n) DIV (fn x n)`;; let NADD_MUL_LINV_LEMMA0 = prove (`!x. ~(x === &0) ==> ?A B. !n. nadd_rinv x n <= A * n + B`, GEN_TAC THEN DISCH_TAC THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_LBOUND) THEN DISCH_THEN(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `N:num`)) THEN MAP_EVERY EXISTS_TAC [`A:num`; `0`; `SUC N`] THEN GEN_TAC THEN DISCH_TAC THEN REWRITE_TAC[ADD_CLAUSES] THEN MP_TAC(SPECL [`nadd_rinv x n`; `A * n`; `n:num`] LE_MULT_RCANCEL) THEN UNDISCH_TAC `SUC N <= n` THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[LE; NOT_SUC] THEN DISCH_TAC THEN DISCH_THEN(SUBST1_TAC o SYM) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `nadd_rinv x n * A * fn x n` THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL] THEN CONJ_TAC THENL [DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC N` THEN ASM_REWRITE_TAC[LE; LE_REFL]; GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN REWRITE_TAC[GSYM MULT_ASSOC; LE_MULT_LCANCEL] THEN DISJ2_TAC THEN ASM_CASES_TAC `fn x n = 0` THEN ASM_REWRITE_TAC[MULT_CLAUSES; LE_0; nadd_rinv] THEN FIRST_ASSUM(MP_TAC o MATCH_MP DIVISION) THEN DISCH_THEN(fun t -> GEN_REWRITE_TAC RAND_CONV [CONJUNCT1(SPEC_ALL t)]) THEN GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN REWRITE_TAC[LE_ADD]]);; let NADD_MUL_LINV_LEMMA1 = prove (`!x n. ~(fn x n = 0) ==> dist(fn x n * nadd_rinv(x) n, n * n) <= fn x n`, REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP DIVISION) THEN DISCH_THEN(CONJUNCTS_THEN2 SUBST1_TAC ASSUME_TAC o SPEC `n * n`) THEN REWRITE_TAC[nadd_rinv] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN REWRITE_TAC[DIST_RADD_0] THEN MATCH_MP_TAC LT_IMP_LE THEN FIRST_ASSUM MATCH_ACCEPT_TAC);; let NADD_MUL_LINV_LEMMA2 = prove (`!x. ~(x === &0) ==> ?N. !n. N <= n ==> dist(fn x n * nadd_rinv(x) n, n * n) <= fn x n`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_NONZERO) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC NADD_MUL_LINV_LEMMA1 THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; let NADD_MUL_LINV_LEMMA3 = prove (`!x. ~(x === &0) ==> ?N. !m n. N <= n ==> dist(m * fn x m * fn x n * nadd_rinv(x) n, m * fn x m * n * n) <= m * fn x m * fn x n`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA2) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN REWRITE_TAC[GSYM DIST_LMUL; MULT_ASSOC] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]);; let NADD_MUL_LINV_LEMMA4 = prove (`!x. ~(x === &0) ==> ?N. !m n. N <= m /\ N <= n ==> (fn x m * fn x n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= (m * n) * dist(m * fn x n,n * fn x m) + (fn x m * fn x n) * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA3) THEN DISCH_THEN(X_CHOOSE_TAC `N:num`) THEN EXISTS_TAC `N:num` THEN REPEAT STRIP_TAC THEN REWRITE_TAC[DIST_LMUL; LEFT_ADD_DISTRIB] THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV) [DIST_SYM] THEN MATCH_MP_TAC DIST_TRIANGLES_LE THEN CONJ_TAC THENL [ANTE_RES_THEN(MP_TAC o SPEC `m:num`) (ASSUME `N <= n`); ANTE_RES_THEN(MP_TAC o SPEC `n:num`) (ASSUME `N <= m`)] THEN MATCH_MP_TAC EQ_IMP THEN REWRITE_TAC[MULT_AC]);; let NADD_MUL_LINV_LEMMA5 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> (fn x m * fn x n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m * n) * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA4) THEN DISCH_THEN(X_CHOOSE_TAC `N1:num`) THEN X_CHOOSE_TAC `B1:num` (SPEC `x:nadd` NADD_CAUCHY) THEN X_CHOOSE_THEN `B2:num` (X_CHOOSE_TAC `N2:num`) (SPEC `x:nadd` NADD_UBOUND) THEN EXISTS_TAC `B1 + B2 * B2` THEN EXISTS_TAC `N1 + N2` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(m * n) * dist(m * fn x n,n * fn x m) + (fn x m * fn x n) * (m + n)` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]; REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN MATCH_MP_TAC LE_ADD2] THEN CONJ_TAC THENL [GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN GEN_REWRITE_TAC RAND_CONV [GSYM MULT_ASSOC] THEN GEN_REWRITE_TAC (funpow 2 RAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; ONCE_REWRITE_TAC[AC MULT_AC `(a * b) * (c * d) * e = ((a * c) * (b * d)) * e`] THEN REWRITE_TAC[LE_MULT_RCANCEL] THEN DISJ1_TAC THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]]);; let NADD_MUL_LINV_LEMMA6 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> (m * n) * dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m * n) * (m + n)`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA5) THEN DISCH_THEN(X_CHOOSE_THEN `B1:num` (X_CHOOSE_TAC `N1:num`)) THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_LBOUND) THEN DISCH_THEN(X_CHOOSE_THEN `B2:num` (X_CHOOSE_TAC `N2:num`)) THEN EXISTS_TAC `B1 * B2 * B2` THEN EXISTS_TAC `N1 + N2` THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `(B2 * B2) * (fn x m * fn x n) * dist (m * nadd_rinv x n,n * nadd_rinv x m)` THEN CONJ_TAC THENL [REWRITE_TAC[MULT_ASSOC; LE_MULT_RCANCEL] THEN DISJ1_TAC THEN ONCE_REWRITE_TAC[AC MULT_AC `((a * b) * c) * d = (a * c) * (b * d)`] THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN FIRST_ASSUM MATCH_MP_TAC; ONCE_REWRITE_TAC[AC MULT_AC `(a * b * c) * (d * e) * f = (b * c) * (a * (d * e) * f)`] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISJ2_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN CONJ_TAC] THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N1 + N2` THEN ASM_REWRITE_TAC[LE_ADD; LE_ADDR]);; let NADD_MUL_LINV_LEMMA7 = prove (`!x. ~(x === &0) ==> ?B N. !m n. N <= m /\ N <= n ==> dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m + n)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA6) THEN DISCH_THEN(X_CHOOSE_THEN `B:num` (X_CHOOSE_TAC `N:num`)) THEN MAP_EVERY EXISTS_TAC [`B:num`; `N + 1`] THEN MAP_EVERY X_GEN_TAC [`m:num`; `n:num`] THEN STRIP_TAC THEN SUBGOAL_THEN `N <= m /\ N <= n` MP_TAC THENL [CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N + 1` THEN ASM_REWRITE_TAC[LE_ADD]; DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN ONCE_REWRITE_TAC[AC MULT_AC `a * b * c = b * a * c`] THEN REWRITE_TAC[LE_MULT_LCANCEL] THEN DISCH_THEN(DISJ_CASES_THEN2 MP_TAC ACCEPT_TAC) THEN CONV_TAC CONTRAPOS_CONV THEN DISCH_THEN(K ALL_TAC) THEN ONCE_REWRITE_TAC[GSYM(CONJUNCT1 LE)] THEN REWRITE_TAC[NOT_LE; GSYM LE_SUC_LT] THEN REWRITE_TAC[EQT_ELIM(REWRITE_CONV[ARITH] `SUC 0 = 1 * 1`)] THEN MATCH_MP_TAC LE_MULT2 THEN CONJ_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `N + 1` THEN ASM_REWRITE_TAC[LE_ADDR]]);; let NADD_MUL_LINV_LEMMA7a = prove (`!x. ~(x === &0) ==> !N. ?A B. !m n. m <= N ==> dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= A * n + B`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA0) THEN DISCH_THEN(X_CHOOSE_THEN `A0:num` (X_CHOOSE_TAC `B0:num`)) THEN INDUCT_TAC THENL [MAP_EVERY EXISTS_TAC [`nadd_rinv x 0`; `0`] THEN REPEAT GEN_TAC THEN REWRITE_TAC[LE] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[MULT_CLAUSES; DIST_LZERO; ADD_CLAUSES] THEN GEN_REWRITE_TAC RAND_CONV [MULT_SYM] THEN MATCH_ACCEPT_TAC LE_REFL; FIRST_ASSUM(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `B:num`)) THEN EXISTS_TAC `A + (nadd_rinv(x)(SUC N) + SUC N * A0)` THEN EXISTS_TAC `SUC N * B0 + B` THEN REPEAT GEN_TAC THEN REWRITE_TAC[LE] THEN DISCH_THEN(DISJ_CASES_THEN2 SUBST1_TAC ASSUME_TAC) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `SUC N * nadd_rinv x n + n * nadd_rinv x (SUC N)` THEN REWRITE_TAC[DIST_ADDBOUND] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b + c) + d + e = (c + d) + (b + a + e)`] THEN MATCH_MP_TAC LE_ADD2 THEN CONJ_TAC THENL [REWRITE_TAC[GSYM MULT_ASSOC; GSYM LEFT_ADD_DISTRIB] THEN ASM_REWRITE_TAC[LE_MULT_LCANCEL]; GEN_REWRITE_TAC LAND_CONV [MULT_SYM] THEN MATCH_ACCEPT_TAC LE_ADD]; MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; REWRITE_TAC[ADD_ASSOC; LE_ADD_RCANCEL] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]]]);; let NADD_MUL_LINV_LEMMA8 = prove (`!x. ~(x === &0) ==> ?B. !m n. dist(m * nadd_rinv(x) n,n * nadd_rinv(x) m) <= B * (m + n)`, GEN_TAC THEN DISCH_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP NADD_MUL_LINV_LEMMA7) THEN DISCH_THEN(X_CHOOSE_THEN `B0:num` (X_CHOOSE_TAC `N:num`)) THEN FIRST_ASSUM(MP_TAC o SPEC `N:num` o MATCH_MP NADD_MUL_LINV_LEMMA7a) THEN DISCH_THEN(X_CHOOSE_THEN `A:num` (X_CHOOSE_TAC `B:num`)) THEN MATCH_MP_TAC BOUNDS_NOTZERO THEN REWRITE_TAC[DIST_REFL] THEN EXISTS_TAC `A + B0` THEN EXISTS_TAC `B:num` THEN REPEAT GEN_TAC THEN DISJ_CASES_THEN2 ASSUME_TAC MP_TAC (SPECL [`N:num`; `m:num`] LE_CASES) THENL [DISJ_CASES_THEN2 ASSUME_TAC MP_TAC (SPECL [`N:num`; `n:num`] LE_CASES) THENL [MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `B0 * (m + n)` THEN CONJ_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; GEN_REWRITE_TAC (RAND_CONV o funpow 2 LAND_CONV) [ADD_SYM] THEN REWRITE_TAC[RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]; DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * m + B` THEN ONCE_REWRITE_TAC[DIST_SYM] THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]; DISCH_THEN(ANTE_RES_THEN ASSUME_TAC) THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `A * n + B` THEN ASM_REWRITE_TAC[LE_ADD_RCANCEL] THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [ADD_SYM] THEN REWRITE_TAC[LEFT_ADD_DISTRIB; RIGHT_ADD_DISTRIB; GSYM ADD_ASSOC; LE_ADD]]);; let nadd_inv = new_definition `nadd_inv(x) = if x === &0 then &0 else afn(nadd_rinv x)`;; override_interface ("inv",`nadd_inv:nadd->nadd`);; let NADD_INV = prove (`!x. fn(nadd_inv x) = if x === &0 then (\n. 0) else nadd_rinv x`, GEN_TAC THEN REWRITE_TAC[nadd_inv] THEN ASM_CASES_TAC `x === &0` THEN ASM_REWRITE_TAC[NADD_OF_NUM; MULT_CLAUSES] THEN REWRITE_TAC[GSYM nadd_rep; is_nadd] THEN MATCH_MP_TAC NADD_MUL_LINV_LEMMA8 THEN POP_ASSUM ACCEPT_TAC);; let NADD_MUL_LINV = prove (`!x. ~(x === &0) ==> inv(x) ** x === &1`, GEN_TAC THEN DISCH_TAC THEN REWRITE_TAC[nadd_eq; NADD_MUL] THEN ONCE_REWRITE_TAC[BOUNDS_DIVIDED] THEN X_CHOOSE_THEN `A1:num` (X_CHOOSE_TAC `B1:num`) (SPECL [`inv(x)`; `x:nadd`] NADD_ALTMUL) THEN REWRITE_TAC[DIST_LMUL; NADD_OF_NUM; MULT_CLAUSES] THEN FIRST_ASSUM(X_CHOOSE_TAC `N:num` o MATCH_MP NADD_MUL_LINV_LEMMA2) THEN X_CHOOSE_THEN `A':num` (X_CHOOSE_TAC `B':num`) (SPEC `x:nadd` NADD_BOUND) THEN SUBGOAL_THEN `?A2 B2. !n. dist(fn x n * nadd_rinv x n,n * n) <= A2 * n + B2` STRIP_ASSUME_TAC THENL [EXISTS_TAC `A':num` THEN ONCE_REWRITE_TAC[BOUNDS_IGNORE] THEN MAP_EVERY EXISTS_TAC [`B':num`; `N:num`] THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LE_TRANS THEN EXISTS_TAC `fn x n` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MAP_EVERY EXISTS_TAC [`A1 + A2`; `B1 + B2`] THEN GEN_TAC THEN MATCH_MP_TAC DIST_TRIANGLE_LE THEN EXISTS_TAC `fn (inv x) n * fn x n` THEN REWRITE_TAC[RIGHT_ADD_DISTRIB] THEN ONCE_REWRITE_TAC[AC ADD_AC `(a + b) + c + d = (a + c) + (b + d)`] THEN MATCH_MP_TAC LE_ADD2 THEN ASM_REWRITE_TAC[] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV o LAND_CONV) [MULT_SYM] THEN ASM_REWRITE_TAC[NADD_INV]]);; let NADD_INV_0 = prove (`inv(&0) === &0`, REWRITE_TAC[nadd_inv; NADD_EQ_REFL]);; x = y then y ' = y ' 1 = y ' ( x ' x ) = y ' ( x ' y ) = ( y ' y ) x ' = 1 x ' = x ' let NADD_INV_WELLDEF = prove (`!x y. x === y ==> inv(x) === inv(y)`, let TAC tm ths = MATCH_MP_TAC NADD_EQ_TRANS THEN EXISTS_TAC tm THEN CONJ_TAC THENL [ALL_TAC; ASM_MESON_TAC ths] in REPEAT STRIP_TAC THEN ASM_CASES_TAC `x === &0` THENL [SUBGOAL_THEN `y === &0` ASSUME_TAC THENL [ASM_MESON_TAC[NADD_EQ_TRANS; NADD_EQ_SYM]; ASM_REWRITE_TAC[nadd_inv; NADD_EQ_REFL]]; SUBGOAL_THEN `~(y === &0)` ASSUME_TAC THENL [ASM_MESON_TAC[NADD_EQ_TRANS; NADD_EQ_SYM]; ALL_TAC]] THEN TAC `inv(y) ** &1` [NADD_MUL_SYM; NADD_MUL_LID; NADD_EQ_TRANS] THEN TAC `inv(y) ** (inv(x) ** x)` [NADD_MUL_LINV; NADD_MUL_WELLDEF; NADD_EQ_REFL] THEN TAC `inv(y) ** (inv(x) ** y)` [NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_EQ_SYM] THEN TAC `(inv(y) ** y) ** inv(x)` [NADD_MUL_ASSOC; NADD_MUL_SYM; NADD_EQ_TRANS; NADD_MUL_WELLDEF; NADD_EQ_REFL] THEN ASM_MESON_TAC[NADD_MUL_LINV; NADD_MUL_WELLDEF; NADD_EQ_REFL; NADD_MUL_LID; NADD_EQ_TRANS; NADD_EQ_SYM]);; let hreal_tybij = define_quotient_type "hreal" ("mk_hreal","dest_hreal") `(===)`;; do_list overload_interface ["+",`hreal_add:hreal->hreal->hreal`; "*",`hreal_mul:hreal->hreal->hreal`; "<=",`hreal_le:hreal->hreal->bool`];; do_list override_interface ["&",`hreal_of_num:num->hreal`; "inv",`hreal_inv:hreal->hreal`];; let hreal_of_num,hreal_of_num_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_of_num" NADD_OF_NUM_WELLDEF;; let hreal_add,hreal_add_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_add" NADD_ADD_WELLDEF;; let hreal_mul,hreal_mul_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_mul" NADD_MUL_WELLDEF;; let hreal_le,hreal_le_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_le" NADD_LE_WELLDEF;; let hreal_inv,hreal_inv_th = lift_function (snd hreal_tybij) (NADD_EQ_REFL,NADD_EQ_TRANS) "hreal_inv" NADD_INV_WELLDEF;; let HREAL_COMPLETE = let th1 = ASSUME `(P:nadd->bool) = (\x. Q(mk_hreal((===) x)))` in let th2 = BETA_RULE(AP_THM th1 `x:nadd`) in let th3 = lift_theorem hreal_tybij (NADD_EQ_REFL,NADD_EQ_SYM,NADD_EQ_TRANS) [hreal_of_num_th; hreal_add_th; hreal_mul_th; hreal_le_th; th2] (SPEC_ALL NADD_COMPLETE) in let th4 = MATCH_MP (DISCH_ALL th3) (REFL `\x. Q(mk_hreal((===) x)):bool`) in CONV_RULE(GEN_ALPHA_CONV `P:hreal->bool`) (GEN_ALL th4);; let [HREAL_OF_NUM_EQ; HREAL_OF_NUM_LE; HREAL_OF_NUM_ADD; HREAL_OF_NUM_MUL; HREAL_LE_REFL; HREAL_LE_TRANS; HREAL_LE_ANTISYM; HREAL_LE_TOTAL; HREAL_LE_ADD; HREAL_LE_EXISTS; HREAL_ARCH; HREAL_ADD_SYM; HREAL_ADD_ASSOC; HREAL_ADD_LID; HREAL_ADD_LCANCEL; HREAL_MUL_SYM; HREAL_MUL_ASSOC; HREAL_MUL_LID; HREAL_ADD_LDISTRIB; HREAL_MUL_LINV; HREAL_INV_0] = map (lift_theorem hreal_tybij (NADD_EQ_REFL,NADD_EQ_SYM,NADD_EQ_TRANS) [hreal_of_num_th; hreal_add_th; hreal_mul_th; hreal_le_th; hreal_inv_th]) [NADD_OF_NUM_EQ; NADD_OF_NUM_LE; NADD_OF_NUM_ADD; NADD_OF_NUM_MUL; NADD_LE_REFL; NADD_LE_TRANS; NADD_LE_ANTISYM; NADD_LE_TOTAL; NADD_LE_ADD; NADD_LE_EXISTS; NADD_ARCH; NADD_ADD_SYM; NADD_ADD_ASSOC; NADD_ADD_LID; NADD_ADD_LCANCEL; NADD_MUL_SYM; NADD_MUL_ASSOC; NADD_MUL_LID; NADD_LDISTRIB; NADD_MUL_LINV; NADD_INV_0];; let HREAL_LE_EXISTS_DEF = prove (`!m n. m <= n <=> ?d. n = m + d`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS] THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC) THEN REWRITE_TAC[HREAL_LE_ADD]);; let HREAL_EQ_ADD_LCANCEL = prove (`!m n p. (m + n = m + p) <=> (n = p)`, REPEAT GEN_TAC THEN EQ_TAC THEN REWRITE_TAC[HREAL_ADD_LCANCEL] THEN DISCH_THEN SUBST1_TAC THEN REFL_TAC);; let HREAL_EQ_ADD_RCANCEL = prove (`!m n p. (m + p = n + p) <=> (m = n)`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL]);; let HREAL_LE_ADD_LCANCEL = prove (`!m n p. (m + n <= m + p) <=> (n <= p)`, REWRITE_TAC[HREAL_LE_EXISTS_DEF; GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL]);; let HREAL_LE_ADD_RCANCEL = prove (`!m n p. (m + p <= n + p) <=> (m <= n)`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN MATCH_ACCEPT_TAC HREAL_LE_ADD_LCANCEL);; let HREAL_ADD_RID = prove (`!n. n + &0 = n`, ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN MATCH_ACCEPT_TAC HREAL_ADD_LID);; let HREAL_ADD_RDISTRIB = prove (`!m n p. (m + n) * p = m * p + n * p`, ONCE_REWRITE_TAC[HREAL_MUL_SYM] THEN MATCH_ACCEPT_TAC HREAL_ADD_LDISTRIB);; let HREAL_MUL_LZERO = prove (`!m. &0 * m = &0`, GEN_TAC THEN MP_TAC(SPECL [`&0`; `&1`; `m:hreal`] HREAL_ADD_RDISTRIB) THEN REWRITE_TAC[HREAL_ADD_LID] THEN GEN_REWRITE_TAC (funpow 2 LAND_CONV) [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL] THEN DISCH_THEN(ACCEPT_TAC o SYM));; let HREAL_MUL_RZERO = prove (`!m. m * &0 = &0`, ONCE_REWRITE_TAC[HREAL_MUL_SYM] THEN MATCH_ACCEPT_TAC HREAL_MUL_LZERO);; let HREAL_ADD_AC = prove (`(m + n = n + m) /\ ((m + n) + p = m + (n + p)) /\ (m + (n + p) = n + (m + p))`, REWRITE_TAC[HREAL_ADD_ASSOC; EQT_INTRO(SPEC_ALL HREAL_ADD_SYM)] THEN AP_THM_TAC THEN AP_TERM_TAC THEN MATCH_ACCEPT_TAC HREAL_ADD_SYM);; let HREAL_LE_ADD2 = prove (`!a b c d. a <= b /\ c <= d ==> a + c <= b + d`, REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS_DEF] THEN DISCH_THEN(CONJUNCTS_THEN2 (X_CHOOSE_TAC `d1:hreal`) (X_CHOOSE_TAC `d2:hreal`)) THEN EXISTS_TAC `d1 + d2` THEN ASM_REWRITE_TAC[HREAL_ADD_AC]);; let HREAL_LE_MUL_RCANCEL_IMP = prove (`!a b c. a <= b ==> a * c <= b * c`, REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_LE_EXISTS_DEF] THEN DISCH_THEN(X_CHOOSE_THEN `d:hreal` SUBST1_TAC) THEN EXISTS_TAC `d * c` THEN REWRITE_TAC[HREAL_ADD_RDISTRIB]);; let treal_of_num = new_definition `treal_of_num n = (&n, &0)`;; let treal_neg = new_definition `treal_neg ((x:hreal),(y:hreal)) = (y,x)`;; let treal_add = new_definition `(x1,y1) treal_add (x2,y2) = (x1 + x2, y1 + y2)`;; let treal_mul = new_definition `(x1,y1) treal_mul (x2,y2) = ((x1 * x2) + (y1 * y2),(x1 * y2) + (y1 * x2))`;; let treal_le = new_definition `(x1,y1) treal_le (x2,y2) <=> x1 + y2 <= x2 + y1`;; let treal_inv = new_definition `treal_inv(x,y) = if x = y then (&0, &0) else if y <= x then (inv(@d. x = y + d), &0) else (&0, inv(@d. y = x + d))`;; let treal_eq = new_definition `(x1,y1) treal_eq (x2,y2) <=> (x1 + y2 = x2 + y1)`;; let TREAL_EQ_REFL = prove (`!x. x treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq]);; let TREAL_EQ_SYM = prove (`!x y. x treal_eq y <=> y treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq; EQ_SYM_EQ]);; let TREAL_EQ_TRANS = prove (`!x y z. x treal_eq y /\ y treal_eq z ==> x treal_eq z`, REWRITE_TAC[FORALL_PAIR_THM; treal_eq] THEN REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MK_COMB o (AP_TERM `(+)` F_F I) o CONJ_PAIR) THEN GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_ASSOC; HREAL_EQ_ADD_RCANCEL] THEN DISCH_THEN(MATCH_ACCEPT_TAC o ONCE_REWRITE_RULE[HREAL_ADD_SYM]));; let TREAL_EQ_AP = prove (`!x y. (x = y) ==> x treal_eq y`, SIMP_TAC[TREAL_EQ_REFL]);; let TREAL_OF_NUM_EQ = prove (`!m n. (treal_of_num m treal_eq treal_of_num n) <=> (m = n)`, REWRITE_TAC[treal_of_num; treal_eq; HREAL_OF_NUM_EQ; HREAL_ADD_RID]);; let TREAL_OF_NUM_LE = prove (`!m n. (treal_of_num m treal_le treal_of_num n) <=> m <= n`, REWRITE_TAC[treal_of_num; treal_le; HREAL_OF_NUM_LE; HREAL_ADD_RID]);; let TREAL_OF_NUM_ADD = prove (`!m n. (treal_of_num m treal_add treal_of_num n) treal_eq (treal_of_num(m + n))`, REWRITE_TAC[treal_of_num; treal_eq; treal_add; HREAL_OF_NUM_ADD; HREAL_ADD_RID; ADD_CLAUSES]);; let TREAL_OF_NUM_MUL = prove (`!m n. (treal_of_num m treal_mul treal_of_num n) treal_eq (treal_of_num(m * n))`, REWRITE_TAC[treal_of_num; treal_eq; treal_mul; HREAL_OF_NUM_MUL; HREAL_MUL_RZERO; HREAL_MUL_LZERO; HREAL_ADD_RID; HREAL_ADD_LID; HREAL_ADD_RID; MULT_CLAUSES]);; let TREAL_ADD_SYM_EQ = prove (`!x y. x treal_add y = y treal_add x`, REWRITE_TAC[FORALL_PAIR_THM; treal_add; PAIR_EQ; HREAL_ADD_SYM]);; let TREAL_MUL_SYM_EQ = prove (`!x y. x treal_mul y = y treal_mul x`, REWRITE_TAC[FORALL_PAIR_THM; treal_mul; HREAL_MUL_SYM; HREAL_ADD_SYM]);; let TREAL_ADD_SYM = prove (`!x y. (x treal_add y) treal_eq (y treal_add x)`, REPEAT GEN_TAC THEN MATCH_MP_TAC TREAL_EQ_AP THEN MATCH_ACCEPT_TAC TREAL_ADD_SYM_EQ);; let TREAL_ADD_ASSOC = prove (`!x y z. (x treal_add (y treal_add z)) treal_eq ((x treal_add y) treal_add z)`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_add; HREAL_ADD_ASSOC]);; let TREAL_ADD_LID = prove (`!x. ((treal_of_num 0) treal_add x) treal_eq x`, REWRITE_TAC[FORALL_PAIR_THM; treal_of_num; treal_add; treal_eq; HREAL_ADD_LID]);; let TREAL_ADD_LINV = prove (`!x. ((treal_neg x) treal_add x) treal_eq (treal_of_num 0)`, REWRITE_TAC[FORALL_PAIR_THM; treal_neg; treal_add; treal_eq; treal_of_num; HREAL_ADD_LID; HREAL_ADD_RID; HREAL_ADD_SYM]);; let TREAL_MUL_SYM = prove (`!x y. (x treal_mul y) treal_eq (y treal_mul x)`, SIMP_TAC[TREAL_EQ_AP; TREAL_MUL_SYM_EQ]);; let TREAL_MUL_ASSOC = prove (`!x y z. (x treal_mul (y treal_mul z)) treal_eq ((x treal_mul y) treal_mul z)`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_mul; HREAL_ADD_LDISTRIB; HREAL_ADD_RDISTRIB; GSYM HREAL_MUL_ASSOC; HREAL_ADD_AC]);; let TREAL_MUL_LID = prove (`!x. ((treal_of_num 1) treal_mul x) treal_eq x`, SIMP_TAC[FORALL_PAIR_THM; treal_of_num; treal_mul; treal_eq] THEN REWRITE_TAC[HREAL_MUL_LZERO; HREAL_MUL_LID; HREAL_ADD_LID; HREAL_ADD_RID]);; let TREAL_ADD_LDISTRIB = prove (`!x y z. (x treal_mul (y treal_add z)) treal_eq ((x treal_mul y) treal_add (x treal_mul z))`, SIMP_TAC[FORALL_PAIR_THM; TREAL_EQ_AP; treal_mul; treal_add; HREAL_ADD_LDISTRIB; PAIR_EQ; HREAL_ADD_AC]);; let TREAL_LE_REFL = prove (`!x. x treal_le x`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; HREAL_LE_REFL]);; let TREAL_LE_ANTISYM = prove (`!x y. x treal_le y /\ y treal_le x <=> (x treal_eq y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; treal_eq; HREAL_LE_ANTISYM]);; let TREAL_LE_TRANS = prove (`!x y z. x treal_le y /\ y treal_le z ==> x treal_le z`, REWRITE_TAC[FORALL_PAIR_THM; treal_le] THEN REPEAT GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP HREAL_LE_ADD2) THEN GEN_REWRITE_TAC (LAND_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_ASSOC; HREAL_LE_ADD_RCANCEL] THEN DISCH_THEN(MATCH_ACCEPT_TAC o ONCE_REWRITE_RULE[HREAL_ADD_SYM]));; let TREAL_LE_TOTAL = prove (`!x y. x treal_le y \/ y treal_le x`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; HREAL_LE_TOTAL]);; let TREAL_LE_LADD_IMP = prove (`!x y z. (y treal_le z) ==> (x treal_add y) treal_le (x treal_add z)`, REWRITE_TAC[FORALL_PAIR_THM; treal_le; treal_add] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL] THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_LE_ADD_LCANCEL]);; let TREAL_LE_MUL = prove (`!x y. (treal_of_num 0) treal_le x /\ (treal_of_num 0) treal_le y ==> (treal_of_num 0) treal_le (x treal_mul y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_of_num; treal_le; treal_mul] THEN REPEAT GEN_TAC THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN DISCH_THEN(CHOOSE_THEN SUBST1_TAC o MATCH_MP HREAL_LE_EXISTS) THEN REWRITE_TAC[HREAL_ADD_LDISTRIB; HREAL_LE_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN GEN_REWRITE_TAC RAND_CONV [HREAL_ADD_SYM] THEN ASM_REWRITE_TAC[HREAL_LE_ADD_LCANCEL] THEN MATCH_MP_TAC HREAL_LE_MUL_RCANCEL_IMP THEN ASM_REWRITE_TAC[]);; let TREAL_INV_0 = prove (`treal_inv (treal_of_num 0) treal_eq (treal_of_num 0)`, REWRITE_TAC[treal_inv; treal_eq; treal_of_num]);; let TREAL_MUL_LINV = prove (`!x. ~(x treal_eq treal_of_num 0) ==> (treal_inv(x) treal_mul x) treal_eq (treal_of_num 1)`, REWRITE_TAC[FORALL_PAIR_THM] THEN MAP_EVERY X_GEN_TAC [`x:hreal`; `y:hreal`] THEN PURE_REWRITE_TAC[treal_eq; treal_of_num; treal_mul; treal_inv] THEN PURE_REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_TAC THEN PURE_ASM_REWRITE_TAC[COND_CLAUSES] THEN COND_CASES_TAC THEN PURE_REWRITE_TAC[treal_mul; treal_eq] THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID; HREAL_MUL_LZERO; HREAL_MUL_RZERO] THENL [ALL_TAC; DISJ_CASES_THEN MP_TAC(SPECL [`x:hreal`; `y:hreal`] HREAL_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN DISCH_TAC] THEN FIRST_ASSUM(MP_TAC o MATCH_MP HREAL_LE_EXISTS) THEN DISCH_THEN(MP_TAC o SELECT_RULE) THEN DISCH_THEN(fun th -> ASSUME_TAC (SYM th) THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [th]) THEN REWRITE_TAC[HREAL_ADD_LDISTRIB] THEN GEN_REWRITE_TAC RAND_CONV [HREAL_ADD_SYM] THEN AP_TERM_TAC THEN MATCH_MP_TAC HREAL_MUL_LINV THEN DISCH_THEN SUBST_ALL_TAC THEN FIRST_ASSUM(UNDISCH_TAC o check is_eq o concl) THEN ASM_REWRITE_TAC[HREAL_ADD_RID] THEN PURE_ONCE_REWRITE_TAC[EQ_SYM_EQ] THEN ASM_REWRITE_TAC[]);; let TREAL_OF_NUM_WELLDEF = prove (`!m n. (m = n) ==> (treal_of_num m) treal_eq (treal_of_num n)`, REPEAT GEN_TAC THEN DISCH_THEN SUBST1_TAC THEN MATCH_ACCEPT_TAC TREAL_EQ_REFL);; let TREAL_NEG_WELLDEF = prove (`!x1 x2. x1 treal_eq x2 ==> (treal_neg x1) treal_eq (treal_neg x2)`, REWRITE_TAC[FORALL_PAIR_THM; treal_neg; treal_eq] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN ASM_REWRITE_TAC[]);; let TREAL_ADD_WELLDEFR = prove (`!x1 x2 y. x1 treal_eq x2 ==> (x1 treal_add y) treal_eq (x2 treal_add y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_add; treal_eq] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL; HREAL_ADD_ASSOC] THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_RCANCEL; HREAL_ADD_ASSOC]);; let TREAL_ADD_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_add y1) treal_eq (x2 treal_add y2)`, REPEAT GEN_TAC THEN DISCH_TAC THEN MATCH_MP_TAC TREAL_EQ_TRANS THEN EXISTS_TAC `x1 treal_add y2` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[TREAL_ADD_SYM_EQ]; ALL_TAC] THEN MATCH_MP_TAC TREAL_ADD_WELLDEFR THEN ASM_REWRITE_TAC[]);; let TREAL_MUL_WELLDEFR = prove (`!x1 x2 y. x1 treal_eq x2 ==> (x1 treal_mul y) treal_eq (x2 treal_mul y)`, REWRITE_TAC[FORALL_PAIR_THM; treal_mul; treal_eq] THEN REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[AC HREAL_ADD_AC `(a + b) + (c + d) = (a + d) + (b + c)`] THEN REWRITE_TAC[GSYM HREAL_ADD_RDISTRIB] THEN DISCH_TAC THEN ASM_REWRITE_TAC[] THEN AP_TERM_TAC THEN ONCE_REWRITE_TAC[HREAL_ADD_SYM] THEN POP_ASSUM SUBST1_TAC THEN REFL_TAC);; let TREAL_MUL_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_mul y1) treal_eq (x2 treal_mul y2)`, REPEAT GEN_TAC THEN DISCH_TAC THEN MATCH_MP_TAC TREAL_EQ_TRANS THEN EXISTS_TAC `x1 treal_mul y2` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[TREAL_MUL_SYM_EQ]; ALL_TAC] THEN MATCH_MP_TAC TREAL_MUL_WELLDEFR THEN ASM_REWRITE_TAC[]);; let TREAL_EQ_IMP_LE = prove (`!x y. x treal_eq y ==> x treal_le y`, SIMP_TAC[FORALL_PAIR_THM; treal_eq; treal_le; HREAL_LE_REFL]);; let TREAL_LE_WELLDEF = prove (`!x1 x2 y1 y2. x1 treal_eq x2 /\ y1 treal_eq y2 ==> (x1 treal_le y1 <=> x2 treal_le y2)`, REPEAT (STRIP_TAC ORELSE EQ_TAC) THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `y1:hreal#hreal` THEN CONJ_TAC THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `x1:hreal#hreal` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC TREAL_EQ_IMP_LE THEN ONCE_REWRITE_TAC[TREAL_EQ_SYM]; MATCH_MP_TAC TREAL_EQ_IMP_LE]; MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `y2:hreal#hreal` THEN CONJ_TAC THENL [MATCH_MP_TAC TREAL_LE_TRANS THEN EXISTS_TAC `x2:hreal#hreal` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC TREAL_EQ_IMP_LE; MATCH_MP_TAC TREAL_EQ_IMP_LE THEN ONCE_REWRITE_TAC[TREAL_EQ_SYM]]] THEN ASM_REWRITE_TAC[]);; let TREAL_INV_WELLDEF = prove (`!x y. x treal_eq y ==> (treal_inv x) treal_eq (treal_inv y)`, let lemma = prove (`(@d. x = x + d) = &0`, MATCH_MP_TAC SELECT_UNIQUE THEN BETA_TAC THEN GEN_TAC THEN GEN_REWRITE_TAC (funpow 2 LAND_CONV) [GSYM HREAL_ADD_RID] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL] THEN MATCH_ACCEPT_TAC EQ_SYM_EQ) in REWRITE_TAC[FORALL_PAIR_THM] THEN MAP_EVERY X_GEN_TAC [`x1:hreal`; `x2:hreal`; `y1:hreal`; `y2:hreal`] THEN PURE_REWRITE_TAC[treal_eq; treal_inv] THEN ASM_CASES_TAC `x1 :hreal = x2` THEN ASM_CASES_TAC `y1 :hreal = y2` THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[TREAL_EQ_REFL] THEN DISCH_THEN(MP_TAC o GEN_REWRITE_RULE RAND_CONV [HREAL_ADD_SYM]) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; HREAL_EQ_ADD_RCANCEL] THEN DISCH_TAC THEN ASM_REWRITE_TAC[HREAL_LE_REFL; lemma; HREAL_INV_0;TREAL_EQ_REFL] THEN ASM_CASES_TAC `x2 <= x1` THEN ASM_REWRITE_TAC[] THENL [FIRST_ASSUM(ASSUME_TAC o SYM o SELECT_RULE o MATCH_MP HREAL_LE_EXISTS) THEN UNDISCH_TAC `x1 + y2 = x2 + y1` THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN DISCH_THEN(SUBST1_TAC o SYM) THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD] THEN GEN_REWRITE_TAC (RAND_CONV o LAND_CONV o RAND_CONV o BINDER_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; TREAL_EQ_REFL]; DISJ_CASES_THEN MP_TAC (SPECL [`x1:hreal`; `x2:hreal`] HREAL_LE_TOTAL) THEN ASM_REWRITE_TAC[] THEN DISCH_TAC THEN FIRST_ASSUM(ASSUME_TAC o SYM o SELECT_RULE o MATCH_MP HREAL_LE_EXISTS) THEN UNDISCH_TAC `x1 + y2 = x2 + y1` THEN FIRST_ASSUM(SUBST1_TAC o SYM) THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; GSYM HREAL_ADD_ASSOC] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD] THEN COND_CASES_TAC THENL [UNDISCH_TAC `(@d. x2 = x1 + d) + y1 <= y1:hreal` THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[ONCE_REWRITE_RULE[HREAL_ADD_SYM] HREAL_LE_ADD_LCANCEL] THEN DISCH_TAC THEN SUBGOAL_THEN `(@d. x2 = x1 + d) = &0` MP_TAC THENL [ASM_REWRITE_TAC[GSYM HREAL_LE_ANTISYM] THEN GEN_REWRITE_TAC RAND_CONV [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_LE_ADD]; DISCH_THEN SUBST_ALL_TAC THEN UNDISCH_TAC `x1 + & 0 = x2` THEN ASM_REWRITE_TAC[HREAL_ADD_RID]]; GEN_REWRITE_TAC (funpow 3 RAND_CONV o BINDER_CONV o LAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[HREAL_EQ_ADD_LCANCEL; TREAL_EQ_REFL]]]);; let real_tybij = define_quotient_type "real" ("mk_real","dest_real") `(treal_eq)`;; let real_of_num,real_of_num_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_of_num" TREAL_OF_NUM_WELLDEF;; let real_neg,real_neg_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_neg" TREAL_NEG_WELLDEF;; let real_add,real_add_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_add" TREAL_ADD_WELLDEF;; let real_mul,real_mul_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_mul" TREAL_MUL_WELLDEF;; let real_le,real_le_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_le" TREAL_LE_WELLDEF;; let real_inv,real_inv_th = lift_function (snd real_tybij) (TREAL_EQ_REFL,TREAL_EQ_TRANS) "real_inv" TREAL_INV_WELLDEF;; let [REAL_ADD_SYM; REAL_ADD_ASSOC; REAL_ADD_LID; REAL_ADD_LINV; REAL_MUL_SYM; REAL_MUL_ASSOC; REAL_MUL_LID; REAL_ADD_LDISTRIB; REAL_LE_REFL; REAL_LE_ANTISYM; REAL_LE_TRANS; REAL_LE_TOTAL; REAL_LE_LADD_IMP; REAL_LE_MUL; REAL_INV_0; REAL_MUL_LINV; REAL_OF_NUM_EQ; REAL_OF_NUM_LE; REAL_OF_NUM_ADD; REAL_OF_NUM_MUL] = map (lift_theorem real_tybij (TREAL_EQ_REFL,TREAL_EQ_SYM,TREAL_EQ_TRANS) [real_of_num_th; real_neg_th; real_add_th; real_mul_th; real_le_th; real_inv_th]) [TREAL_ADD_SYM; TREAL_ADD_ASSOC; TREAL_ADD_LID; TREAL_ADD_LINV; TREAL_MUL_SYM; TREAL_MUL_ASSOC; TREAL_MUL_LID; TREAL_ADD_LDISTRIB; TREAL_LE_REFL; TREAL_LE_ANTISYM; TREAL_LE_TRANS; TREAL_LE_TOTAL; TREAL_LE_LADD_IMP; TREAL_LE_MUL; TREAL_INV_0; TREAL_MUL_LINV; TREAL_OF_NUM_EQ; TREAL_OF_NUM_LE; TREAL_OF_NUM_ADD; TREAL_OF_NUM_MUL];; parse_as_prefix "--";; parse_as_infix ("/",(22,"left"));; parse_as_infix ("pow",(24,"left"));; do_list overload_interface ["+",`real_add:real->real->real`; "-",`real_sub:real->real->real`; "*",`real_mul:real->real->real`; "/",`real_div:real->real->real`; "<",`real_lt:real->real->bool`; "<=",`real_le:real->real->bool`; ">",`real_gt:real->real->bool`; ">=",`real_ge:real->real->bool`; "--",`real_neg:real->real`; "pow",`real_pow:real->num->real`; "inv",`real_inv:real->real`; "abs",`real_abs:real->real`; "max",`real_max:real->real->real`; "min",`real_min:real->real->real`; "&",`real_of_num:num->real`];; let prioritize_real() = prioritize_overload(mk_type("real",[]));; let real_sub = new_definition `x - y = x + --y`;; let real_lt = new_definition `x < y <=> ~(y <= x)`;; let real_ge = new_definition `x >= y <=> y <= x`;; let real_gt = new_definition `x > y <=> y < x`;; let real_abs = new_definition `abs(x) = if &0 <= x then x else --x`;; let real_pow = new_recursive_definition num_RECURSION `(x pow 0 = &1) /\ (!n. x pow (SUC n) = x * (x pow n))`;; let real_div = new_definition `x / y = x * inv(y)`;; let real_max = new_definition `real_max m n = if m <= n then n else m`;; let real_min = new_definition `real_min m n = if m <= n then m else n`;; let REAL_HREAL_LEMMA1 = prove (`?r:hreal->real. (!x. &0 <= x <=> ?y. x = r y) /\ (!y z. y <= z <=> r y <= r z)`, EXISTS_TAC `\y. mk_real((treal_eq)(y,hreal_of_num 0))` THEN REWRITE_TAC[GSYM real_le_th] THEN REWRITE_TAC[treal_le; HREAL_ADD_LID; HREAL_ADD_RID] THEN GEN_TAC THEN EQ_TAC THENL [MP_TAC(INST [`dest_real x`,`r:hreal#hreal->bool`] (snd real_tybij)) THEN REWRITE_TAC[fst real_tybij] THEN DISCH_THEN(X_CHOOSE_THEN `p:hreal#hreal` MP_TAC) THEN DISCH_THEN(MP_TAC o AP_TERM `mk_real`) THEN REWRITE_TAC[fst real_tybij] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[GSYM real_of_num_th; GSYM real_le_th] THEN SUBST1_TAC(GSYM(ISPEC `p:hreal#hreal` PAIR)) THEN PURE_REWRITE_TAC[treal_of_num; treal_le] THEN PURE_REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN DISCH_THEN(X_CHOOSE_THEN `d:hreal` SUBST1_TAC o MATCH_MP HREAL_LE_EXISTS) THEN EXISTS_TAC `d:hreal` THEN AP_TERM_TAC THEN ONCE_REWRITE_TAC[FUN_EQ_THM] THEN X_GEN_TAC `q:hreal#hreal` THEN SUBST1_TAC(GSYM(ISPEC `q:hreal#hreal` PAIR)) THEN PURE_REWRITE_TAC[treal_eq] THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [HREAL_ADD_SYM] THEN REWRITE_TAC[GSYM HREAL_ADD_ASSOC; HREAL_EQ_ADD_LCANCEL] THEN REWRITE_TAC[HREAL_ADD_RID]; DISCH_THEN(CHOOSE_THEN SUBST1_TAC) THEN REWRITE_TAC[GSYM real_of_num_th; GSYM real_le_th] THEN REWRITE_TAC[treal_of_num; treal_le] THEN REWRITE_TAC[HREAL_ADD_LID; HREAL_ADD_RID] THEN GEN_REWRITE_TAC RAND_CONV [GSYM HREAL_ADD_LID] THEN REWRITE_TAC[HREAL_LE_ADD]]);; let REAL_HREAL_LEMMA2 = prove (`?h r. (!x:hreal. h(r x) = x) /\ (!x. &0 <= x ==> (r(h x) = x)) /\ (!x:hreal. &0 <= r x) /\ (!x y. x <= y <=> r x <= r y)`, STRIP_ASSUME_TAC REAL_HREAL_LEMMA1 THEN EXISTS_TAC `\x:real. @y:hreal. x = r y` THEN EXISTS_TAC `r:hreal->real` THEN ASM_REWRITE_TAC[BETA_THM] THEN SUBGOAL_THEN `!y z. ((r:hreal->real) y = r z) <=> (y = z)` ASSUME_TAC THENL [ASM_REWRITE_TAC[GSYM REAL_LE_ANTISYM; GSYM HREAL_LE_ANTISYM]; ALL_TAC] THEN ASM_REWRITE_TAC[GEN_REWRITE_RULE (LAND_CONV o BINDER_CONV) [EQ_SYM_EQ] (SPEC_ALL SELECT_REFL); GSYM EXISTS_REFL] THEN GEN_TAC THEN DISCH_THEN(ACCEPT_TAC o SYM o SELECT_RULE));; let REAL_COMPLETE_SOMEPOS = prove (`!P. (?x. P x /\ &0 <= x) /\ (?M. !x. P x ==> x <= M) ==> ?M. (!x. P x ==> x <= M) /\ !M'. (!x. P x ==> x <= M') ==> M <= M'`, REPEAT STRIP_TAC THEN STRIP_ASSUME_TAC REAL_HREAL_LEMMA2 THEN MP_TAC(SPEC `\y:hreal. (P:real->bool)(r y)` HREAL_COMPLETE) THEN BETA_TAC THEN W(C SUBGOAL_THEN MP_TAC o funpow 2 (fst o dest_imp) o snd) THENL [CONJ_TAC THENL [EXISTS_TAC `(h:real->hreal) x` THEN UNDISCH_TAC `(P:real->bool) x` THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; EXISTS_TAC `(h:real->hreal) M` THEN X_GEN_TAC `y:hreal` THEN DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `x:real` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]; MATCH_MP_TAC(TAUT `(b ==> c) ==> a ==> (a ==> b) ==> c`) THEN DISCH_THEN(X_CHOOSE_THEN `B:hreal` STRIP_ASSUME_TAC)] THEN EXISTS_TAC `(r:hreal->real) B` THEN CONJ_TAC THENL [X_GEN_TAC `z:real` THEN DISCH_TAC THEN DISJ_CASES_TAC(SPECL [`&0`; `z:real`] REAL_LE_TOTAL) THENL [ANTE_RES_THEN(SUBST1_TAC o SYM) (ASSUME `&0 <= z`) THEN FIRST_ASSUM(fun th -> GEN_REWRITE_TAC I [GSYM th]) THEN FIRST_ASSUM MATCH_MP_TAC THEN UNDISCH_TAC `(P:real->bool) z` THEN MATCH_MP_TAC(TAUT `(b <=> a) ==> a ==> b`) THEN AP_TERM_TAC THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `&0` THEN ASM_REWRITE_TAC[]]; X_GEN_TAC `C:real` THEN DISCH_TAC THEN SUBGOAL_THEN `B:hreal <= (h(C:real))` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN SUBGOAL_THEN `(r:hreal->real)(h C) = C` (fun th -> ASM_REWRITE_TAC[th]); ASM_REWRITE_TAC[] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC] THEN FIRST_ASSUM MATCH_MP_TAC THEN MATCH_MP_TAC REAL_LE_TRANS THEN EXISTS_TAC `x:real` THEN ASM_REWRITE_TAC[] THEN FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]]);; let REAL_COMPLETE = prove (`!P. (?x. P x) /\ (?M. !x. P x ==> x <= M) ==> ?M. (!x. P x ==> x <= M) /\ !M'. (!x. P x ==> x <= M') ==> M <= M'`, let lemma = prove (`y = (y - x) + x`, REWRITE_TAC[real_sub; GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[REAL_ADD_LID]) in REPEAT STRIP_TAC THEN DISJ_CASES_TAC (SPECL [`&0`; `x:real`] REAL_LE_TOTAL) THENL [MATCH_MP_TAC REAL_COMPLETE_SOMEPOS THEN CONJ_TAC THENL [EXISTS_TAC `x:real`; EXISTS_TAC `M:real`] THEN ASM_REWRITE_TAC[]; FIRST_ASSUM(MP_TAC o MATCH_MP REAL_LE_LADD_IMP) THEN DISCH_THEN(MP_TAC o SPEC `--x`) THEN REWRITE_TAC[REAL_ADD_LINV] THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[REAL_ADD_LID] THEN DISCH_TAC THEN MP_TAC(SPEC `\y. P(y + x) :bool` REAL_COMPLETE_SOMEPOS) THEN BETA_TAC THEN W(C SUBGOAL_THEN MP_TAC o funpow 2 (fst o dest_imp) o snd) THENL [CONJ_TAC THENL [EXISTS_TAC `&0` THEN ASM_REWRITE_TAC[REAL_LE_REFL; REAL_ADD_LID]; EXISTS_TAC `M + --x` THEN GEN_TAC THEN DISCH_THEN(ANTE_RES_THEN MP_TAC) THEN DISCH_THEN(MP_TAC o SPEC `--x` o MATCH_MP REAL_LE_LADD_IMP) THEN DISCH_THEN(MP_TAC o ONCE_REWRITE_RULE[REAL_ADD_SYM]) THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]; MATCH_MP_TAC(TAUT `(b ==> c) ==> a ==> (a ==> b) ==> c`) THEN DISCH_THEN(X_CHOOSE_THEN `B:real` STRIP_ASSUME_TAC)] THEN EXISTS_TAC `B + x` THEN CONJ_TAC THENL [GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [lemma] THEN DISCH_THEN(ANTE_RES_THEN (MP_TAC o SPEC `x:real` o MATCH_MP REAL_LE_LADD_IMP)) THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub; GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID] THEN REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN ASM_REWRITE_TAC[]; REPEAT STRIP_TAC THEN SUBGOAL_THEN `B <= M' - x` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN X_GEN_TAC `z:real` THEN DISCH_TAC THEN SUBGOAL_THEN `z + x <= M'` MP_TAC THENL [FIRST_ASSUM MATCH_MP_TAC THEN ASM_REWRITE_TAC[]; DISCH_THEN(MP_TAC o SPEC `--x` o MATCH_MP REAL_LE_LADD_IMP) THEN ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub] THEN MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]; DISCH_THEN(MP_TAC o SPEC `x:real` o MATCH_MP REAL_LE_LADD_IMP) THEN MATCH_MP_TAC EQ_IMP THEN BINOP_TAC THENL [MATCH_ACCEPT_TAC REAL_ADD_SYM; ONCE_REWRITE_TAC[REAL_ADD_SYM] THEN REWRITE_TAC[real_sub] THEN REWRITE_TAC[GSYM REAL_ADD_ASSOC; REAL_ADD_LINV] THEN REWRITE_TAC[ONCE_REWRITE_RULE[REAL_ADD_SYM] REAL_ADD_LID]]]]]);; do_list reduce_interface ["+",`hreal_add:hreal->hreal->hreal`; "*",`hreal_mul:hreal->hreal->hreal`; "<=",`hreal_le:hreal->hreal->bool`; "inv",`hreal_inv:hreal->hreal`];; do_list remove_interface ["**"; "++"; "<<="; "==="; "fn"; "afn"];; print_endline "realax.ml loaded"
69ebf6ef601e8b6d1dbce9fe582917453e22bec45f1b78730fba9424dbb33115
nixeagle/cl-irc
package.lisp
$ Id$ ;;;; $Source$ ;;;; See the LICENSE file for licensing information. (in-package :cl-user) (eval-when (:execute :load-toplevel :compile-toplevel) (defpackage :cl-irc-test (:use :cl :rt) (:nicknames :cl-irc-test) (:export :do-tests)))
null
https://raw.githubusercontent.com/nixeagle/cl-irc/efaea15f2962107ea9b1a2fad5cd9db492b4247b/tags/cl_irc_0_7/test/package.lisp
lisp
$Source$ See the LICENSE file for licensing information.
$ Id$ (in-package :cl-user) (eval-when (:execute :load-toplevel :compile-toplevel) (defpackage :cl-irc-test (:use :cl :rt) (:nicknames :cl-irc-test) (:export :do-tests)))
24435960a7dc3d948f876c3d9aef1eec4a07fa6f55a69f017bd81a2c40454066
racket/drdr
sema.rkt
#lang racket/base (require racket/contract/base) (define (semaphore-wait* sema how-many) (unless (zero? how-many) (semaphore-wait sema) (semaphore-wait* sema (sub1 how-many)))) (provide/contract [semaphore-wait* (semaphore? exact-nonnegative-integer? . -> . void)])
null
https://raw.githubusercontent.com/racket/drdr/a3e5e778a1c19e7312b98bab25ed95075783f896/sema.rkt
racket
#lang racket/base (require racket/contract/base) (define (semaphore-wait* sema how-many) (unless (zero? how-many) (semaphore-wait sema) (semaphore-wait* sema (sub1 how-many)))) (provide/contract [semaphore-wait* (semaphore? exact-nonnegative-integer? . -> . void)])
350f79b71024a509cb79a7f9234e4c1e91ca897b5544fe7d8c54e025ec3c605e
cxphoe/SICP-solutions
2.08.rkt
(load "2.7.rkt") (define (sub-interval x y) (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y))))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%202-Building%20Abstractions%20with%20Data/1.Introduction%20to%20Data%20Abstraction/2.08.rkt
racket
(load "2.7.rkt") (define (sub-interval x y) (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y))))
94f58ef5f465a4204e6dd767e43570ae6bc9c333be86e9f4abb873d47d4820e3
realworldocaml/book
ppx_hash_expander.ml
open Base open Ppxlib open Ast_builder.Default module Attrs = struct let ignore_label_declaration = Attribute.declare "hash.ignore" Attribute.Context.label_declaration Ast_pattern.(pstr nil) () ;; let ignore_core_type = Attribute.declare "hash.ignore" Attribute.Context.core_type Ast_pattern.(pstr nil) () ;; let no_hashing_label_declaration = Attribute.declare "hash.no_hashing" Attribute.Context.label_declaration Ast_pattern.(pstr nil) () ;; end let str_attributes = [ Attribute.T Attrs.ignore_core_type ; Attribute.T Attrs.ignore_label_declaration ; Attribute.T Attrs.no_hashing_label_declaration ] ;; let is_ignored_gen attrs t = List.exists attrs ~f:(fun attr -> Option.is_some (Attribute.get attr t)) ;; let core_type_is_ignored ct = is_ignored_gen [ Attrs.ignore_core_type; Ppx_compare_expander.Compare.Attrs.ignore_core_type ] ct ;; let should_ignore_label_declaration ld = let warning = "[@hash.no_hashing] is deprecated. Use [@hash.ignore]." in let is_ignored = is_ignored_gen [ Attrs.ignore_label_declaration ; Ppx_compare_expander.Compare.Attrs.ignore_label_declaration ] ld (* Avoid confusing errors with [ { mutable field : (value[@ignore]) } ] vs [ { mutable field : value [@ignore] } ] by treating them the same. *) || core_type_is_ignored ld.pld_type in match Attribute.get Attrs.no_hashing_label_declaration ld with | None -> (if is_ignored then `ignore else `incorporate), None | Some () -> `ignore, Some (attribute_of_warning ld.pld_loc warning) ;; (* Generate code to compute hash values of type [t] in folding style, following the structure of the type. Incorporate all structure when computing hash values, to maximise hash quality. Don't attempt to detect/avoid cycles - just loop. *) let hash_state_t ~loc = [%type: Ppx_hash_lib.Std.Hash.state] let hash_fold_type ~loc ty = let loc = { loc with loc_ghost = true } in [%type: [%t hash_state_t ~loc] -> [%t ty] -> [%t hash_state_t ~loc]] ;; let hash_type ~loc ty = let loc = { loc with loc_ghost = true } in [%type: [%t ty] -> Ppx_hash_lib.Std.Hash.hash_value] ;; (* [expr] is an expression that doesn't use the [hsv] variable. Currently it's there only for documentation value, but conceptually it can be thought of as an abstract type *) type expr = expression (* Represents an expression that produces a hash value and uses the variable [hsv] in a linear way (mixes it in exactly once). You can think of it as a body of a function of type [Hash.state -> Hash.state] *) module Hsv_expr : sig type t val identity : loc:location -> t val invoke_hash_fold_t : loc:location -> hash_fold_t:expr -> t:expr -> t val compose : loc:location -> t -> t -> t val compile_error : loc:location -> string -> t (** the [_unchecked] functions all break abstraction in some way *) val of_expression_unchecked : expr -> t (** the returned [expression] uses the binding [hsv] bound by [pattern] *) val to_expression : loc:location -> t -> pattern * expression (* [case] is binding a variable that's not [hsv] and uses [hsv] on the rhs exactly once *) type case val compile_error_case : loc:location -> string -> case val pexp_match : loc:location -> expr -> case list -> t [ lhs ] should not bind [ hsv ] val case : lhs:pattern -> guard:expr option -> rhs:t -> case (* [value_binding]s should not bind or use [hsv] *) val pexp_let : loc:location -> rec_flag -> value_binding list -> t -> t val with_attributes : f:(attribute list -> attribute list) -> t -> t end = struct type t = expression type nonrec case = case let invoke_hash_fold_t ~loc ~hash_fold_t ~t = eapply ~loc hash_fold_t [ [%expr hsv]; t ] let identity ~loc = [%expr hsv] let compose ~loc a b = [%expr let hsv = [%e a] in [%e b]] ;; let to_expression ~loc x = [%pat? hsv], x let of_expression_unchecked x = x let pexp_match = pexp_match let case = case let pexp_let = pexp_let let with_attributes ~f x = { x with pexp_attributes = f x.pexp_attributes } let compile_error ~loc s = pexp_extension ~loc (Location.Error.to_extension (Location.Error.createf ~loc "%s" s)) ;; let compile_error_case ~loc s = case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:(compile_error ~loc s) ;; end let hash_fold_int ~loc i : Hsv_expr.t = Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:[%expr Ppx_hash_lib.Std.Hash.fold_int] ~t:(eint ~loc i) ;; let special_case_types_named_t = function | `hash_fold -> false | `hash -> true ;; let hash_fold_ tn = match tn with | "t" when special_case_types_named_t `hash_fold -> "hash_fold" | _ -> "hash_fold_" ^ tn ;; let hash_ tn = match tn with | "t" when special_case_types_named_t `hash -> "hash" | _ -> "hash_" ^ tn ;; (** renames [x] avoiding collision with [type_name] *) let rigid_type_var ~type_name x = let prefix = "rigid_" in if String.equal x type_name || String.is_prefix x ~prefix then prefix ^ x ^ "_of_type_" ^ type_name else x ;; let make_type_rigid ~type_name = let map = object inherit Ast_traverse.map as super method! core_type ty = let ptyp_desc = let () = (* making sure [type_name] is the only free type variable *) match ty.ptyp_desc with | Ptyp_constr (name, _args) -> (match name.txt with | Ldot _ | Lapply _ -> () | Lident name -> if not (String.equal name type_name) then Location.raise_errorf ~loc:ty.ptyp_loc "ppx_hash: make_type_rigid: unexpected type %S. expected to only \ find %S" (string_of_core_type ty) type_name; ()) | _ -> () in match ty.ptyp_desc with | Ptyp_var s -> Ptyp_constr (Located.lident ~loc:ty.ptyp_loc (rigid_type_var ~type_name s), []) | desc -> super#core_type_desc desc in { ty with ptyp_desc } end in map#core_type ;; (* The only names we assume to be in scope are [hash_fold_<TY>] So we are sure [tp_name] (which start with an [_]) will not capture them. *) let tp_name n = Printf.sprintf "_hash_fold_%s" n let with_tuple loc (value : expr) xs (f : (expr * core_type) list -> Hsv_expr.t) : Hsv_expr.t = let names = List.mapi ~f:(fun i t -> Printf.sprintf "e%d" i, t) xs in let pattern = let l = List.map ~f:(fun (n, _) -> pvar ~loc n) names in ppat_tuple ~loc l in let e = f (List.map ~f:(fun (n, t) -> evar ~loc n, t) names) in let binding = value_binding ~loc ~pat:pattern ~expr:value in Hsv_expr.pexp_let ~loc Nonrecursive [ binding ] e ;; let hash_ignore ~loc value = Hsv_expr.pexp_let ~loc Nonrecursive [ value_binding ~loc ~pat:[%pat? _] ~expr:value ] (Hsv_expr.identity ~loc) ;; let ghostify_located (t : 'a loc) : 'a loc = { t with loc = { t.loc with loc_ghost = true } } ;; let rec hash_applied ty value = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (name, ta) -> let args = List.map ta ~f:(hash_fold_of_ty_fun ~type_constraint:false) in Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:(type_constr_conv ~loc name ~f:hash_fold_ args) ~t:value | _ -> assert false and hash_fold_of_tuple ~loc tys value = with_tuple loc value tys (fun elems1 -> List.fold_right elems1 ~init:(Hsv_expr.identity ~loc) ~f:(fun (v, t) (result : Hsv_expr.t) -> Hsv_expr.compose ~loc (hash_fold_of_ty t v) result)) and hash_variant ~loc row_fields value = let map row = match row.prf_desc with | Rtag ({ txt = cnstr; _ }, true, _) | Rtag ({ txt = cnstr; _ }, _, []) -> Hsv_expr.case ~guard:None ~lhs:(ppat_variant ~loc cnstr None) ~rhs:(hash_fold_int ~loc (Ocaml_common.Btype.hash_variant cnstr)) | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let v = "_v" in let body = Hsv_expr.compose ~loc (hash_fold_int ~loc (Ocaml_common.Btype.hash_variant cnstr)) (hash_fold_of_ty tp (evar ~loc v)) in Hsv_expr.case ~guard:None ~lhs:(ppat_variant ~loc cnstr (Some (pvar ~loc v))) ~rhs:body | Rinherit ({ ptyp_desc = Ptyp_constr (id, _); _ } as ty) -> Generated code from .. type ' a i d = ' a [ @@deriving hash ] type t = [ ` a | [ ` b ] i d ] [ @@deriving hash ] does n't compile : Also see the " sadly " note in : ppx_compare_expander.ml type 'a id = 'a [@@deriving hash] type t = [ `a | [ `b ] id ] [@@deriving hash] doesn't compile: Also see the "sadly" note in: ppx_compare_expander.ml *) let v = "_v" in Hsv_expr.case ~guard:None ~lhs:(ppat_alias ~loc (ppat_type ~loc (ghostify_located id)) (Located.mk ~loc v)) ~rhs:(hash_applied ty (evar ~loc v)) | Rinherit ty -> let s = string_of_core_type ty in Hsv_expr.compile_error_case ~loc (Printf.sprintf "ppx_hash: impossible variant case: %s" s) in Hsv_expr.pexp_match ~loc value (List.map ~f:map row_fields) and branch_of_sum hsv ~loc cd = match cd.pcd_args with | Pcstr_tuple [] -> let pcnstr = pconstruct cd None in Hsv_expr.case ~guard:None ~lhs:pcnstr ~rhs:hsv | Pcstr_tuple tps -> let ids_ty = List.mapi tps ~f:(fun i ty -> Printf.sprintf "_a%d" i, ty) in let lpatt = List.map ids_ty ~f:(fun (l, _ty) -> pvar ~loc l) |> ppat_tuple ~loc and body = List.fold_left ids_ty ~init:(Hsv_expr.identity ~loc) ~f:(fun expr (l, ty) -> Hsv_expr.compose ~loc expr (hash_fold_of_ty ty (evar ~loc l))) in Hsv_expr.case ~guard:None ~lhs:(pconstruct cd (Some lpatt)) ~rhs:(Hsv_expr.compose ~loc hsv body) | Pcstr_record lds -> let arg = "_ir" in let pat = pvar ~loc arg in let v = evar ~loc arg in let body = hash_fold_of_record ~loc lds v in Hsv_expr.case ~guard:None ~lhs:(pconstruct cd (Some pat)) ~rhs:(Hsv_expr.compose ~loc hsv body) and branches_of_sum = function | [ cd ] -> this is an optimization : we do n't need to mix in the constructor tag if the type only has one constructor only has one constructor *) let loc = cd.pcd_loc in [ branch_of_sum (Hsv_expr.identity ~loc) ~loc cd ] | cds -> List.mapi cds ~f:(fun i cd -> let loc = cd.pcd_loc in let hsv = hash_fold_int ~loc i in branch_of_sum hsv ~loc cd) and hash_sum ~loc cds value = Hsv_expr.pexp_match ~loc value (branches_of_sum cds) and hash_fold_of_ty ty value = let loc = { ty.ptyp_loc with loc_ghost = true } in if core_type_is_ignored ty then hash_ignore ~loc value else ( match ty.ptyp_desc with | Ptyp_constr _ -> hash_applied ty value | Ptyp_tuple tys -> hash_fold_of_tuple ~loc tys value | Ptyp_var name -> Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:(evar ~loc (tp_name name)) ~t:value | Ptyp_arrow _ -> Hsv_expr.compile_error ~loc "ppx_hash: functions can not be hashed." | Ptyp_variant (row_fields, Closed, _) -> hash_variant ~loc row_fields value | _ -> let s = string_of_core_type ty in Hsv_expr.compile_error ~loc (Printf.sprintf "ppx_hash: unsupported type: %s" s)) and hash_fold_of_ty_fun ~type_constraint ty = let loc = { ty.ptyp_loc with loc_ghost = true } in let arg = "arg" in let maybe_constrained_arg = if type_constraint then ppat_constraint ~loc (pvar ~loc arg) ty else pvar ~loc arg in let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc (hash_fold_of_ty ty (evar ~loc arg)) in eta_reduce_if_possible [%expr fun [%p hsv_pat] [%p maybe_constrained_arg] -> [%e hsv_expr]] and hash_fold_of_record ~loc lds value = let is_evar = function | { pexp_desc = Pexp_ident _; _ } -> true | _ -> false in assert (is_evar value); List.fold_left lds ~init:(Hsv_expr.identity ~loc) ~f:(fun hsv ld -> Hsv_expr.compose ~loc hsv (let loc = ld.pld_loc in let label = Located.map lident ld.pld_name in let should_ignore, should_warn = should_ignore_label_declaration ld in let field_handling = match ld.pld_mutable, should_ignore with | Mutable, `incorporate -> `error "require [@hash.ignore] or [@compare.ignore] on mutable record field" | (Mutable | Immutable), `ignore -> `ignore | Immutable, `incorporate -> `incorporate in let hsv = match field_handling with | `error s -> Hsv_expr.compile_error ~loc (Printf.sprintf "ppx_hash: %s" s) | `incorporate -> hash_fold_of_ty ld.pld_type (pexp_field ~loc value label) | `ignore -> Hsv_expr.identity ~loc in match should_warn with | None -> hsv | Some attribute -> Hsv_expr.with_attributes ~f:(fun attributes -> attribute :: attributes) hsv)) ;; let hash_fold_of_abstract ~loc type_name value = let str = Printf.sprintf "hash called on the type %s, which is abstract in an implementation." type_name in Hsv_expr.of_expression_unchecked [%expr let _ = hsv in let _ = [%e value] in failwith [%e estring ~loc str]] ;; * this does not change behavior ( keeps the expression side - effect if any ) , but it can make the compiler happy when the expression occurs on the rhs of an [ let rec ] binding . but it can make the compiler happy when the expression occurs on the rhs of an [let rec] binding. *) let eta_expand ~loc f = [%expr let func = [%e f] in fun x -> func x] ;; let recognize_simple_type ty = match ty.ptyp_desc with | Ptyp_constr (lident, []) -> Some lident | _ -> None ;; let hash_of_ty_fun ~special_case_simple_types ~type_constraint ty = let loc = { ty.ptyp_loc with loc_ghost = true } in let arg = "arg" in let maybe_constrained_arg = if type_constraint then ppat_constraint ~loc (pvar ~loc arg) ty else pvar ~loc arg in match recognize_simple_type ty with | Some lident when special_case_simple_types -> unapplied_type_constr_conv ~loc lident ~f:hash_ | _ -> let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc (hash_fold_of_ty ty (evar ~loc arg)) in [%expr fun [%p maybe_constrained_arg] -> Ppx_hash_lib.Std.Hash.get_hash_value (let [%p hsv_pat] = Ppx_hash_lib.Std.Hash.create () in [%e hsv_expr])] ;; let hash_structure_item_of_td td = let loc = td.ptype_loc in match td.ptype_params with | _ :: _ -> [] | [] -> [ (let bnd = pvar ~loc (hash_ td.ptype_name.txt) in let typ = combinator_type_of_type_declaration td ~f:hash_type in let pat = ppat_constraint ~loc bnd typ in let expected_scope, expr = let is_simple_type ty = match recognize_simple_type ty with | Some _ -> true | None -> false in match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, Some ty when is_simple_type ty -> ( `uses_rhs , hash_of_ty_fun ~special_case_simple_types:true ~type_constraint:false ty ) | _ -> ( `uses_hash_fold_t_being_defined , hash_of_ty_fun ~special_case_simple_types:false ~type_constraint:false { ptyp_loc = loc ; ptyp_loc_stack = [] ; ptyp_attributes = [] ; ptyp_desc = Ptyp_constr ({ loc; txt = Lident td.ptype_name.txt }, []) } ) in expected_scope, value_binding ~loc ~pat ~expr:(eta_expand ~loc expr)) ] ;; let hash_fold_structure_item_of_td td ~rec_flag = let loc = { td.ptype_loc with loc_ghost = true } in let arg = "arg" in let body = let v = evar ~loc arg in match td.ptype_kind with | Ptype_variant cds -> hash_sum ~loc cds v | Ptype_record lds -> hash_fold_of_record ~loc lds v | Ptype_open -> Hsv_expr.compile_error ~loc "ppx_hash: open types are not supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> hash_fold_of_abstract ~loc td.ptype_name.txt v | Some ty -> (match ty.ptyp_desc with | Ptyp_variant (_, Open, _) | Ptyp_variant (_, Closed, Some (_ :: _)) -> Hsv_expr.compile_error ~loc:ty.ptyp_loc "ppx_hash: cannot hash open polymorphic variant types" | Ptyp_variant (row_fields, _, _) -> hash_variant ~loc row_fields v | _ -> hash_fold_of_ty ty v)) in let vars = List.map td.ptype_params ~f:(fun p -> get_type_param_name p) in let extra_names = List.map vars ~f:(fun x -> tp_name x.txt) in let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc body in let patts = List.map extra_names ~f:(pvar ~loc) @ [ hsv_pat; pvar ~loc arg ] in let bnd = pvar ~loc (hash_fold_ td.ptype_name.txt) in let scheme = combinator_type_of_type_declaration td ~f:hash_fold_type in let pat = ppat_constraint ~loc bnd (ptyp_poly ~loc vars scheme) in let expr = eta_reduce_if_possible_and_nonrec ~rec_flag (eabstract ~loc patts hsv_expr) in let use_rigid_variables = match td.ptype_kind with | Ptype_variant _ -> true | _ -> false in let expr = if use_rigid_variables then ( let type_name = td.ptype_name.txt in List.fold_right vars ~f:(fun s -> pexp_newtype ~loc { txt = rigid_type_var ~type_name s.txt; loc = s.loc }) ~init:(pexp_constraint ~loc expr (make_type_rigid ~type_name scheme))) else expr in value_binding ~loc ~pat ~expr ;; let pstr_value ~loc rec_flag bindings = match bindings with | [] -> [] | nonempty_bindings -> [ pstr_value ] with zero bindings is invalid [ pstr_value ~loc rec_flag nonempty_bindings ] ;; let str_type_decl ~loc ~path:_ (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = (object inherit type_is_recursive rec_flag tds as super method! label_declaration ld = match fst (should_ignore_label_declaration ld) with | `ignore -> () | `incorporate -> super#label_declaration ld method! core_type ty = if core_type_is_ignored ty then () else super#core_type ty end) #go () in let hash_fold_bindings = List.map ~f:(hash_fold_structure_item_of_td ~rec_flag) tds in let hash_bindings = List.concat (List.map ~f:hash_structure_item_of_td tds) in match rec_flag with | Recursive -> (* if we wanted to maximize the scope hygiene here this would be, in this order: - recursive group of [hash_fold] - nonrecursive group of [hash] that are [`uses_hash_fold_t_being_defined] - recursive group of [hash] that are [`uses_rhs] but fighting the "unused rec flag" warning is just way too hard *) pstr_value ~loc Recursive (hash_fold_bindings @ List.map ~f:snd hash_bindings) | Nonrecursive -> let rely_on_hash_fold_t, use_rhs = List.partition_map hash_bindings ~f:(function | `uses_hash_fold_t_being_defined, binding -> First binding | `uses_rhs, binding -> Second binding) in pstr_value ~loc Nonrecursive (hash_fold_bindings @ use_rhs) @ pstr_value ~loc Nonrecursive rely_on_hash_fold_t ;; let mk_sig ~loc:_ ~path:_ (_rec_flag, tds) = List.concat (List.map tds ~f:(fun td -> let monomorphic = List.is_empty td.ptype_params in let definition ~f_type ~f_name = let type_ = combinator_type_of_type_declaration td ~f:f_type in let name = let tn = td.ptype_name.txt in f_name tn in let loc = td.ptype_loc in psig_value ~loc (value_description ~loc ~name:{ td.ptype_name with txt = name } ~type_ ~prim:[]) in List.concat [ [ definition ~f_type:hash_fold_type ~f_name:hash_fold_ ] ; (if monomorphic then [ definition ~f_type:hash_type ~f_name:hash_ ] else []) ])) ;; let sig_type_decl ~loc ~path (rec_flag, tds) = match mk_named_sig ~loc ~sg_name:"Ppx_hash_lib.Hashable.S" ~handle_polymorphic_variant:true tds with | Some include_info -> [ psig_include ~loc include_info ] | None -> mk_sig ~loc ~path (rec_flag, tds) ;; let hash_fold_core_type ty = hash_fold_of_ty_fun ~type_constraint:true ty let hash_core_type ty = hash_of_ty_fun ~special_case_simple_types:true ~type_constraint:true ty ;;
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppx_hash/expander/ppx_hash_expander.ml
ocaml
Avoid confusing errors with [ { mutable field : (value[@ignore]) } ] vs [ { mutable field : value [@ignore] } ] by treating them the same. Generate code to compute hash values of type [t] in folding style, following the structure of the type. Incorporate all structure when computing hash values, to maximise hash quality. Don't attempt to detect/avoid cycles - just loop. [expr] is an expression that doesn't use the [hsv] variable. Currently it's there only for documentation value, but conceptually it can be thought of as an abstract type Represents an expression that produces a hash value and uses the variable [hsv] in a linear way (mixes it in exactly once). You can think of it as a body of a function of type [Hash.state -> Hash.state] * the [_unchecked] functions all break abstraction in some way * the returned [expression] uses the binding [hsv] bound by [pattern] [case] is binding a variable that's not [hsv] and uses [hsv] on the rhs exactly once [value_binding]s should not bind or use [hsv] * renames [x] avoiding collision with [type_name] making sure [type_name] is the only free type variable The only names we assume to be in scope are [hash_fold_<TY>] So we are sure [tp_name] (which start with an [_]) will not capture them. if we wanted to maximize the scope hygiene here this would be, in this order: - recursive group of [hash_fold] - nonrecursive group of [hash] that are [`uses_hash_fold_t_being_defined] - recursive group of [hash] that are [`uses_rhs] but fighting the "unused rec flag" warning is just way too hard
open Base open Ppxlib open Ast_builder.Default module Attrs = struct let ignore_label_declaration = Attribute.declare "hash.ignore" Attribute.Context.label_declaration Ast_pattern.(pstr nil) () ;; let ignore_core_type = Attribute.declare "hash.ignore" Attribute.Context.core_type Ast_pattern.(pstr nil) () ;; let no_hashing_label_declaration = Attribute.declare "hash.no_hashing" Attribute.Context.label_declaration Ast_pattern.(pstr nil) () ;; end let str_attributes = [ Attribute.T Attrs.ignore_core_type ; Attribute.T Attrs.ignore_label_declaration ; Attribute.T Attrs.no_hashing_label_declaration ] ;; let is_ignored_gen attrs t = List.exists attrs ~f:(fun attr -> Option.is_some (Attribute.get attr t)) ;; let core_type_is_ignored ct = is_ignored_gen [ Attrs.ignore_core_type; Ppx_compare_expander.Compare.Attrs.ignore_core_type ] ct ;; let should_ignore_label_declaration ld = let warning = "[@hash.no_hashing] is deprecated. Use [@hash.ignore]." in let is_ignored = is_ignored_gen [ Attrs.ignore_label_declaration ; Ppx_compare_expander.Compare.Attrs.ignore_label_declaration ] ld || core_type_is_ignored ld.pld_type in match Attribute.get Attrs.no_hashing_label_declaration ld with | None -> (if is_ignored then `ignore else `incorporate), None | Some () -> `ignore, Some (attribute_of_warning ld.pld_loc warning) ;; let hash_state_t ~loc = [%type: Ppx_hash_lib.Std.Hash.state] let hash_fold_type ~loc ty = let loc = { loc with loc_ghost = true } in [%type: [%t hash_state_t ~loc] -> [%t ty] -> [%t hash_state_t ~loc]] ;; let hash_type ~loc ty = let loc = { loc with loc_ghost = true } in [%type: [%t ty] -> Ppx_hash_lib.Std.Hash.hash_value] ;; type expr = expression module Hsv_expr : sig type t val identity : loc:location -> t val invoke_hash_fold_t : loc:location -> hash_fold_t:expr -> t:expr -> t val compose : loc:location -> t -> t -> t val compile_error : loc:location -> string -> t val of_expression_unchecked : expr -> t val to_expression : loc:location -> t -> pattern * expression type case val compile_error_case : loc:location -> string -> case val pexp_match : loc:location -> expr -> case list -> t [ lhs ] should not bind [ hsv ] val case : lhs:pattern -> guard:expr option -> rhs:t -> case val pexp_let : loc:location -> rec_flag -> value_binding list -> t -> t val with_attributes : f:(attribute list -> attribute list) -> t -> t end = struct type t = expression type nonrec case = case let invoke_hash_fold_t ~loc ~hash_fold_t ~t = eapply ~loc hash_fold_t [ [%expr hsv]; t ] let identity ~loc = [%expr hsv] let compose ~loc a b = [%expr let hsv = [%e a] in [%e b]] ;; let to_expression ~loc x = [%pat? hsv], x let of_expression_unchecked x = x let pexp_match = pexp_match let case = case let pexp_let = pexp_let let with_attributes ~f x = { x with pexp_attributes = f x.pexp_attributes } let compile_error ~loc s = pexp_extension ~loc (Location.Error.to_extension (Location.Error.createf ~loc "%s" s)) ;; let compile_error_case ~loc s = case ~lhs:(ppat_any ~loc) ~guard:None ~rhs:(compile_error ~loc s) ;; end let hash_fold_int ~loc i : Hsv_expr.t = Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:[%expr Ppx_hash_lib.Std.Hash.fold_int] ~t:(eint ~loc i) ;; let special_case_types_named_t = function | `hash_fold -> false | `hash -> true ;; let hash_fold_ tn = match tn with | "t" when special_case_types_named_t `hash_fold -> "hash_fold" | _ -> "hash_fold_" ^ tn ;; let hash_ tn = match tn with | "t" when special_case_types_named_t `hash -> "hash" | _ -> "hash_" ^ tn ;; let rigid_type_var ~type_name x = let prefix = "rigid_" in if String.equal x type_name || String.is_prefix x ~prefix then prefix ^ x ^ "_of_type_" ^ type_name else x ;; let make_type_rigid ~type_name = let map = object inherit Ast_traverse.map as super method! core_type ty = let ptyp_desc = let () = match ty.ptyp_desc with | Ptyp_constr (name, _args) -> (match name.txt with | Ldot _ | Lapply _ -> () | Lident name -> if not (String.equal name type_name) then Location.raise_errorf ~loc:ty.ptyp_loc "ppx_hash: make_type_rigid: unexpected type %S. expected to only \ find %S" (string_of_core_type ty) type_name; ()) | _ -> () in match ty.ptyp_desc with | Ptyp_var s -> Ptyp_constr (Located.lident ~loc:ty.ptyp_loc (rigid_type_var ~type_name s), []) | desc -> super#core_type_desc desc in { ty with ptyp_desc } end in map#core_type ;; let tp_name n = Printf.sprintf "_hash_fold_%s" n let with_tuple loc (value : expr) xs (f : (expr * core_type) list -> Hsv_expr.t) : Hsv_expr.t = let names = List.mapi ~f:(fun i t -> Printf.sprintf "e%d" i, t) xs in let pattern = let l = List.map ~f:(fun (n, _) -> pvar ~loc n) names in ppat_tuple ~loc l in let e = f (List.map ~f:(fun (n, t) -> evar ~loc n, t) names) in let binding = value_binding ~loc ~pat:pattern ~expr:value in Hsv_expr.pexp_let ~loc Nonrecursive [ binding ] e ;; let hash_ignore ~loc value = Hsv_expr.pexp_let ~loc Nonrecursive [ value_binding ~loc ~pat:[%pat? _] ~expr:value ] (Hsv_expr.identity ~loc) ;; let ghostify_located (t : 'a loc) : 'a loc = { t with loc = { t.loc with loc_ghost = true } } ;; let rec hash_applied ty value = let loc = { ty.ptyp_loc with loc_ghost = true } in match ty.ptyp_desc with | Ptyp_constr (name, ta) -> let args = List.map ta ~f:(hash_fold_of_ty_fun ~type_constraint:false) in Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:(type_constr_conv ~loc name ~f:hash_fold_ args) ~t:value | _ -> assert false and hash_fold_of_tuple ~loc tys value = with_tuple loc value tys (fun elems1 -> List.fold_right elems1 ~init:(Hsv_expr.identity ~loc) ~f:(fun (v, t) (result : Hsv_expr.t) -> Hsv_expr.compose ~loc (hash_fold_of_ty t v) result)) and hash_variant ~loc row_fields value = let map row = match row.prf_desc with | Rtag ({ txt = cnstr; _ }, true, _) | Rtag ({ txt = cnstr; _ }, _, []) -> Hsv_expr.case ~guard:None ~lhs:(ppat_variant ~loc cnstr None) ~rhs:(hash_fold_int ~loc (Ocaml_common.Btype.hash_variant cnstr)) | Rtag ({ txt = cnstr; _ }, false, tp :: _) -> let v = "_v" in let body = Hsv_expr.compose ~loc (hash_fold_int ~loc (Ocaml_common.Btype.hash_variant cnstr)) (hash_fold_of_ty tp (evar ~loc v)) in Hsv_expr.case ~guard:None ~lhs:(ppat_variant ~loc cnstr (Some (pvar ~loc v))) ~rhs:body | Rinherit ({ ptyp_desc = Ptyp_constr (id, _); _ } as ty) -> Generated code from .. type ' a i d = ' a [ @@deriving hash ] type t = [ ` a | [ ` b ] i d ] [ @@deriving hash ] does n't compile : Also see the " sadly " note in : ppx_compare_expander.ml type 'a id = 'a [@@deriving hash] type t = [ `a | [ `b ] id ] [@@deriving hash] doesn't compile: Also see the "sadly" note in: ppx_compare_expander.ml *) let v = "_v" in Hsv_expr.case ~guard:None ~lhs:(ppat_alias ~loc (ppat_type ~loc (ghostify_located id)) (Located.mk ~loc v)) ~rhs:(hash_applied ty (evar ~loc v)) | Rinherit ty -> let s = string_of_core_type ty in Hsv_expr.compile_error_case ~loc (Printf.sprintf "ppx_hash: impossible variant case: %s" s) in Hsv_expr.pexp_match ~loc value (List.map ~f:map row_fields) and branch_of_sum hsv ~loc cd = match cd.pcd_args with | Pcstr_tuple [] -> let pcnstr = pconstruct cd None in Hsv_expr.case ~guard:None ~lhs:pcnstr ~rhs:hsv | Pcstr_tuple tps -> let ids_ty = List.mapi tps ~f:(fun i ty -> Printf.sprintf "_a%d" i, ty) in let lpatt = List.map ids_ty ~f:(fun (l, _ty) -> pvar ~loc l) |> ppat_tuple ~loc and body = List.fold_left ids_ty ~init:(Hsv_expr.identity ~loc) ~f:(fun expr (l, ty) -> Hsv_expr.compose ~loc expr (hash_fold_of_ty ty (evar ~loc l))) in Hsv_expr.case ~guard:None ~lhs:(pconstruct cd (Some lpatt)) ~rhs:(Hsv_expr.compose ~loc hsv body) | Pcstr_record lds -> let arg = "_ir" in let pat = pvar ~loc arg in let v = evar ~loc arg in let body = hash_fold_of_record ~loc lds v in Hsv_expr.case ~guard:None ~lhs:(pconstruct cd (Some pat)) ~rhs:(Hsv_expr.compose ~loc hsv body) and branches_of_sum = function | [ cd ] -> this is an optimization : we do n't need to mix in the constructor tag if the type only has one constructor only has one constructor *) let loc = cd.pcd_loc in [ branch_of_sum (Hsv_expr.identity ~loc) ~loc cd ] | cds -> List.mapi cds ~f:(fun i cd -> let loc = cd.pcd_loc in let hsv = hash_fold_int ~loc i in branch_of_sum hsv ~loc cd) and hash_sum ~loc cds value = Hsv_expr.pexp_match ~loc value (branches_of_sum cds) and hash_fold_of_ty ty value = let loc = { ty.ptyp_loc with loc_ghost = true } in if core_type_is_ignored ty then hash_ignore ~loc value else ( match ty.ptyp_desc with | Ptyp_constr _ -> hash_applied ty value | Ptyp_tuple tys -> hash_fold_of_tuple ~loc tys value | Ptyp_var name -> Hsv_expr.invoke_hash_fold_t ~loc ~hash_fold_t:(evar ~loc (tp_name name)) ~t:value | Ptyp_arrow _ -> Hsv_expr.compile_error ~loc "ppx_hash: functions can not be hashed." | Ptyp_variant (row_fields, Closed, _) -> hash_variant ~loc row_fields value | _ -> let s = string_of_core_type ty in Hsv_expr.compile_error ~loc (Printf.sprintf "ppx_hash: unsupported type: %s" s)) and hash_fold_of_ty_fun ~type_constraint ty = let loc = { ty.ptyp_loc with loc_ghost = true } in let arg = "arg" in let maybe_constrained_arg = if type_constraint then ppat_constraint ~loc (pvar ~loc arg) ty else pvar ~loc arg in let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc (hash_fold_of_ty ty (evar ~loc arg)) in eta_reduce_if_possible [%expr fun [%p hsv_pat] [%p maybe_constrained_arg] -> [%e hsv_expr]] and hash_fold_of_record ~loc lds value = let is_evar = function | { pexp_desc = Pexp_ident _; _ } -> true | _ -> false in assert (is_evar value); List.fold_left lds ~init:(Hsv_expr.identity ~loc) ~f:(fun hsv ld -> Hsv_expr.compose ~loc hsv (let loc = ld.pld_loc in let label = Located.map lident ld.pld_name in let should_ignore, should_warn = should_ignore_label_declaration ld in let field_handling = match ld.pld_mutable, should_ignore with | Mutable, `incorporate -> `error "require [@hash.ignore] or [@compare.ignore] on mutable record field" | (Mutable | Immutable), `ignore -> `ignore | Immutable, `incorporate -> `incorporate in let hsv = match field_handling with | `error s -> Hsv_expr.compile_error ~loc (Printf.sprintf "ppx_hash: %s" s) | `incorporate -> hash_fold_of_ty ld.pld_type (pexp_field ~loc value label) | `ignore -> Hsv_expr.identity ~loc in match should_warn with | None -> hsv | Some attribute -> Hsv_expr.with_attributes ~f:(fun attributes -> attribute :: attributes) hsv)) ;; let hash_fold_of_abstract ~loc type_name value = let str = Printf.sprintf "hash called on the type %s, which is abstract in an implementation." type_name in Hsv_expr.of_expression_unchecked [%expr let _ = hsv in let _ = [%e value] in failwith [%e estring ~loc str]] ;; * this does not change behavior ( keeps the expression side - effect if any ) , but it can make the compiler happy when the expression occurs on the rhs of an [ let rec ] binding . but it can make the compiler happy when the expression occurs on the rhs of an [let rec] binding. *) let eta_expand ~loc f = [%expr let func = [%e f] in fun x -> func x] ;; let recognize_simple_type ty = match ty.ptyp_desc with | Ptyp_constr (lident, []) -> Some lident | _ -> None ;; let hash_of_ty_fun ~special_case_simple_types ~type_constraint ty = let loc = { ty.ptyp_loc with loc_ghost = true } in let arg = "arg" in let maybe_constrained_arg = if type_constraint then ppat_constraint ~loc (pvar ~loc arg) ty else pvar ~loc arg in match recognize_simple_type ty with | Some lident when special_case_simple_types -> unapplied_type_constr_conv ~loc lident ~f:hash_ | _ -> let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc (hash_fold_of_ty ty (evar ~loc arg)) in [%expr fun [%p maybe_constrained_arg] -> Ppx_hash_lib.Std.Hash.get_hash_value (let [%p hsv_pat] = Ppx_hash_lib.Std.Hash.create () in [%e hsv_expr])] ;; let hash_structure_item_of_td td = let loc = td.ptype_loc in match td.ptype_params with | _ :: _ -> [] | [] -> [ (let bnd = pvar ~loc (hash_ td.ptype_name.txt) in let typ = combinator_type_of_type_declaration td ~f:hash_type in let pat = ppat_constraint ~loc bnd typ in let expected_scope, expr = let is_simple_type ty = match recognize_simple_type ty with | Some _ -> true | None -> false in match td.ptype_kind, td.ptype_manifest with | Ptype_abstract, Some ty when is_simple_type ty -> ( `uses_rhs , hash_of_ty_fun ~special_case_simple_types:true ~type_constraint:false ty ) | _ -> ( `uses_hash_fold_t_being_defined , hash_of_ty_fun ~special_case_simple_types:false ~type_constraint:false { ptyp_loc = loc ; ptyp_loc_stack = [] ; ptyp_attributes = [] ; ptyp_desc = Ptyp_constr ({ loc; txt = Lident td.ptype_name.txt }, []) } ) in expected_scope, value_binding ~loc ~pat ~expr:(eta_expand ~loc expr)) ] ;; let hash_fold_structure_item_of_td td ~rec_flag = let loc = { td.ptype_loc with loc_ghost = true } in let arg = "arg" in let body = let v = evar ~loc arg in match td.ptype_kind with | Ptype_variant cds -> hash_sum ~loc cds v | Ptype_record lds -> hash_fold_of_record ~loc lds v | Ptype_open -> Hsv_expr.compile_error ~loc "ppx_hash: open types are not supported" | Ptype_abstract -> (match td.ptype_manifest with | None -> hash_fold_of_abstract ~loc td.ptype_name.txt v | Some ty -> (match ty.ptyp_desc with | Ptyp_variant (_, Open, _) | Ptyp_variant (_, Closed, Some (_ :: _)) -> Hsv_expr.compile_error ~loc:ty.ptyp_loc "ppx_hash: cannot hash open polymorphic variant types" | Ptyp_variant (row_fields, _, _) -> hash_variant ~loc row_fields v | _ -> hash_fold_of_ty ty v)) in let vars = List.map td.ptype_params ~f:(fun p -> get_type_param_name p) in let extra_names = List.map vars ~f:(fun x -> tp_name x.txt) in let hsv_pat, hsv_expr = Hsv_expr.to_expression ~loc body in let patts = List.map extra_names ~f:(pvar ~loc) @ [ hsv_pat; pvar ~loc arg ] in let bnd = pvar ~loc (hash_fold_ td.ptype_name.txt) in let scheme = combinator_type_of_type_declaration td ~f:hash_fold_type in let pat = ppat_constraint ~loc bnd (ptyp_poly ~loc vars scheme) in let expr = eta_reduce_if_possible_and_nonrec ~rec_flag (eabstract ~loc patts hsv_expr) in let use_rigid_variables = match td.ptype_kind with | Ptype_variant _ -> true | _ -> false in let expr = if use_rigid_variables then ( let type_name = td.ptype_name.txt in List.fold_right vars ~f:(fun s -> pexp_newtype ~loc { txt = rigid_type_var ~type_name s.txt; loc = s.loc }) ~init:(pexp_constraint ~loc expr (make_type_rigid ~type_name scheme))) else expr in value_binding ~loc ~pat ~expr ;; let pstr_value ~loc rec_flag bindings = match bindings with | [] -> [] | nonempty_bindings -> [ pstr_value ] with zero bindings is invalid [ pstr_value ~loc rec_flag nonempty_bindings ] ;; let str_type_decl ~loc ~path:_ (rec_flag, tds) = let tds = List.map tds ~f:name_type_params_in_td in let rec_flag = (object inherit type_is_recursive rec_flag tds as super method! label_declaration ld = match fst (should_ignore_label_declaration ld) with | `ignore -> () | `incorporate -> super#label_declaration ld method! core_type ty = if core_type_is_ignored ty then () else super#core_type ty end) #go () in let hash_fold_bindings = List.map ~f:(hash_fold_structure_item_of_td ~rec_flag) tds in let hash_bindings = List.concat (List.map ~f:hash_structure_item_of_td tds) in match rec_flag with | Recursive -> pstr_value ~loc Recursive (hash_fold_bindings @ List.map ~f:snd hash_bindings) | Nonrecursive -> let rely_on_hash_fold_t, use_rhs = List.partition_map hash_bindings ~f:(function | `uses_hash_fold_t_being_defined, binding -> First binding | `uses_rhs, binding -> Second binding) in pstr_value ~loc Nonrecursive (hash_fold_bindings @ use_rhs) @ pstr_value ~loc Nonrecursive rely_on_hash_fold_t ;; let mk_sig ~loc:_ ~path:_ (_rec_flag, tds) = List.concat (List.map tds ~f:(fun td -> let monomorphic = List.is_empty td.ptype_params in let definition ~f_type ~f_name = let type_ = combinator_type_of_type_declaration td ~f:f_type in let name = let tn = td.ptype_name.txt in f_name tn in let loc = td.ptype_loc in psig_value ~loc (value_description ~loc ~name:{ td.ptype_name with txt = name } ~type_ ~prim:[]) in List.concat [ [ definition ~f_type:hash_fold_type ~f_name:hash_fold_ ] ; (if monomorphic then [ definition ~f_type:hash_type ~f_name:hash_ ] else []) ])) ;; let sig_type_decl ~loc ~path (rec_flag, tds) = match mk_named_sig ~loc ~sg_name:"Ppx_hash_lib.Hashable.S" ~handle_polymorphic_variant:true tds with | Some include_info -> [ psig_include ~loc include_info ] | None -> mk_sig ~loc ~path (rec_flag, tds) ;; let hash_fold_core_type ty = hash_fold_of_ty_fun ~type_constraint:true ty let hash_core_type ty = hash_of_ty_fun ~special_case_simple_types:true ~type_constraint:true ty ;;
f95722fa10242c1bfc77bb8fc4e0cac86fa05e541474084866dc0787bcfbb943
UU-ComputerScience/js-asteroids
HTML5.hs
module Language.UHC.JS.W3C.HTML5 ( Document , documentAnchors , documentForms , documentImages , documentLinks , document , documentWriteln, documentWrite , documentGetElementById, documentGetElementsByName, documentGetElementsByTagName , documentCreateElement , Anchor , anchorCharset , anchorHref , anchorHreflang , anchorName , anchorRel , anchorRev , anchorTarget , anchorType , Form , Image , Link , Element , elementValue , elementInnerHTML , elementTagName , elementClientWidth , elementClientHeight , elementAttributes , elementSetAttribute , elementAppendChild , Attr , attrValue , NamedNodeMap , namedNodeMapLength , namedNodeMapItem , namedNodeMapNamedItem , namedNodeMapRemoveNamedItem , namedNodeMapSetNamedItem , Node , nodeName , nodeType , NodeList , nodeListItem , nodeListLength , pathName , encodeURIComponent , _encodeURIComponent ) where import Language.UHC.JS.Types import Language.UHC.JS.Primitives import Language.UHC.JS.ECMA.Array import Language.UHC.JS.ECMA.String import Language.UHC.JS.Marshal import Data.Maybe (fromJust) data DocumentPtr type Document = JSObject_ DocumentPtr foreign import js "document" document :: IO Document foreign import js "%1.anchors" documentAnchors :: Document -> JSArray Anchor foreign import js "%1.forms" documentForms :: Document -> JSArray Form foreign import js "%1.images" documentImages :: Document -> JSArray Image foreign import js "%1.links" documentLinks :: Document -> JSArray Link foreign import js "%1.write(%*)" documentWrite :: Document -> JSString -> IO () foreign import js "%1.writeln(%*)" documentWriteln :: Document -> JSString -> IO () foreign import js "%1.getElementById(%*)" documentGetElementById :: Document -> JSString -> IO Node foreign import js "%1.getElementsByName(%*)" documentGetElementsByName :: Document -> JSString -> IO (NodeList Node) documentGetElementsByTagName :: Document -> String -> IO (NodeList Node) documentGetElementsByTagName d = _documentGetElementsByTagName d . stringToJSString foreign import js "%1.getElementsByTagName(%*)" _documentGetElementsByTagName :: Document -> JSString -> IO (NodeList Node) documentCreateElement :: String -> IO Node documentCreateElement elem = _documentCreateElement (stringToJSString elem :: JSString) foreign import js "document.createElement(%*)" _documentCreateElement :: JSString -> IO Node data AnchorPtr type Anchor = JSObject_ AnchorPtr foreign import js "%1.charset" anchorCharset :: Anchor -> JSString foreign import js "%1.href" anchorHref :: Anchor -> JSString foreign import js "%1.hreflang" anchorHreflang :: Anchor -> JSString foreign import js "%1.name" anchorName :: Anchor -> JSString foreign import js "%1.rel" anchorRel :: Anchor -> JSString foreign import js "%1.rev" anchorRev :: Anchor -> JSString foreign import js "%1.target" anchorTarget :: Anchor -> JSString foreign import js "%1.type" anchorType :: Anchor -> JSString data FormPtr type Form = JSObject_ FormPtr foreign import js "%1.elements" formElements :: Form -> JSArray Element data ImagePtr type Image = JSObject_ ImagePtr data LinkPtr type Link = JSObject_ LinkPtr data ElementPtr type Element = JSObject_ ElementPtr foreign import js "%1.innerHTML" elementInnerHTML :: Node -> JSString foreign import js "%1.value" elementValue :: Node -> JSString foreign import js "%1.tagName" elementTagName :: Node -> JSString foreign import js "%1.clientWidth" elementClientWidth :: Node -> Int foreign import js "%1.clientHeight" elementClientHeight :: Node -> Int foreign import js "%1.attributes" elementAttributes :: Node -> NamedNodeMap Node elementSetAttribute :: Node -> String -> String -> IO () elementSetAttribute n k v = _elementSetAttribute n (stringToJSString k :: JSString) (stringToJSString v :: JSString) foreign import js "%1.setAttribute(%*)" _elementSetAttribute :: Node -> JSString -> JSString -> IO () foreign import js "%1.appendChild(%2)" elementAppendChild :: Node -> Node -> IO () data NodePtr type Node = JSObject_ NodePtr foreign import js "%1.nodeName" nodeName :: Node -> JSString foreign import js "%1.nodeType" nodeType :: Node -> Int data NodeListPtr x type NodeList x = JSObject_ (NodeListPtr x) foreign import js "%1.length" nodeListLength :: NodeList Node -> Int foreign import js "%1[%2]" nodeListItem :: NodeList Node -> Int -> IO Node data NamedNodeMapPtr x type NamedNodeMap x = JSObject_ (NamedNodeMapPtr x) foreign import js "%1.length" namedNodeMapLength :: NamedNodeMap Node -> Int foreign import js "%1[%2]" namedNodeMapItem :: NamedNodeMap Node -> Int -> IO Node foreign import js "%1.getNamedItem(%*)" namedNodeMapNamedItem :: NamedNodeMap Node -> JSString -> IO Node foreign import js "%1.removeNamedItem(%*)" namedNodeMapRemoveNamedItem :: NamedNodeMap Node -> JSString -> IO Node foreign import js "%1.setNamedItem(%*)" namedNodeMapSetNamedItem :: NamedNodeMap Node -> Node -> IO Node data AttrPtr type Attr = JSObject_ AttrPtr foreign import js "%1.value" attrValue :: Attr -> JSString foreign import js "window.location.pathname" _pathName :: IO JSString pathName :: IO String pathName = liftFromJS_ _pathName encodeURIComponent :: String -> String encodeURIComponent = fromJust . (fromJS :: JSString -> Maybe String) . _encodeURIComponent . (toJS :: String -> JSString) foreign import js "encodeURIComponent(%1)" _encodeURIComponent :: JSString -> JSString
null
https://raw.githubusercontent.com/UU-ComputerScience/js-asteroids/b7015d8ad4aa57ff30f2631e0945462f6e1ef47a/uhc-js/uhc-js/src/Language/UHC/JS/W3C/HTML5.hs
haskell
module Language.UHC.JS.W3C.HTML5 ( Document , documentAnchors , documentForms , documentImages , documentLinks , document , documentWriteln, documentWrite , documentGetElementById, documentGetElementsByName, documentGetElementsByTagName , documentCreateElement , Anchor , anchorCharset , anchorHref , anchorHreflang , anchorName , anchorRel , anchorRev , anchorTarget , anchorType , Form , Image , Link , Element , elementValue , elementInnerHTML , elementTagName , elementClientWidth , elementClientHeight , elementAttributes , elementSetAttribute , elementAppendChild , Attr , attrValue , NamedNodeMap , namedNodeMapLength , namedNodeMapItem , namedNodeMapNamedItem , namedNodeMapRemoveNamedItem , namedNodeMapSetNamedItem , Node , nodeName , nodeType , NodeList , nodeListItem , nodeListLength , pathName , encodeURIComponent , _encodeURIComponent ) where import Language.UHC.JS.Types import Language.UHC.JS.Primitives import Language.UHC.JS.ECMA.Array import Language.UHC.JS.ECMA.String import Language.UHC.JS.Marshal import Data.Maybe (fromJust) data DocumentPtr type Document = JSObject_ DocumentPtr foreign import js "document" document :: IO Document foreign import js "%1.anchors" documentAnchors :: Document -> JSArray Anchor foreign import js "%1.forms" documentForms :: Document -> JSArray Form foreign import js "%1.images" documentImages :: Document -> JSArray Image foreign import js "%1.links" documentLinks :: Document -> JSArray Link foreign import js "%1.write(%*)" documentWrite :: Document -> JSString -> IO () foreign import js "%1.writeln(%*)" documentWriteln :: Document -> JSString -> IO () foreign import js "%1.getElementById(%*)" documentGetElementById :: Document -> JSString -> IO Node foreign import js "%1.getElementsByName(%*)" documentGetElementsByName :: Document -> JSString -> IO (NodeList Node) documentGetElementsByTagName :: Document -> String -> IO (NodeList Node) documentGetElementsByTagName d = _documentGetElementsByTagName d . stringToJSString foreign import js "%1.getElementsByTagName(%*)" _documentGetElementsByTagName :: Document -> JSString -> IO (NodeList Node) documentCreateElement :: String -> IO Node documentCreateElement elem = _documentCreateElement (stringToJSString elem :: JSString) foreign import js "document.createElement(%*)" _documentCreateElement :: JSString -> IO Node data AnchorPtr type Anchor = JSObject_ AnchorPtr foreign import js "%1.charset" anchorCharset :: Anchor -> JSString foreign import js "%1.href" anchorHref :: Anchor -> JSString foreign import js "%1.hreflang" anchorHreflang :: Anchor -> JSString foreign import js "%1.name" anchorName :: Anchor -> JSString foreign import js "%1.rel" anchorRel :: Anchor -> JSString foreign import js "%1.rev" anchorRev :: Anchor -> JSString foreign import js "%1.target" anchorTarget :: Anchor -> JSString foreign import js "%1.type" anchorType :: Anchor -> JSString data FormPtr type Form = JSObject_ FormPtr foreign import js "%1.elements" formElements :: Form -> JSArray Element data ImagePtr type Image = JSObject_ ImagePtr data LinkPtr type Link = JSObject_ LinkPtr data ElementPtr type Element = JSObject_ ElementPtr foreign import js "%1.innerHTML" elementInnerHTML :: Node -> JSString foreign import js "%1.value" elementValue :: Node -> JSString foreign import js "%1.tagName" elementTagName :: Node -> JSString foreign import js "%1.clientWidth" elementClientWidth :: Node -> Int foreign import js "%1.clientHeight" elementClientHeight :: Node -> Int foreign import js "%1.attributes" elementAttributes :: Node -> NamedNodeMap Node elementSetAttribute :: Node -> String -> String -> IO () elementSetAttribute n k v = _elementSetAttribute n (stringToJSString k :: JSString) (stringToJSString v :: JSString) foreign import js "%1.setAttribute(%*)" _elementSetAttribute :: Node -> JSString -> JSString -> IO () foreign import js "%1.appendChild(%2)" elementAppendChild :: Node -> Node -> IO () data NodePtr type Node = JSObject_ NodePtr foreign import js "%1.nodeName" nodeName :: Node -> JSString foreign import js "%1.nodeType" nodeType :: Node -> Int data NodeListPtr x type NodeList x = JSObject_ (NodeListPtr x) foreign import js "%1.length" nodeListLength :: NodeList Node -> Int foreign import js "%1[%2]" nodeListItem :: NodeList Node -> Int -> IO Node data NamedNodeMapPtr x type NamedNodeMap x = JSObject_ (NamedNodeMapPtr x) foreign import js "%1.length" namedNodeMapLength :: NamedNodeMap Node -> Int foreign import js "%1[%2]" namedNodeMapItem :: NamedNodeMap Node -> Int -> IO Node foreign import js "%1.getNamedItem(%*)" namedNodeMapNamedItem :: NamedNodeMap Node -> JSString -> IO Node foreign import js "%1.removeNamedItem(%*)" namedNodeMapRemoveNamedItem :: NamedNodeMap Node -> JSString -> IO Node foreign import js "%1.setNamedItem(%*)" namedNodeMapSetNamedItem :: NamedNodeMap Node -> Node -> IO Node data AttrPtr type Attr = JSObject_ AttrPtr foreign import js "%1.value" attrValue :: Attr -> JSString foreign import js "window.location.pathname" _pathName :: IO JSString pathName :: IO String pathName = liftFromJS_ _pathName encodeURIComponent :: String -> String encodeURIComponent = fromJust . (fromJS :: JSString -> Maybe String) . _encodeURIComponent . (toJS :: String -> JSString) foreign import js "encodeURIComponent(%1)" _encodeURIComponent :: JSString -> JSString
852b215fe210d74df586e0738f15a47d047fa2596299d14800a01ed6aec0b183
george-steel/maxent-learner
FeatureTableEditor.hs
# LANGUAGE LambdaCase , OverloadedStrings , ExtendedDefaultRules # module FeatureTableEditor ( createEditableFT, displayFeatureMatrix, displayDynFeatureTable ) where import Graphics.UI.Gtk import Control.FRPNow hiding (swap) import Control.FRPNow.GTK import Control.FRPNow.GTK.MissingFFI import Control.Monad import Control.Exception import Data.Tuple import Data.List import Data.Maybe import Text.PhonotacticLearner.PhonotacticConstraints import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Array.IArray import qualified Data.Map.Lazy as M import qualified Data.ByteString as B import Control.DeepSeq default (T.Text) data FTRow = FTRow T.Text (M.Map SegRef FeatureState) deriving (Eq, Show) fsTrue FPlus = True fsTrue FMinus = False fsTrue FOff = False fsInc FPlus = False fsInc FMinus = True fsInc FOff = False fsCycle FPlus = FMinus fsCycle FMinus = FOff fsCycle FOff = FPlus ft2rows ft = ffor (assocs . featNames $ ft) $ \(fi,fn) -> let sbounds = bounds (segNames ft) sidxs = indices (segNames ft) fsmap = M.fromList [(i,ftlook ft i fi) | i <- sidxs] in FTRow fn fsmap rows2ft :: Array SegRef String -> [FTRow] -> FeatureTable String rows2ft segs rows = FeatureTable ftarr fnames segs flook slook where nf = length rows (sa,sb) = bounds segs nrows = zip [1..] rows fnames = array (1,nf) [(n,fn) | (n,FTRow fn _) <- nrows] ftarr = array ((sa,1),(sb,nf)) $ do (fi, FTRow _ fsmap) <- nrows (si,fs) <- M.assocs fsmap return ((si,fi),fs) slook = M.fromList (fmap swap (assocs segs)) flook = M.fromList (fmap swap (assocs fnames)) resegft :: [String] -> FeatureTable String -> FeatureTable String resegft segs oldft = FeatureTable ftarr fnames segsarr flook slook where fnames = featNames oldft flook = featLookup oldft (fa,fb) = bounds fnames uniqsegs = nub segs nsegs = length uniqsegs segsarr = listArray (Seg 1, Seg nsegs) uniqsegs slook = M.fromList (fmap swap (assocs segsarr)) ftarr = array ((Seg 1,fa), (Seg nsegs,fb)) $ do f <- indices fnames (sr,s) <- assocs segsarr let fs = fromMaybe FOff $ do sr' <- M.lookup s (segLookup oldft) return $ ftlook oldft sr' f return ((sr,f),fs) setFTContents :: TreeView -> FeatureTable String -> IO (Array SegRef String, ListStore FTRow) setFTContents editor newft = do let segs = segNames newft rows = ft2rows newft model <- listStoreNew rows oldcols <- treeViewGetColumns editor forM_ oldcols $ \col -> treeViewRemoveColumn editor col treeViewSetModel editor model lcol <- treeViewColumnNew set lcol [treeViewColumnTitle := "Feature"] lcell <- cellRendererTextNew set lcell [cellTextEditable := True] cellLayoutPackStart lcol lcell True treeViewAppendColumn editor lcol cellLayoutSetAttributes lcol lcell model $ \(FTRow fn _) -> [cellText := fn] on lcell edited $ \[i] newtext -> do FTRow _ fsmap <- listStoreGetValue model i listStoreSetValue model i (FTRow newtext fsmap) forM_ (assocs segs) $ \(si,sn) -> do col <- treeViewColumnNew set col [treeViewColumnTitle := sn] cell <- cellRendererToggleNew cellLayoutPackStart col cell True treeViewAppendColumn editor col cellLayoutSetAttributes col cell model $ \(FTRow _ fsmap) -> [cellToggleActive := fsTrue (fsmap M.! si), cellToggleInconsistent := fsInc (fsmap M.! si)] on cell cellToggled $ \tpStr -> do let [i] = stringToTreePath tpStr FTRow fn fsmap <- listStoreGetValue model i let newrow = FTRow fn (M.adjust fsCycle si fsmap) listStoreSetValue model i newrow pcol <- treeViewColumnNew treeViewAppendColumn editor pcol return (segs, model) watchFtModel :: (Array SegRef String, ListStore FTRow) -> Now (Behavior (FeatureTable String)) watchFtModel (segs, model) = do (rowsChanged, rowcb) <- callbackStream let changecb = listStoreToList model >>= rowcb sync $ do on model rowChanged $ \_ _ -> changecb on model rowInserted $ \_ _ -> changecb on model rowDeleted $ \_ -> changecb initrows <- sync $ listStoreToList model dynrows <- sample $ fromChanges initrows rowsChanged return $ fmap (rows2ft segs) dynrows loadFTfromFile :: FilePath -> IO (Maybe (FeatureTable String)) loadFTfromFile fp = fmap join . checkIOError $ do bincsv <- B.readFile fp evaluate $ force . csvToFeatureTable id . T.unpack =<< either (const Nothing) Just (T.decodeUtf8' bincsv) runTextDialog :: Maybe Window -> T.Text -> T.Text -> Now (Event (Maybe T.Text)) runTextDialog transwin q defa = do (retev, cb) <- callback dia <- sync $ dialogNew ent <- sync $ entryNew sync $ do case transwin of Just win -> set dia [windowTransientFor := win, windowModal := True] Nothing -> return () dialogAddButton dia "gtk-ok" ResponseOk dialogAddButton dia "gtk-cancel" ResponseCancel ca <- castToBox <$> dialogGetContentArea dia entrySetText ent defa lbl <- createLabel q boxPackStart ca lbl PackGrow 0 boxPackStart ca ent PackNatural 0 on dia response $ \resp -> do case resp of ResponseOk -> do txt <- entryGetText ent cb (Just txt) _ -> cb Nothing widgetDestroy dia widgetShowAll dia return retev createEditableFT :: Maybe Window -> FeatureTable String -> Now (VBox, Behavior (FeatureTable String)) createEditableFT transwin initft = do editor <- sync treeViewNew editor' <- createScrolledWindow editor sync $ set editor' [scrolledWindowOverlay := False] (loadButton, loadPressed) <- createButton (Just "document-open") (Just "Load Table") (saveButton, savePressed) <- createButton (Just "document-save") (Just "Save Table") (addButton, addPressed) <- createButton (Just "list-add") Nothing (delButton, delPressed) <- createButton (Just "list-remove") Nothing (editButton, isEditing) <- createToggleButton (Just "accessories-text-editor") (Just "Edit Table") False (segButton, segPressed) <- createButton Nothing (Just "Change Segments") setAttr widgetSensitive addButton isEditing setAttr widgetSensitive delButton isEditing (ftReplaced, replaceft) <- callbackStream (modelReplaced, replaceModel) <- callbackStream initmodel <- sync $ setFTContents editor initft currentModel <- sample $ fromChanges initmodel modelReplaced initdft <- watchFtModel initmodel callStream (sync . replaceft <=< watchFtModel . last) modelReplaced currentft <- sample$ foldrSwitch initdft ftReplaced viewer <- displayDynFeatureTable currentft top <- sync stackNew sync $ do stackAddNamed top viewer "False" stackAddNamed top editor' "True" setAttr stackVisibleChildName top (fmap show isEditing) vb <- createVBox 2 $ do bstretch =<< createFrame ShadowIn top bpack <=< createHBox 2 $ do bpack addButton bpack delButton bspacer bpack segButton bpack editButton bpack loadButton bpack saveButton csvfilter < - sync fileFilterNew allfilter < - sync fileFilterNew sync $ do " text / csv " " CSV " fileFilterAddPattern allfilter " * " fileFilterSetName allfilter " All Files " allfilter <- sync fileFilterNew sync $ do fileFilterAddMimeType csvfilter "text/csv" fileFilterSetName csvfilter "CSV" fileFilterAddPattern allfilter "*" fileFilterSetName allfilter "All Files" -} loadDialog <- sync $ fileChooserDialogNew (Just "Open Feature Table") transwin FileChooserActionOpen [("gtk-cancel", ResponseCancel), ("gtk-open", ResponseAccept)] sync $ fileChooserAddFilter loadDialog csvfilter sync $ fileChooserAddFilter loadDialog allfilter sync $ set loadDialog [windowModal := True] flip callStream loadPressed $ \_ -> do filePicked <- runFileChooserDialog loadDialog emft <- planNow . ffor filePicked $ \case Nothing -> return never Just fn -> async $ loadFTfromFile fn planNow . ffor (join emft) $ \case Nothing -> sync $ putStrLn "Invalid CSV table." Just newft -> sync $ do newmodel <- setFTContents editor newft replaceModel newmodel putStrLn "Feature table sucessfully loaded." return () saveDialog <- sync $ fileChooserDialogNew (Just "Save Feature Table") transwin FileChooserActionSave [("gtk-cancel", ResponseCancel), ("gtk-save", ResponseAccept)] sync $ fileChooserAddFilter saveDialog csvfilter --sync $ fileChooserAddFilter saveDialog allfilter sync $ set saveDialog [windowModal := True] flip callStream savePressed $ \_ -> do savePicked <- runFileChooserDialog saveDialog planNow . ffor savePicked $ \case Nothing -> return () Just fn -> do ft <- sample currentft async $ do let csv = featureTableToCsv id ft bincsv = T.encodeUtf8 (T.pack csv) B.writeFile fn bincsv putStrLn $ "Wrote Feature Table " ++ fn return () return () flip callStream segPressed $ \_ -> do oldft <- sample currentft let oldsegs = T.pack . unwords . elems . segNames $ oldft enewsegs <- runTextDialog transwin "Enter a new set of segments." oldsegs planNow . ffor enewsegs $ \case Nothing -> return () Just newsegs -> let segs = words (T.unpack newsegs) in case segs of [] -> return () _ -> sync $ do let newft = resegft segs oldft newmodel <- setFTContents editor newft replaceModel newmodel putStrLn "Segments Changed." return () flip callStream addPressed $ \_ -> do (segs, store) <- sample currentModel let newRow = FTRow "" (M.fromList [(s,FOff) | s <- indices segs]) sync $ listStoreAppend store newRow return () flip callStream delPressed $ \_ -> do (segs, store) <- sample currentModel (cur, _) <- sync $ treeViewGetCursor editor sync $ case cur of [i] -> listStoreRemove store i _ -> return () return (vb, currentft) displayFeatureMatrix :: FeatureTable String -> IO Grid displayFeatureMatrix ft = do g <- gridNew set g [widgetName := Just "featuretable"] set g [ containerBorderWidth : = 5 ] 2 forM_ (assocs (segNames ft)) $ \(Seg n,s) -> do l <- labelNew (Just s) let oddclass = if odd n then ["oddcol"] else [] widgetAddClasses (["segheader"] ++ oddclass) l gridAttach g l n 0 1 1 forM_ (assocs (featNames ft)) $ \(n,f) -> do l <- labelNew (Just f) widgetAddClasses ["featheader"] l set l [miscXalign := 0] gridAttach g l 0 n 1 1 forM_ (assocs (featTable ft)) $ \((Seg s, f), fs) -> do l <- case fs of FPlus -> labelNew (Just "+") FMinus -> labelNew (Just "−") FOff -> do l <- labelNew (Just "0") widgetAddClasses ["featzero"] l return l let oddclass = if odd s then ["oddcol"] else [] widgetAddClasses oddclass l gridAttach g l s f 1 1 return g displayDynFeatureTable :: Behavior (FeatureTable String) -> Now ScrolledWindow displayDynFeatureTable dynft = do initft <- sample dynft scr <- sync $ scrolledWindowNew Nothing Nothing done <- getUnrealize scr let ftchanged = toChanges dynft `beforeEs` done initwidget <- sync $ displayFeatureMatrix initft sync $ scrolledWindowAddWithViewport scr initwidget Just vp' <- sync $ binGetChild scr let vp = castToViewport vp' flip callIOStream ftchanged $ \newft -> do Just oldw <- binGetChild vp widgetDestroy oldw newwidget <- displayFeatureMatrix newft containerAdd vp newwidget widgetShowAll newwidget return scr
null
https://raw.githubusercontent.com/george-steel/maxent-learner/dfa29387338418e55f681886a7b3e5ca46bba459/maxent-learner-hw-gui/app/FeatureTableEditor.hs
haskell
sync $ fileChooserAddFilter saveDialog allfilter
# LANGUAGE LambdaCase , OverloadedStrings , ExtendedDefaultRules # module FeatureTableEditor ( createEditableFT, displayFeatureMatrix, displayDynFeatureTable ) where import Graphics.UI.Gtk import Control.FRPNow hiding (swap) import Control.FRPNow.GTK import Control.FRPNow.GTK.MissingFFI import Control.Monad import Control.Exception import Data.Tuple import Data.List import Data.Maybe import Text.PhonotacticLearner.PhonotacticConstraints import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Array.IArray import qualified Data.Map.Lazy as M import qualified Data.ByteString as B import Control.DeepSeq default (T.Text) data FTRow = FTRow T.Text (M.Map SegRef FeatureState) deriving (Eq, Show) fsTrue FPlus = True fsTrue FMinus = False fsTrue FOff = False fsInc FPlus = False fsInc FMinus = True fsInc FOff = False fsCycle FPlus = FMinus fsCycle FMinus = FOff fsCycle FOff = FPlus ft2rows ft = ffor (assocs . featNames $ ft) $ \(fi,fn) -> let sbounds = bounds (segNames ft) sidxs = indices (segNames ft) fsmap = M.fromList [(i,ftlook ft i fi) | i <- sidxs] in FTRow fn fsmap rows2ft :: Array SegRef String -> [FTRow] -> FeatureTable String rows2ft segs rows = FeatureTable ftarr fnames segs flook slook where nf = length rows (sa,sb) = bounds segs nrows = zip [1..] rows fnames = array (1,nf) [(n,fn) | (n,FTRow fn _) <- nrows] ftarr = array ((sa,1),(sb,nf)) $ do (fi, FTRow _ fsmap) <- nrows (si,fs) <- M.assocs fsmap return ((si,fi),fs) slook = M.fromList (fmap swap (assocs segs)) flook = M.fromList (fmap swap (assocs fnames)) resegft :: [String] -> FeatureTable String -> FeatureTable String resegft segs oldft = FeatureTable ftarr fnames segsarr flook slook where fnames = featNames oldft flook = featLookup oldft (fa,fb) = bounds fnames uniqsegs = nub segs nsegs = length uniqsegs segsarr = listArray (Seg 1, Seg nsegs) uniqsegs slook = M.fromList (fmap swap (assocs segsarr)) ftarr = array ((Seg 1,fa), (Seg nsegs,fb)) $ do f <- indices fnames (sr,s) <- assocs segsarr let fs = fromMaybe FOff $ do sr' <- M.lookup s (segLookup oldft) return $ ftlook oldft sr' f return ((sr,f),fs) setFTContents :: TreeView -> FeatureTable String -> IO (Array SegRef String, ListStore FTRow) setFTContents editor newft = do let segs = segNames newft rows = ft2rows newft model <- listStoreNew rows oldcols <- treeViewGetColumns editor forM_ oldcols $ \col -> treeViewRemoveColumn editor col treeViewSetModel editor model lcol <- treeViewColumnNew set lcol [treeViewColumnTitle := "Feature"] lcell <- cellRendererTextNew set lcell [cellTextEditable := True] cellLayoutPackStart lcol lcell True treeViewAppendColumn editor lcol cellLayoutSetAttributes lcol lcell model $ \(FTRow fn _) -> [cellText := fn] on lcell edited $ \[i] newtext -> do FTRow _ fsmap <- listStoreGetValue model i listStoreSetValue model i (FTRow newtext fsmap) forM_ (assocs segs) $ \(si,sn) -> do col <- treeViewColumnNew set col [treeViewColumnTitle := sn] cell <- cellRendererToggleNew cellLayoutPackStart col cell True treeViewAppendColumn editor col cellLayoutSetAttributes col cell model $ \(FTRow _ fsmap) -> [cellToggleActive := fsTrue (fsmap M.! si), cellToggleInconsistent := fsInc (fsmap M.! si)] on cell cellToggled $ \tpStr -> do let [i] = stringToTreePath tpStr FTRow fn fsmap <- listStoreGetValue model i let newrow = FTRow fn (M.adjust fsCycle si fsmap) listStoreSetValue model i newrow pcol <- treeViewColumnNew treeViewAppendColumn editor pcol return (segs, model) watchFtModel :: (Array SegRef String, ListStore FTRow) -> Now (Behavior (FeatureTable String)) watchFtModel (segs, model) = do (rowsChanged, rowcb) <- callbackStream let changecb = listStoreToList model >>= rowcb sync $ do on model rowChanged $ \_ _ -> changecb on model rowInserted $ \_ _ -> changecb on model rowDeleted $ \_ -> changecb initrows <- sync $ listStoreToList model dynrows <- sample $ fromChanges initrows rowsChanged return $ fmap (rows2ft segs) dynrows loadFTfromFile :: FilePath -> IO (Maybe (FeatureTable String)) loadFTfromFile fp = fmap join . checkIOError $ do bincsv <- B.readFile fp evaluate $ force . csvToFeatureTable id . T.unpack =<< either (const Nothing) Just (T.decodeUtf8' bincsv) runTextDialog :: Maybe Window -> T.Text -> T.Text -> Now (Event (Maybe T.Text)) runTextDialog transwin q defa = do (retev, cb) <- callback dia <- sync $ dialogNew ent <- sync $ entryNew sync $ do case transwin of Just win -> set dia [windowTransientFor := win, windowModal := True] Nothing -> return () dialogAddButton dia "gtk-ok" ResponseOk dialogAddButton dia "gtk-cancel" ResponseCancel ca <- castToBox <$> dialogGetContentArea dia entrySetText ent defa lbl <- createLabel q boxPackStart ca lbl PackGrow 0 boxPackStart ca ent PackNatural 0 on dia response $ \resp -> do case resp of ResponseOk -> do txt <- entryGetText ent cb (Just txt) _ -> cb Nothing widgetDestroy dia widgetShowAll dia return retev createEditableFT :: Maybe Window -> FeatureTable String -> Now (VBox, Behavior (FeatureTable String)) createEditableFT transwin initft = do editor <- sync treeViewNew editor' <- createScrolledWindow editor sync $ set editor' [scrolledWindowOverlay := False] (loadButton, loadPressed) <- createButton (Just "document-open") (Just "Load Table") (saveButton, savePressed) <- createButton (Just "document-save") (Just "Save Table") (addButton, addPressed) <- createButton (Just "list-add") Nothing (delButton, delPressed) <- createButton (Just "list-remove") Nothing (editButton, isEditing) <- createToggleButton (Just "accessories-text-editor") (Just "Edit Table") False (segButton, segPressed) <- createButton Nothing (Just "Change Segments") setAttr widgetSensitive addButton isEditing setAttr widgetSensitive delButton isEditing (ftReplaced, replaceft) <- callbackStream (modelReplaced, replaceModel) <- callbackStream initmodel <- sync $ setFTContents editor initft currentModel <- sample $ fromChanges initmodel modelReplaced initdft <- watchFtModel initmodel callStream (sync . replaceft <=< watchFtModel . last) modelReplaced currentft <- sample$ foldrSwitch initdft ftReplaced viewer <- displayDynFeatureTable currentft top <- sync stackNew sync $ do stackAddNamed top viewer "False" stackAddNamed top editor' "True" setAttr stackVisibleChildName top (fmap show isEditing) vb <- createVBox 2 $ do bstretch =<< createFrame ShadowIn top bpack <=< createHBox 2 $ do bpack addButton bpack delButton bspacer bpack segButton bpack editButton bpack loadButton bpack saveButton csvfilter < - sync fileFilterNew allfilter < - sync fileFilterNew sync $ do " text / csv " " CSV " fileFilterAddPattern allfilter " * " fileFilterSetName allfilter " All Files " allfilter <- sync fileFilterNew sync $ do fileFilterAddMimeType csvfilter "text/csv" fileFilterSetName csvfilter "CSV" fileFilterAddPattern allfilter "*" fileFilterSetName allfilter "All Files" -} loadDialog <- sync $ fileChooserDialogNew (Just "Open Feature Table") transwin FileChooserActionOpen [("gtk-cancel", ResponseCancel), ("gtk-open", ResponseAccept)] sync $ fileChooserAddFilter loadDialog csvfilter sync $ fileChooserAddFilter loadDialog allfilter sync $ set loadDialog [windowModal := True] flip callStream loadPressed $ \_ -> do filePicked <- runFileChooserDialog loadDialog emft <- planNow . ffor filePicked $ \case Nothing -> return never Just fn -> async $ loadFTfromFile fn planNow . ffor (join emft) $ \case Nothing -> sync $ putStrLn "Invalid CSV table." Just newft -> sync $ do newmodel <- setFTContents editor newft replaceModel newmodel putStrLn "Feature table sucessfully loaded." return () saveDialog <- sync $ fileChooserDialogNew (Just "Save Feature Table") transwin FileChooserActionSave [("gtk-cancel", ResponseCancel), ("gtk-save", ResponseAccept)] sync $ fileChooserAddFilter saveDialog csvfilter sync $ set saveDialog [windowModal := True] flip callStream savePressed $ \_ -> do savePicked <- runFileChooserDialog saveDialog planNow . ffor savePicked $ \case Nothing -> return () Just fn -> do ft <- sample currentft async $ do let csv = featureTableToCsv id ft bincsv = T.encodeUtf8 (T.pack csv) B.writeFile fn bincsv putStrLn $ "Wrote Feature Table " ++ fn return () return () flip callStream segPressed $ \_ -> do oldft <- sample currentft let oldsegs = T.pack . unwords . elems . segNames $ oldft enewsegs <- runTextDialog transwin "Enter a new set of segments." oldsegs planNow . ffor enewsegs $ \case Nothing -> return () Just newsegs -> let segs = words (T.unpack newsegs) in case segs of [] -> return () _ -> sync $ do let newft = resegft segs oldft newmodel <- setFTContents editor newft replaceModel newmodel putStrLn "Segments Changed." return () flip callStream addPressed $ \_ -> do (segs, store) <- sample currentModel let newRow = FTRow "" (M.fromList [(s,FOff) | s <- indices segs]) sync $ listStoreAppend store newRow return () flip callStream delPressed $ \_ -> do (segs, store) <- sample currentModel (cur, _) <- sync $ treeViewGetCursor editor sync $ case cur of [i] -> listStoreRemove store i _ -> return () return (vb, currentft) displayFeatureMatrix :: FeatureTable String -> IO Grid displayFeatureMatrix ft = do g <- gridNew set g [widgetName := Just "featuretable"] set g [ containerBorderWidth : = 5 ] 2 forM_ (assocs (segNames ft)) $ \(Seg n,s) -> do l <- labelNew (Just s) let oddclass = if odd n then ["oddcol"] else [] widgetAddClasses (["segheader"] ++ oddclass) l gridAttach g l n 0 1 1 forM_ (assocs (featNames ft)) $ \(n,f) -> do l <- labelNew (Just f) widgetAddClasses ["featheader"] l set l [miscXalign := 0] gridAttach g l 0 n 1 1 forM_ (assocs (featTable ft)) $ \((Seg s, f), fs) -> do l <- case fs of FPlus -> labelNew (Just "+") FMinus -> labelNew (Just "−") FOff -> do l <- labelNew (Just "0") widgetAddClasses ["featzero"] l return l let oddclass = if odd s then ["oddcol"] else [] widgetAddClasses oddclass l gridAttach g l s f 1 1 return g displayDynFeatureTable :: Behavior (FeatureTable String) -> Now ScrolledWindow displayDynFeatureTable dynft = do initft <- sample dynft scr <- sync $ scrolledWindowNew Nothing Nothing done <- getUnrealize scr let ftchanged = toChanges dynft `beforeEs` done initwidget <- sync $ displayFeatureMatrix initft sync $ scrolledWindowAddWithViewport scr initwidget Just vp' <- sync $ binGetChild scr let vp = castToViewport vp' flip callIOStream ftchanged $ \newft -> do Just oldw <- binGetChild vp widgetDestroy oldw newwidget <- displayFeatureMatrix newft containerAdd vp newwidget widgetShowAll newwidget return scr
6c3558f969715a18329e5b3a10e2a9d356860f9d07b87571bdaad9c84036c491
LambdaScientist/CLaSH-by-example
TestSimpleDFlopWithReset.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # module ClocksAndRegisters.TestSimpleDFlopWithReset where import CLaSH.Prelude import SAFE.TestingTools import SAFE.CommonClash import ClocksAndRegisters.Models.SimpleDFlopWithReset import Text.PrettyPrint.HughesPJClass import GHC.Generics (Generic) import Control.DeepSeq configurationList :: [Config] configurationList = [configOne, configTwo, configThree, configFour] where startSt = St 0 inputOne = PIn 1 0 True configOne = Config inputOne startSt inputTwo = PIn 1 1 False configTwo = Config inputTwo startSt inputThree = PIn 0 0 False configThree = Config inputThree startSt inputFour = PIn 0 1 False configFour = Config inputFour startSt ---TESTING data Config = Config { input :: PIn , startSt :: St } instance Pretty Config where pPrint Config{..} = text "Config:" $+$ text "input =" <+> pPrint input $+$ text "startSt =" <+> pPrint startSt instance Transition Config where runOneTest = runOneTest' instance NFData Config where rnf a = seq a () setupTest :: Config -> Signal St setupTest (Config pin st) = topEntity' st sPin where sPin = signal pin setupAndRun :: [[TestResult]] setupAndRun = runConfigList setupTest configurationList ppSetupAndRun :: Doc ppSetupAndRun = pPrint setupAndRun
null
https://raw.githubusercontent.com/LambdaScientist/CLaSH-by-example/e783cd2f2408e67baf7f36c10398c27036a78ef3/ConvertedClashExamples/src/ClocksAndRegisters/TestSimpleDFlopWithReset.hs
haskell
-TESTING
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # module ClocksAndRegisters.TestSimpleDFlopWithReset where import CLaSH.Prelude import SAFE.TestingTools import SAFE.CommonClash import ClocksAndRegisters.Models.SimpleDFlopWithReset import Text.PrettyPrint.HughesPJClass import GHC.Generics (Generic) import Control.DeepSeq configurationList :: [Config] configurationList = [configOne, configTwo, configThree, configFour] where startSt = St 0 inputOne = PIn 1 0 True configOne = Config inputOne startSt inputTwo = PIn 1 1 False configTwo = Config inputTwo startSt inputThree = PIn 0 0 False configThree = Config inputThree startSt inputFour = PIn 0 1 False configFour = Config inputFour startSt data Config = Config { input :: PIn , startSt :: St } instance Pretty Config where pPrint Config{..} = text "Config:" $+$ text "input =" <+> pPrint input $+$ text "startSt =" <+> pPrint startSt instance Transition Config where runOneTest = runOneTest' instance NFData Config where rnf a = seq a () setupTest :: Config -> Signal St setupTest (Config pin st) = topEntity' st sPin where sPin = signal pin setupAndRun :: [[TestResult]] setupAndRun = runConfigList setupTest configurationList ppSetupAndRun :: Doc ppSetupAndRun = pPrint setupAndRun
d8fedb3be94593fc4615b2b77a8ff4baa43700c2c06d7a5a945c67da43512a91
oden-lang/oden
Lint.hs
module Oden.CLI.Lint where import Oden.QualifiedName import Oden.SourceFile import Oden.CLI import Oden.CLI.Build lint :: FilePath -> CLI () lint path = do _ <- compileFile (OdenSourceFile path (NativePackageName ["main"])) return ()
null
https://raw.githubusercontent.com/oden-lang/oden/10c99b59c8b77c4db51ade9a4d8f9573db7f4d14/cli/Oden/CLI/Lint.hs
haskell
module Oden.CLI.Lint where import Oden.QualifiedName import Oden.SourceFile import Oden.CLI import Oden.CLI.Build lint :: FilePath -> CLI () lint path = do _ <- compileFile (OdenSourceFile path (NativePackageName ["main"])) return ()
b53a45d826e455ce7e0d50ea5e44a064a593d7fc9be63977d42ed38397315399
juspay/atlas
PaymentTransaction.hs
# OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd 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 : Domain . PaymentTransaction Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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 : Domain.PaymentTransaction Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.PaymentTransaction where import Beckn.Prelude import Beckn.Types.Amount import Beckn.Types.Id import Domain.Booking.Type data PaymentStatus = PENDING | FAILED | SUCCESS deriving (Generic, Show, Read, FromJSON, ToJSON, ToSchema) data PaymentTransaction = PaymentTransaction { id :: Id PaymentTransaction, bookingId :: Id Booking, paymentGatewayTxnId :: Text, paymentGatewayTxnStatus :: Text, fare :: Amount, status :: PaymentStatus, paymentUrl :: BaseUrl, updatedAt :: UTCTime, createdAt :: UTCTime } deriving (Generic, Show, ToSchema) data PaymentTransactionAPIEntity = PaymentTransactionAPIEntity { id :: Id PaymentTransaction, paymentGatewayTxnId :: Text, fare :: Amount, status :: PaymentStatus, paymentUrl :: BaseUrl, updatedAt :: UTCTime, createdAt :: UTCTime } deriving (Generic, ToJSON, ToSchema) makePaymentTransactionAPIEntity :: PaymentTransaction -> PaymentTransactionAPIEntity makePaymentTransactionAPIEntity PaymentTransaction {..} = PaymentTransactionAPIEntity {..}
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/parking-bap/src/Domain/PaymentTransaction.hs
haskell
# OPTIONS_GHC -Wno - orphans # | Copyright 2022 Juspay Technologies Pvt Ltd 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 : Domain . PaymentTransaction Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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 : Domain.PaymentTransaction Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.PaymentTransaction where import Beckn.Prelude import Beckn.Types.Amount import Beckn.Types.Id import Domain.Booking.Type data PaymentStatus = PENDING | FAILED | SUCCESS deriving (Generic, Show, Read, FromJSON, ToJSON, ToSchema) data PaymentTransaction = PaymentTransaction { id :: Id PaymentTransaction, bookingId :: Id Booking, paymentGatewayTxnId :: Text, paymentGatewayTxnStatus :: Text, fare :: Amount, status :: PaymentStatus, paymentUrl :: BaseUrl, updatedAt :: UTCTime, createdAt :: UTCTime } deriving (Generic, Show, ToSchema) data PaymentTransactionAPIEntity = PaymentTransactionAPIEntity { id :: Id PaymentTransaction, paymentGatewayTxnId :: Text, fare :: Amount, status :: PaymentStatus, paymentUrl :: BaseUrl, updatedAt :: UTCTime, createdAt :: UTCTime } deriving (Generic, ToJSON, ToSchema) makePaymentTransactionAPIEntity :: PaymentTransaction -> PaymentTransactionAPIEntity makePaymentTransactionAPIEntity PaymentTransaction {..} = PaymentTransactionAPIEntity {..}
fe7cbc1f3ea4f1e05e5a71f45903813766e667483663e8a995a0bf903de08ee5
sky-big/RabbitMQ
rabbit_mgmt_wm_extensions.erl
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in %% compliance with the License. You may obtain a copy of the License at %% / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the %% License for the specific language governing rights and limitations %% under the License. %% The Original Code is RabbitMQ Management Plugin . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2011 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_mgmt_wm_extensions). -export([init/1, to_json/2, content_types_provided/2, is_authorized/2]). -include("rabbit_mgmt.hrl"). -include("webmachine.hrl"). -include("rabbit.hrl"). %%-------------------------------------------------------------------- init(_Config) -> {ok, #context{}}. content_types_provided(ReqData, Context) -> {[{"application/json", to_json}], ReqData, Context}. to_json(ReqData, Context) -> Modules = rabbit_mgmt_dispatcher:modules([]), rabbit_mgmt_util:reply( [Module:web_ui() || Module <- Modules], ReqData, Context). is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized(ReqData, Context).
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-management/src/rabbit_mgmt_wm_extensions.erl
erlang
compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. --------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ Management Plugin . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2011 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_mgmt_wm_extensions). -export([init/1, to_json/2, content_types_provided/2, is_authorized/2]). -include("rabbit_mgmt.hrl"). -include("webmachine.hrl"). -include("rabbit.hrl"). init(_Config) -> {ok, #context{}}. content_types_provided(ReqData, Context) -> {[{"application/json", to_json}], ReqData, Context}. to_json(ReqData, Context) -> Modules = rabbit_mgmt_dispatcher:modules([]), rabbit_mgmt_util:reply( [Module:web_ui() || Module <- Modules], ReqData, Context). is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized(ReqData, Context).
5cd391e39573f1b9658361c68d951413e25bcbedbf2b7c79ee3950ce308a879a
UU-ComputerScience/uhc
Error.hs
----------------------------------------------------------------------------- -- | Module : System . . Error Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : non-portable (requires POSIX) -- -- POSIX error support -- ----------------------------------------------------------------------------- module System.Posix.Error ( throwErrnoPath, throwErrnoPathIf, throwErrnoPathIf_, throwErrnoPathIfNull, throwErrnoPathIfMinus1, throwErrnoPathIfMinus1_, ) where import Foreign.C.Error
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/unix/System/Posix/Error.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : provisional Portability : non-portable (requires POSIX) POSIX error support ---------------------------------------------------------------------------
Module : System . . Error Copyright : ( c ) The University of Glasgow 2002 module System.Posix.Error ( throwErrnoPath, throwErrnoPathIf, throwErrnoPathIf_, throwErrnoPathIfNull, throwErrnoPathIfMinus1, throwErrnoPathIfMinus1_, ) where import Foreign.C.Error
a289db522190033d42e981cac44643f4b03867d5c2c1e4a8151bac47f592023f
input-output-hk/project-icarus-importer
CLI.hs
module CLI where import Universum import Data.String.Conv (toS) import Options.Applicative (auto, eitherReader, help, long, metavar, option, strOption, switch) import Options.Generic (ParseRecord (..)) import Pos.Util.Servant (decodeCType) import Pos.Wallet.Web.ClientTypes.Instances () import Pos.Wallet.Web.ClientTypes.Types (AccountId, CAccountId (..)) import Text.Read (readMaybe) import Types (Method (..)) data CLI = CLI { config :: FilePath -- ^ The path to the config file , nodePath :: FilePath -- ^ The path to a valid rocksdb database. , secretKeyPath :: FilePath -- ^ The path to the secret key from the database. , walletPath :: FilePath -- ^ The path to a valid acid-state database. , configurationPath :: FilePath -- ^ The path to a valid cardano-sl configuration. , configurationProf :: String -- ^ The configuration profile to use. , systemStart :: Maybe Int -- ^ The systemStart for the application , showStats :: Bool -- ^ If true, print the stats for the `wallet-db` , queryMethod :: Maybe Method -- ^ If a method is defined, try to call it. For example, calling ` ` could be useful . , addTo :: Maybe AccountId -- ^ If specified, only append addresses to the -- given <wallet_id@account_id> } instance ParseRecord CLI where parseRecord = CLI <$> (strOption (long "config" <> metavar "CONFIG.DHALL" <> help "A path to a config file." )) <*> (strOption (long "nodeDB" <> metavar "rocksdb-path" <> help "A path to a valid rocksdb database." )) <*> (strOption (long "secretKey" <> metavar "secret-key-path" <> help "A path to a valid secreate key for the database." )) <*> (strOption (long "walletDB" <> metavar "acidstate-path" <> help "A path to a valid acidstate database." )) <*> (strOption (long "configPath" <> metavar "configuration-path" <> help "A path to a valid cardano-sl configuration." )) <*> (strOption (long "configProf" <> metavar "configuration-profile" <> help "A valid cardano-sl configuration profile to use." )) <*> optional (option auto (long "systemStart" <> help "A valid node system start to use.")) <*> switch (long "stats" <> help "Show stats for this wallet.") <*> ((readMaybe =<<) <$> (optional (strOption (long "query" <> help "Query a predefined endpoint.")))) <*> (optional (option (eitherReader readAccountId) (long "add-to" <> metavar "walletId@accountId" <> help "Append to an existing wallet & account." ))) readAccountId :: String -> Either String AccountId readAccountId str' = case decodeCType (CAccountId (toS str')) of Left e -> Left (toS e) Right x -> Right x
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/tools/src/dbgen/CLI.hs
haskell
^ The path to the config file ^ The path to a valid rocksdb database. ^ The path to the secret key from the database. ^ The path to a valid acid-state database. ^ The path to a valid cardano-sl configuration. ^ The configuration profile to use. ^ The systemStart for the application ^ If true, print the stats for the `wallet-db` ^ If a method is defined, try to call it. For example, ^ If specified, only append addresses to the given <wallet_id@account_id>
module CLI where import Universum import Data.String.Conv (toS) import Options.Applicative (auto, eitherReader, help, long, metavar, option, strOption, switch) import Options.Generic (ParseRecord (..)) import Pos.Util.Servant (decodeCType) import Pos.Wallet.Web.ClientTypes.Instances () import Pos.Wallet.Web.ClientTypes.Types (AccountId, CAccountId (..)) import Text.Read (readMaybe) import Types (Method (..)) data CLI = CLI { config :: FilePath , nodePath :: FilePath , secretKeyPath :: FilePath , walletPath :: FilePath , configurationPath :: FilePath , configurationProf :: String , systemStart :: Maybe Int , showStats :: Bool , queryMethod :: Maybe Method calling ` ` could be useful . , addTo :: Maybe AccountId } instance ParseRecord CLI where parseRecord = CLI <$> (strOption (long "config" <> metavar "CONFIG.DHALL" <> help "A path to a config file." )) <*> (strOption (long "nodeDB" <> metavar "rocksdb-path" <> help "A path to a valid rocksdb database." )) <*> (strOption (long "secretKey" <> metavar "secret-key-path" <> help "A path to a valid secreate key for the database." )) <*> (strOption (long "walletDB" <> metavar "acidstate-path" <> help "A path to a valid acidstate database." )) <*> (strOption (long "configPath" <> metavar "configuration-path" <> help "A path to a valid cardano-sl configuration." )) <*> (strOption (long "configProf" <> metavar "configuration-profile" <> help "A valid cardano-sl configuration profile to use." )) <*> optional (option auto (long "systemStart" <> help "A valid node system start to use.")) <*> switch (long "stats" <> help "Show stats for this wallet.") <*> ((readMaybe =<<) <$> (optional (strOption (long "query" <> help "Query a predefined endpoint.")))) <*> (optional (option (eitherReader readAccountId) (long "add-to" <> metavar "walletId@accountId" <> help "Append to an existing wallet & account." ))) readAccountId :: String -> Either String AccountId readAccountId str' = case decodeCType (CAccountId (toS str')) of Left e -> Left (toS e) Right x -> Right x
4d4ec6128ee620bb1bcaf963d7f53597662472a7665bf6e7d0b22783dbf8092f
Feuerlabs/netlink
netlink.erl
%%%---- BEGIN COPYRIGHT ------------------------------------------------------- %%% Copyright ( C ) 2012 Feuerlabs , Inc. All rights reserved . %%% This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%%---- END COPYRIGHT --------------------------------------------------------- %%%------------------------------------------------------------------- @author < > %%% @doc Netlink state monitor %%% @end Created : 11 Jun 2012 by < > %%%------------------------------------------------------------------- -module(netlink). -behaviour(gen_server). %% API -export([start_link/0, start_link/1]). -export([start/0, stop/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([i/0, list/1]). -export([subscribe/1, subscribe/2, subscribe/3]). -export([unsubscribe/1]). -export([invalidate/2]). -export([get_root/2, get_match/3, get/4]). -include_lib("hut/include/hut.hrl"). -include("netlink.hrl"). -include("netl_codec.hrl"). -define(SERVER, ?MODULE). -type if_addr_field() :: address | local | broadcast | anycast | multicast. -type if_link_field() :: name | index | mtu | txqlen | flags | operstate | qdisc | address | broadcast. -type uint8_t() :: 0..16#ff. -type uint16_t() :: 0..16#ffff. -type ipv4_addr() :: {uint8_t(),uint8_t(),uint8_t(),uint8_t()}. -type ipv6_addr() :: {uint16_t(),uint16_t(),uint16_t(),uint16_t(), uint16_t(),uint16_t(),uint16_t(),uint16_t()}. -type if_addr() :: ipv4_addr() | ipv6_addr(). -type if_field() :: if_link_field() | if_addr_field() | {link,if_link_field()} | {addr,if_addr_field()}. -type if_name() :: string(). -record(link, { name :: if_name(), %% interface name index :: non_neg_integer(), %% interface index attr :: term() %% attributes {atom(),term} }). -record(addr, { addr :: if_addr(), %% the address name :: if_name(), %% interface label index :: non_neg_integer(), %% interface index attr :: term() %% attributes }). -record(subscription, { pid :: pid(), %% subscriber mon :: reference(), %% monitor name :: string(), %% name fields=all :: all | addr | link | [if_field()] }). -define(MIN_RCVBUF, (128*1024)). -define(MIN_SNDBUF, (32*1024)). -define(REQUEST_TMO, 2000). -record(request, { tmr, %% timer reference call, %% call request from, %% caller reply=ok, %% reply to send when done seq=0 %% sequence to expect in reply }). -record(state, { port, link_list = [] :: [#link {}], addr_list = [] :: [#addr {}], sub_list = [] :: [#subscription {}], request :: undefined | #request{}, request_queue = [] :: [#request{}], o_seq = 0, i_seq = 0, ospid }). %%%=================================================================== %%% API %%%=================================================================== start() -> application:start(netlink). i() -> gen_server:call(?SERVER, {list,[]}). stop() -> gen_server:call(?SERVER, stop). list(Match) -> gen_server:call(?SERVER, {list,Match}). %% @doc %% Subscribe to interface changes, notifications will be sent in { netlink , reference(),if_name(),if_field(),OldValue , NewValue } %% @end -spec subscribe(Name::string()) -> {ok,reference()}. subscribe(Name) -> subscribe(Name,all,[]). -spec subscribe(Name::string(),Fields::all|[if_field()]) -> {ok,reference()}. subscribe(Name,Fields) -> subscribe(Name,Fields, []). -spec subscribe(Name::string(),Fields::all|[if_field()],Otions::[atom()]) -> {ok,reference()}. subscribe(Name,Fields,Options) -> gen_server:call(?SERVER, {subscribe, self(),Name,Options,Fields}). unsubscribe(Ref) -> gen_server:call(?SERVER, {unsubscribe,Ref}). %% clear all attributes for interface Name invalidate(Name,Fields) -> gen_server:call(?SERVER, {invalidate,Name,Fields}). get_root(What,Fam) -> get(What,Fam,[root,match,request],[]). get_match(What,Fam,GetAttrs) -> get(What,Fam,[match,request],GetAttrs). get(What,Fam,GetFlags,GetAttrs) -> gen_server:call(?SERVER, {get,What,Fam,GetFlags,GetAttrs}). %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> start_link([]). start_link(Opts) -> gen_server:start_link({local, ?SERVER}, ?MODULE, [Opts], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([Opts]) -> OsPid = list_to_integer(os:getpid()), I_Seq = O_Seq = 1234, %% element(2,now()), State = #state{ ospid = OsPid, o_seq = O_Seq, i_seq = I_Seq }, case os:type() of {unix, linux} -> init_drv(Opts, State); _ -> {ok, State} end. init_drv(Opts, State) -> Port = netlink_drv:open(?NETLINK_ROUTE), netlink_drv:debug(Port, proplists:get_value(debug,Opts,none)), {ok,Rcvbuf} = update_rcvbuf(Port, ?MIN_RCVBUF), {ok,Sndbuf} = update_sndbuf(Port, ?MIN_SNDBUF), ?log(info, "Rcvbuf: ~w, Sndbuf: ~w", [Rcvbuf, Sndbuf]), {ok,Sizes} = netlink_drv:get_sizeof(Port), ?log(info, "Sizes: ~w", [Sizes]), ok = netlink_drv:add_membership(Port, ?RTNLGRP_LINK), ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV4_IFADDR), ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV6_IFADDR), netlink_drv:activate(Port), %% init sequence to fill the cache T0 = erlang:start_timer(200, self(), request_timeout), R0 = #request { tmr = T0, call = noop, from = {self(),make_ref()} }, R1 = #request { tmr = {relative, ?REQUEST_TMO}, call = {get,link,unspec, [root,match,request], []}, from = {self(),make_ref()} }, R2 = #request { tmr = {relative, 1000}, call = noop, from = {self(),make_ref()} }, R3 = #request { tmr = {relative,?REQUEST_TMO}, call = {get,addr,unspec, [root,match,request], []}, from = {self(),make_ref()} }, {ok, State#state{ port=Port, request = R0, request_queue = [R1,R2,R3] }}. %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call({list,Match}, _From, State) -> lists:foreach( fun(L) -> %% select addresses that belong to link L Ys = [Y || Y <- State#state.addr_list, Y#addr.index =:= L#link.index], FYs = [format_addr(Y) || Y <- Ys ], case match(L#link.attr,dict:new(),Match) of true -> io:format("link {~s~s}\n", [FYs,format_link(L)]); false -> ok end end, State#state.link_list), {reply, ok, State}; handle_call({subscribe, Pid, Name, Options, Fs}, _From, State) -> Mon = erlang:monitor(process, Pid), S = #subscription { pid=Pid, mon=Mon, name=Name, fields=Fs }, SList = [S | State#state.sub_list], case proplists:get_bool(flush, Options) of false -> {reply, {ok,Mon}, State#state { sub_list = SList }}; true -> lists:foreach( fun(L) -> As = dict:to_list(L#link.attr), update_attrs(L#link.name, link, As, dict:new(), [S]) end, State#state.link_list), lists:foreach( fun(Y) -> As = dict:to_list(Y#addr.attr), update_attrs(Y#addr.name, addr, As, dict:new(), [S]) end, State#state.addr_list), {reply, {ok,Mon}, State#state { sub_list = SList }} end; handle_call({unsubscribe,Ref}, _From, State) -> case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of false -> {reply,ok,State}; {value,_S,SubList} -> erlang:demonitor(Ref), {reply,ok,State#state { sub_list=SubList }} end; handle_call({invalidate,Name,Fields},_From,State) -> case lists:keytake(Name, #link.name, State#state.link_list) of false -> {reply, {error,enoent}, State}; {value,L,Ls} -> Attr = lists:foldl( fun(F,D) when is_atom(F) -> dict:erase(F, D) end, L#link.attr, Fields), L1 = L#link { attr = Attr }, {reply, ok, State#state { link_list = [L1|Ls] } } end; handle_call(Req={get,_What,_Fam,_Flags,_Attrs}, From, State) -> ?log(debug, "handle_call: GET: ~p", [Req]), State1 = enq_request(Req, From, State), State2 = dispatch_command(State1), {noreply, State2}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(_Info={nl_data,Port,Data},State) when Port =:= State#state.port -> try netlink_codec:decode(Data,[]) of MsgList -> FIXME : the messages should be delivered one by one from %% the driver so the decoding could simplified. State1 = lists:foldl( fun(Msg,StateI) -> ?log(debug, "handle_info: msg=~p", [Msg]), _Hdr = Msg#nlmsg.hdr, MsgData = Msg#nlmsg.data, handle_nlmsg(MsgData, StateI) end, State, MsgList), {noreply, State1} catch ?EXCEPTION(error, _Reason, Stacktrace) -> ?log(error, "netlink: handle_info: Crash: ~p", [?GET_STACK(Stacktrace)]), {noreply, State} end; handle_info({'DOWN',Ref,process,Pid,Reason}, State) -> case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of false -> {noreply,State}; {value,_S,SubList} -> ?log(debug, "subscription from pid ~p deleted reason=~p", [Pid, Reason]), {noreply,State#state { sub_list=SubList }} end; handle_info({timeout,Tmr,request_timeout}, State) -> R = State#state.request, if R#request.tmr =:= Tmr -> ?log(debug, "Timeout: ref current", []), gen_server:reply(R#request.from, {error,timeout}), State1 = State#state { request = undefined }, {noreply, dispatch_command(State1)}; true -> case lists:keytake(Tmr, #request.tmr, State#state.request_queue) of false -> ?log(debug, "Timeout: ref not found", []), {noreply, State}; {value,#request { from = From},Q} -> ?log(debug, "Timeout: ref in queue", []), gen_server:reply(From, {error,timeout}), State1 = State#state { request_queue = Q }, {noreply,dispatch_command(State1)} end end; handle_info({Tag, Reply}, State) when is_reference(Tag) -> ?log(debug, "INFO: SELF Reply=~p", [Reply]), {noreply, State}; handle_info(_Info, State) -> ?log(debug, "INFO: ~p", [_Info]), {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== enq_request(Call, From, State) -> Tmr = erlang:start_timer(?REQUEST_TMO, self(), request_timeout), R = #request { tmr = Tmr, call = Call, from = From }, Q = State#state.request_queue ++ [R], State#state { request_queue = Q }. dispatch_command(State) when State#state.request =:= undefined -> case State#state.request_queue of [R=#request { call = {get,What,Fam,Flags,Attrs} } | Q ] -> R1 = update_timer(R), State1 = State#state { request_queue = Q, request = R1 }, ?log(debug, "dispatch_command: ~p", [R1]), get_command(What,Fam,Flags,Attrs,State1); [R=#request { call = noop } | Q ] -> R1 = update_timer(R), State1 = State#state { request_queue = Q, request = R1 }, ?log(debug, "dispatch_command: ~p", [R1]), State1; %% let it timeout [] -> State end; dispatch_command(State) -> State. update_timer(R = #request { tmr = {relative,Tmo} }) when is_integer(Tmo), Tmo >= 0 -> Tmr = erlang:start_timer(Tmo, self(), request_timeout), R#request { tmr = Tmr }; update_timer(R = #request { tmr = Tmr }) when is_reference(Tmr) -> R. update_sndbuf(Port, Min) -> case netlink_drv:get_sndbuf(Port) of {ok,Size} when Size >= Min -> {ok,Size}; {ok,_Size} -> netlink_drv:set_sndbuf(Port, Min), netlink_drv:get_sndbuf(Port); Err -> Err end. update_rcvbuf(Port, Min) -> case netlink_drv:get_rcvbuf(Port) of {ok,Size} when Size >= Min -> {ok,Size}; {ok,_Size} -> netlink_drv:set_rcvbuf(Port, Min), netlink_drv:get_rcvbuf(Port); Err -> Err end. get_command(link,Fam,Flags,Attrs,State) -> Seq = State#state.o_seq, Get = #getlink{family=Fam,arphrd=ether,index=0, flags=[], change=[], attributes=Attrs}, Hdr = #nlmsghdr { type = getlink, flags = Flags, seq = Seq, pid = State#state.ospid }, Request = netlink_codec:encode(Hdr,Get), netlink_drv:send(State#state.port, Request), State#state { o_seq = (Seq+1) band 16#ffffffff }; get_command(addr,Fam,Flags,Attrs,State) -> Seq = State#state.o_seq, Get = #getaddr{family=Fam,prefixlen=0,flags=[],scope=0, index=0,attributes=Attrs}, Hdr = #nlmsghdr { type=getaddr, flags=Flags, seq=Seq, pid=State#state.ospid }, Request = netlink_codec:encode(Hdr,Get), netlink_drv:send(State#state.port, Request), State#state { o_seq = (Seq+1) band 16#ffffffff}. handle_nlmsg(RTM=#newlink{family=_Fam,index=Index,flags=Fs,change=Cs, attributes=As}, State) -> ?log(debug, "RTM = ~p", [RTM]), Name = proplists:get_value(ifname, As, ""), As1 = [{index,Index},{flags,Fs},{change,Cs}|As], case lists:keytake(Index, #link.index, State#state.link_list) of false -> Attr = update_attrs(Name, link, As1, dict:new(), State#state.sub_list), L = #link { index = Index, name = Name, attr = Attr }, Ls = [L|State#state.link_list], State#state { link_list = Ls }; {value,L,Ls} -> Attr = update_attrs(Name, link, As1, L#link.attr, State#state.sub_list), L1 = L#link { name = Name, attr = Attr }, State#state { link_list = [L1|Ls] } end; handle_nlmsg(RTM=#dellink{family=_Fam,index=Index,flags=_Fs,change=_Cs, attributes=As}, State) -> ?log(debug, "RTM = ~p\n", [RTM]), Name = proplists:get_value(ifname, As, ""), %% does this delete the link? case lists:keytake(Index, #link.index, State#state.link_list) of false -> ?log(warning, "Warning link index=~w not found", [Index]), State; {value,L,Ls} -> As1 = dict:to_list(L#link.attr), update_attrs(Name, link, As1, undefined, State#state.sub_list), State#state { link_list = Ls } end; handle_nlmsg(RTM=#newaddr { family=Fam, prefixlen=Prefixlen, flags=Flags, scope=Scope, index=Index, attributes=As }, State) -> ?log(debug, "RTM = ~p", [RTM]), Addr = proplists:get_value(address, As, {}), Name = proplists:get_value(label, As, ""), As1 = [{family,Fam},{prefixlen,Prefixlen},{flags,Flags}, {scope,Scope},{index,Index} | As], case lists:keymember(Index, #link.index, State#state.link_list) of false -> ?log(warning, "link index ~p does not exist", [Index]); true -> ok end, case lists:keytake(Addr, #addr.addr, State#state.addr_list) of false -> Attrs = update_attrs(Name,addr,As1,dict:new(),State#state.sub_list), Y = #addr { addr=Addr, name = Name, index=Index, attr=Attrs }, Ys = [Y|State#state.addr_list], State#state { addr_list = Ys }; {value,Y,Ys} -> Attr = update_attrs(Name,addr,As1,Y#addr.attr,State#state.sub_list), Y1 = Y#addr { index=Index, name=Name, attr = Attr }, State#state { addr_list = [Y1|Ys] } end; handle_nlmsg(RTM=#deladdr { family=_Fam, index=_Index, attributes=As }, State) -> ?log(debug, "RTM = ~p", [RTM]), Addr = proplists:get_value(address, As, {}), Name = proplists:get_value(label, As, ""), case lists:keytake(Addr, #addr.addr, State#state.addr_list) of false -> ?log(warning, "Warning addr=~w not found", [Addr]), State; {value,Y,Ys} -> As1 = dict:to_list(Y#addr.attr), update_attrs(Name, addr, As1, undefined, State#state.sub_list), State#state { addr_list = Ys } end; handle_nlmsg(#done { }, State) -> case State#state.request of undefined -> dispatch_command(State); #request { tmr = Tmr, from = From, reply = Reply } -> ?log(debug, "handle_nlmsg: DONE: ~p", [State#state.request]), erlang:cancel_timer(Tmr), gen_server:reply(From, Reply), State1 = State#state { request = undefined }, dispatch_command(State1) end; handle_nlmsg(Err=#error { errno=Err }, State) -> ?log(debug, "handle_nlmsg: ERROR: ~p", [State#state.request]), case State#state.request of undefined -> dispatch_command(State); #request { tmr = Tmr, from = From } -> ?log(debug, "handle_nlmsg: DONE: ~p", [State#state.request]), erlang:cancel_timer(Tmr), fixme : convert errno to posix error ( netlink.inc ? ) gen_server:reply(From, {error,Err}), State1 = State#state { request = undefined }, dispatch_command(State1) end; handle_nlmsg(RTM, State) -> ?log(debug, "netlink: handle_nlmsg, ignore ~p", [RTM]), State. %% update attributes form interface "Name" %% From to To Type is either link | addr update_attrs(Name,Type,As,undefined,Subs) -> lists:foreach( fun({K,Vold}) -> send_event(Name,Type,K,Vold,undefined,Subs) end, As), undefined; update_attrs(Name,Type,As,To,Subs) -> lists:foldl( fun({K,Vnew},D) -> case dict:find(K,D) of error -> send_event(Name,Type,K,undefined,Vnew,Subs), dict:store(K,Vnew,D); {ok,Vnew} -> D; %% already exist {ok,Vold} -> send_event(Name,Type,K,Vold,Vnew,Subs), dict:store(K,Vnew,D) end end, To, As). send_event(Name,Type,Field,Old,New,[S|SList]) when S#subscription.name =:= Name; S#subscription.name =:= "" -> case S#subscription.fields =:= all orelse S#subscription.fields =:= Type orelse lists:member(Field,S#subscription.fields) orelse lists:member({Type,Field},S#subscription.fields) of true -> S#subscription.pid ! {netlink,S#subscription.mon, Name,Field,Old,New}, send_event(Name,Type,Field,Old,New,SList); false -> send_event(Name,Type,Field,Old,New,SList) end; send_event(Name,Type,Field,Old,New,[_|SList]) -> send_event(Name,Type,Field,Old,New,SList); send_event(_Name,_Type,_Field,_Old,_New,[]) -> ok. match(Y,L,[{Field,Value}|Match]) when is_atom(Field) -> case find2(Field,Y,L) of {ok,Value} -> match(Y, L, Match); _ -> false end; match(Y,L,[{Op,Field,Value}|Match]) when is_atom(Op),is_atom(Field) -> case find2(Y,L,Field) of {ok,FValue} -> case compare(Op,FValue,Value) of true -> match(Y,L,Match); false -> false end; error -> false end; match(_Y, _L, []) -> true. find2(Key,D1,D2) -> case dict:find(Key,D1) of error -> dict:find(Key,D2); Res -> Res end. format_link(L) -> dict:fold( fun(af_spec,_V,A) -> A; (map,_V,A) -> A; (stats,_V,A) -> A; (stats64,_V,A) -> A; (change,_V,A) -> A; (K,V,A) -> [["\n ",name_to_list(K), " ",value_to_list(K,V),";"]|A] end, [], L#link.attr). format_addr(Y) -> ["\n", " addr {", dict:fold( fun(cacheinfo,_V,A) -> A; (K,V,A) -> [[" ",name_to_list(K), " ",value_to_list(K,V),";"]|A] end, [], Y#addr.attr), "}"]. name_to_list(K) when is_atom(K) -> atom_to_list(K); name_to_list(K) when is_integer(K) -> integer_to_list(K). value_to_list(local,V) -> format_a(V); value_to_list(address,V) -> format_a(V); value_to_list(broadcast,V) -> format_a(V); value_to_list(multicast,V) -> format_a(V); value_to_list(anycast,V) -> format_a(V); value_to_list(_, V) -> io_lib:format("~p", [V]). format_a(undefined) -> ""; format_a(A) when is_tuple(A), tuple_size(A) =:= 6 -> io_lib:format("~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b", tuple_to_list(A)); format_a(A) when is_tuple(A), tuple_size(A) =:= 4 -> inet_parse:ntoa(A); format_a(A) when is_tuple(A), tuple_size(A) =:= 8 -> inet_parse:ntoa(A). compare('==',A,B) -> A == B; compare('=:=',A,B) -> A =:= B; compare('<' ,A,B) -> A < B; compare('=<' ,A,B) -> A =< B; compare('>' ,A,B) -> A > B; compare('>=' ,A,B) -> A >= B; compare('/=' ,A,B) -> A /= B; compare('=/=' ,A,B) -> A =/= B; compare(_,_,_) -> false.
null
https://raw.githubusercontent.com/Feuerlabs/netlink/82579a8435472094494fe287df905cb07c1dee80/src/netlink.erl
erlang
---- BEGIN COPYRIGHT ------------------------------------------------------- ---- END COPYRIGHT --------------------------------------------------------- ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API gen_server callbacks interface name interface index attributes {atom(),term} the address interface label interface index attributes subscriber monitor name timer reference call request caller reply to send when done sequence to expect in reply =================================================================== API =================================================================== @doc Subscribe to interface changes, notifications will be @end clear all attributes for interface Name -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- element(2,now()), init sequence to fill the cache -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- select addresses that belong to link L -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- the driver so the decoding could simplified. -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== =================================================================== let it timeout does this delete the link? update attributes form interface "Name" From to To Type is either link | addr already exist
Copyright ( C ) 2012 Feuerlabs , Inc. All rights reserved . This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. @author < > Netlink state monitor Created : 11 Jun 2012 by < > -module(netlink). -behaviour(gen_server). -export([start_link/0, start_link/1]). -export([start/0, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([i/0, list/1]). -export([subscribe/1, subscribe/2, subscribe/3]). -export([unsubscribe/1]). -export([invalidate/2]). -export([get_root/2, get_match/3, get/4]). -include_lib("hut/include/hut.hrl"). -include("netlink.hrl"). -include("netl_codec.hrl"). -define(SERVER, ?MODULE). -type if_addr_field() :: address | local | broadcast | anycast | multicast. -type if_link_field() :: name | index | mtu | txqlen | flags | operstate | qdisc | address | broadcast. -type uint8_t() :: 0..16#ff. -type uint16_t() :: 0..16#ffff. -type ipv4_addr() :: {uint8_t(),uint8_t(),uint8_t(),uint8_t()}. -type ipv6_addr() :: {uint16_t(),uint16_t(),uint16_t(),uint16_t(), uint16_t(),uint16_t(),uint16_t(),uint16_t()}. -type if_addr() :: ipv4_addr() | ipv6_addr(). -type if_field() :: if_link_field() | if_addr_field() | {link,if_link_field()} | {addr,if_addr_field()}. -type if_name() :: string(). -record(link, { }). -record(addr, { }). -record(subscription, { fields=all :: all | addr | link | [if_field()] }). -define(MIN_RCVBUF, (128*1024)). -define(MIN_SNDBUF, (32*1024)). -define(REQUEST_TMO, 2000). -record(request, { }). -record(state, { port, link_list = [] :: [#link {}], addr_list = [] :: [#addr {}], sub_list = [] :: [#subscription {}], request :: undefined | #request{}, request_queue = [] :: [#request{}], o_seq = 0, i_seq = 0, ospid }). start() -> application:start(netlink). i() -> gen_server:call(?SERVER, {list,[]}). stop() -> gen_server:call(?SERVER, stop). list(Match) -> gen_server:call(?SERVER, {list,Match}). sent in { netlink , reference(),if_name(),if_field(),OldValue , NewValue } -spec subscribe(Name::string()) -> {ok,reference()}. subscribe(Name) -> subscribe(Name,all,[]). -spec subscribe(Name::string(),Fields::all|[if_field()]) -> {ok,reference()}. subscribe(Name,Fields) -> subscribe(Name,Fields, []). -spec subscribe(Name::string(),Fields::all|[if_field()],Otions::[atom()]) -> {ok,reference()}. subscribe(Name,Fields,Options) -> gen_server:call(?SERVER, {subscribe, self(),Name,Options,Fields}). unsubscribe(Ref) -> gen_server:call(?SERVER, {unsubscribe,Ref}). invalidate(Name,Fields) -> gen_server:call(?SERVER, {invalidate,Name,Fields}). get_root(What,Fam) -> get(What,Fam,[root,match,request],[]). get_match(What,Fam,GetAttrs) -> get(What,Fam,[match,request],GetAttrs). get(What,Fam,GetFlags,GetAttrs) -> gen_server:call(?SERVER, {get,What,Fam,GetFlags,GetAttrs}). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> start_link([]). start_link(Opts) -> gen_server:start_link({local, ?SERVER}, ?MODULE, [Opts], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([Opts]) -> OsPid = list_to_integer(os:getpid()), State = #state{ ospid = OsPid, o_seq = O_Seq, i_seq = I_Seq }, case os:type() of {unix, linux} -> init_drv(Opts, State); _ -> {ok, State} end. init_drv(Opts, State) -> Port = netlink_drv:open(?NETLINK_ROUTE), netlink_drv:debug(Port, proplists:get_value(debug,Opts,none)), {ok,Rcvbuf} = update_rcvbuf(Port, ?MIN_RCVBUF), {ok,Sndbuf} = update_sndbuf(Port, ?MIN_SNDBUF), ?log(info, "Rcvbuf: ~w, Sndbuf: ~w", [Rcvbuf, Sndbuf]), {ok,Sizes} = netlink_drv:get_sizeof(Port), ?log(info, "Sizes: ~w", [Sizes]), ok = netlink_drv:add_membership(Port, ?RTNLGRP_LINK), ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV4_IFADDR), ok = netlink_drv:add_membership(Port, ?RTNLGRP_IPV6_IFADDR), netlink_drv:activate(Port), T0 = erlang:start_timer(200, self(), request_timeout), R0 = #request { tmr = T0, call = noop, from = {self(),make_ref()} }, R1 = #request { tmr = {relative, ?REQUEST_TMO}, call = {get,link,unspec, [root,match,request], []}, from = {self(),make_ref()} }, R2 = #request { tmr = {relative, 1000}, call = noop, from = {self(),make_ref()} }, R3 = #request { tmr = {relative,?REQUEST_TMO}, call = {get,addr,unspec, [root,match,request], []}, from = {self(),make_ref()} }, {ok, State#state{ port=Port, request = R0, request_queue = [R1,R2,R3] }}. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({list,Match}, _From, State) -> lists:foreach( fun(L) -> Ys = [Y || Y <- State#state.addr_list, Y#addr.index =:= L#link.index], FYs = [format_addr(Y) || Y <- Ys ], case match(L#link.attr,dict:new(),Match) of true -> io:format("link {~s~s}\n", [FYs,format_link(L)]); false -> ok end end, State#state.link_list), {reply, ok, State}; handle_call({subscribe, Pid, Name, Options, Fs}, _From, State) -> Mon = erlang:monitor(process, Pid), S = #subscription { pid=Pid, mon=Mon, name=Name, fields=Fs }, SList = [S | State#state.sub_list], case proplists:get_bool(flush, Options) of false -> {reply, {ok,Mon}, State#state { sub_list = SList }}; true -> lists:foreach( fun(L) -> As = dict:to_list(L#link.attr), update_attrs(L#link.name, link, As, dict:new(), [S]) end, State#state.link_list), lists:foreach( fun(Y) -> As = dict:to_list(Y#addr.attr), update_attrs(Y#addr.name, addr, As, dict:new(), [S]) end, State#state.addr_list), {reply, {ok,Mon}, State#state { sub_list = SList }} end; handle_call({unsubscribe,Ref}, _From, State) -> case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of false -> {reply,ok,State}; {value,_S,SubList} -> erlang:demonitor(Ref), {reply,ok,State#state { sub_list=SubList }} end; handle_call({invalidate,Name,Fields},_From,State) -> case lists:keytake(Name, #link.name, State#state.link_list) of false -> {reply, {error,enoent}, State}; {value,L,Ls} -> Attr = lists:foldl( fun(F,D) when is_atom(F) -> dict:erase(F, D) end, L#link.attr, Fields), L1 = L#link { attr = Attr }, {reply, ok, State#state { link_list = [L1|Ls] } } end; handle_call(Req={get,_What,_Fam,_Flags,_Attrs}, From, State) -> ?log(debug, "handle_call: GET: ~p", [Req]), State1 = enq_request(Req, From, State), State2 = dispatch_command(State1), {noreply, State2}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info={nl_data,Port,Data},State) when Port =:= State#state.port -> try netlink_codec:decode(Data,[]) of MsgList -> FIXME : the messages should be delivered one by one from State1 = lists:foldl( fun(Msg,StateI) -> ?log(debug, "handle_info: msg=~p", [Msg]), _Hdr = Msg#nlmsg.hdr, MsgData = Msg#nlmsg.data, handle_nlmsg(MsgData, StateI) end, State, MsgList), {noreply, State1} catch ?EXCEPTION(error, _Reason, Stacktrace) -> ?log(error, "netlink: handle_info: Crash: ~p", [?GET_STACK(Stacktrace)]), {noreply, State} end; handle_info({'DOWN',Ref,process,Pid,Reason}, State) -> case lists:keytake(Ref, #subscription.mon, State#state.sub_list) of false -> {noreply,State}; {value,_S,SubList} -> ?log(debug, "subscription from pid ~p deleted reason=~p", [Pid, Reason]), {noreply,State#state { sub_list=SubList }} end; handle_info({timeout,Tmr,request_timeout}, State) -> R = State#state.request, if R#request.tmr =:= Tmr -> ?log(debug, "Timeout: ref current", []), gen_server:reply(R#request.from, {error,timeout}), State1 = State#state { request = undefined }, {noreply, dispatch_command(State1)}; true -> case lists:keytake(Tmr, #request.tmr, State#state.request_queue) of false -> ?log(debug, "Timeout: ref not found", []), {noreply, State}; {value,#request { from = From},Q} -> ?log(debug, "Timeout: ref in queue", []), gen_server:reply(From, {error,timeout}), State1 = State#state { request_queue = Q }, {noreply,dispatch_command(State1)} end end; handle_info({Tag, Reply}, State) when is_reference(Tag) -> ?log(debug, "INFO: SELF Reply=~p", [Reply]), {noreply, State}; handle_info(_Info, State) -> ?log(debug, "INFO: ~p", [_Info]), {noreply, State}. @private with . The return value is ignored . , State ) - > void ( ) terminate(_Reason, _State) -> ok. @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions enq_request(Call, From, State) -> Tmr = erlang:start_timer(?REQUEST_TMO, self(), request_timeout), R = #request { tmr = Tmr, call = Call, from = From }, Q = State#state.request_queue ++ [R], State#state { request_queue = Q }. dispatch_command(State) when State#state.request =:= undefined -> case State#state.request_queue of [R=#request { call = {get,What,Fam,Flags,Attrs} } | Q ] -> R1 = update_timer(R), State1 = State#state { request_queue = Q, request = R1 }, ?log(debug, "dispatch_command: ~p", [R1]), get_command(What,Fam,Flags,Attrs,State1); [R=#request { call = noop } | Q ] -> R1 = update_timer(R), State1 = State#state { request_queue = Q, request = R1 }, ?log(debug, "dispatch_command: ~p", [R1]), [] -> State end; dispatch_command(State) -> State. update_timer(R = #request { tmr = {relative,Tmo} }) when is_integer(Tmo), Tmo >= 0 -> Tmr = erlang:start_timer(Tmo, self(), request_timeout), R#request { tmr = Tmr }; update_timer(R = #request { tmr = Tmr }) when is_reference(Tmr) -> R. update_sndbuf(Port, Min) -> case netlink_drv:get_sndbuf(Port) of {ok,Size} when Size >= Min -> {ok,Size}; {ok,_Size} -> netlink_drv:set_sndbuf(Port, Min), netlink_drv:get_sndbuf(Port); Err -> Err end. update_rcvbuf(Port, Min) -> case netlink_drv:get_rcvbuf(Port) of {ok,Size} when Size >= Min -> {ok,Size}; {ok,_Size} -> netlink_drv:set_rcvbuf(Port, Min), netlink_drv:get_rcvbuf(Port); Err -> Err end. get_command(link,Fam,Flags,Attrs,State) -> Seq = State#state.o_seq, Get = #getlink{family=Fam,arphrd=ether,index=0, flags=[], change=[], attributes=Attrs}, Hdr = #nlmsghdr { type = getlink, flags = Flags, seq = Seq, pid = State#state.ospid }, Request = netlink_codec:encode(Hdr,Get), netlink_drv:send(State#state.port, Request), State#state { o_seq = (Seq+1) band 16#ffffffff }; get_command(addr,Fam,Flags,Attrs,State) -> Seq = State#state.o_seq, Get = #getaddr{family=Fam,prefixlen=0,flags=[],scope=0, index=0,attributes=Attrs}, Hdr = #nlmsghdr { type=getaddr, flags=Flags, seq=Seq, pid=State#state.ospid }, Request = netlink_codec:encode(Hdr,Get), netlink_drv:send(State#state.port, Request), State#state { o_seq = (Seq+1) band 16#ffffffff}. handle_nlmsg(RTM=#newlink{family=_Fam,index=Index,flags=Fs,change=Cs, attributes=As}, State) -> ?log(debug, "RTM = ~p", [RTM]), Name = proplists:get_value(ifname, As, ""), As1 = [{index,Index},{flags,Fs},{change,Cs}|As], case lists:keytake(Index, #link.index, State#state.link_list) of false -> Attr = update_attrs(Name, link, As1, dict:new(), State#state.sub_list), L = #link { index = Index, name = Name, attr = Attr }, Ls = [L|State#state.link_list], State#state { link_list = Ls }; {value,L,Ls} -> Attr = update_attrs(Name, link, As1, L#link.attr, State#state.sub_list), L1 = L#link { name = Name, attr = Attr }, State#state { link_list = [L1|Ls] } end; handle_nlmsg(RTM=#dellink{family=_Fam,index=Index,flags=_Fs,change=_Cs, attributes=As}, State) -> ?log(debug, "RTM = ~p\n", [RTM]), Name = proplists:get_value(ifname, As, ""), case lists:keytake(Index, #link.index, State#state.link_list) of false -> ?log(warning, "Warning link index=~w not found", [Index]), State; {value,L,Ls} -> As1 = dict:to_list(L#link.attr), update_attrs(Name, link, As1, undefined, State#state.sub_list), State#state { link_list = Ls } end; handle_nlmsg(RTM=#newaddr { family=Fam, prefixlen=Prefixlen, flags=Flags, scope=Scope, index=Index, attributes=As }, State) -> ?log(debug, "RTM = ~p", [RTM]), Addr = proplists:get_value(address, As, {}), Name = proplists:get_value(label, As, ""), As1 = [{family,Fam},{prefixlen,Prefixlen},{flags,Flags}, {scope,Scope},{index,Index} | As], case lists:keymember(Index, #link.index, State#state.link_list) of false -> ?log(warning, "link index ~p does not exist", [Index]); true -> ok end, case lists:keytake(Addr, #addr.addr, State#state.addr_list) of false -> Attrs = update_attrs(Name,addr,As1,dict:new(),State#state.sub_list), Y = #addr { addr=Addr, name = Name, index=Index, attr=Attrs }, Ys = [Y|State#state.addr_list], State#state { addr_list = Ys }; {value,Y,Ys} -> Attr = update_attrs(Name,addr,As1,Y#addr.attr,State#state.sub_list), Y1 = Y#addr { index=Index, name=Name, attr = Attr }, State#state { addr_list = [Y1|Ys] } end; handle_nlmsg(RTM=#deladdr { family=_Fam, index=_Index, attributes=As }, State) -> ?log(debug, "RTM = ~p", [RTM]), Addr = proplists:get_value(address, As, {}), Name = proplists:get_value(label, As, ""), case lists:keytake(Addr, #addr.addr, State#state.addr_list) of false -> ?log(warning, "Warning addr=~w not found", [Addr]), State; {value,Y,Ys} -> As1 = dict:to_list(Y#addr.attr), update_attrs(Name, addr, As1, undefined, State#state.sub_list), State#state { addr_list = Ys } end; handle_nlmsg(#done { }, State) -> case State#state.request of undefined -> dispatch_command(State); #request { tmr = Tmr, from = From, reply = Reply } -> ?log(debug, "handle_nlmsg: DONE: ~p", [State#state.request]), erlang:cancel_timer(Tmr), gen_server:reply(From, Reply), State1 = State#state { request = undefined }, dispatch_command(State1) end; handle_nlmsg(Err=#error { errno=Err }, State) -> ?log(debug, "handle_nlmsg: ERROR: ~p", [State#state.request]), case State#state.request of undefined -> dispatch_command(State); #request { tmr = Tmr, from = From } -> ?log(debug, "handle_nlmsg: DONE: ~p", [State#state.request]), erlang:cancel_timer(Tmr), fixme : convert errno to posix error ( netlink.inc ? ) gen_server:reply(From, {error,Err}), State1 = State#state { request = undefined }, dispatch_command(State1) end; handle_nlmsg(RTM, State) -> ?log(debug, "netlink: handle_nlmsg, ignore ~p", [RTM]), State. update_attrs(Name,Type,As,undefined,Subs) -> lists:foreach( fun({K,Vold}) -> send_event(Name,Type,K,Vold,undefined,Subs) end, As), undefined; update_attrs(Name,Type,As,To,Subs) -> lists:foldl( fun({K,Vnew},D) -> case dict:find(K,D) of error -> send_event(Name,Type,K,undefined,Vnew,Subs), dict:store(K,Vnew,D); {ok,Vold} -> send_event(Name,Type,K,Vold,Vnew,Subs), dict:store(K,Vnew,D) end end, To, As). send_event(Name,Type,Field,Old,New,[S|SList]) when S#subscription.name =:= Name; S#subscription.name =:= "" -> case S#subscription.fields =:= all orelse S#subscription.fields =:= Type orelse lists:member(Field,S#subscription.fields) orelse lists:member({Type,Field},S#subscription.fields) of true -> S#subscription.pid ! {netlink,S#subscription.mon, Name,Field,Old,New}, send_event(Name,Type,Field,Old,New,SList); false -> send_event(Name,Type,Field,Old,New,SList) end; send_event(Name,Type,Field,Old,New,[_|SList]) -> send_event(Name,Type,Field,Old,New,SList); send_event(_Name,_Type,_Field,_Old,_New,[]) -> ok. match(Y,L,[{Field,Value}|Match]) when is_atom(Field) -> case find2(Field,Y,L) of {ok,Value} -> match(Y, L, Match); _ -> false end; match(Y,L,[{Op,Field,Value}|Match]) when is_atom(Op),is_atom(Field) -> case find2(Y,L,Field) of {ok,FValue} -> case compare(Op,FValue,Value) of true -> match(Y,L,Match); false -> false end; error -> false end; match(_Y, _L, []) -> true. find2(Key,D1,D2) -> case dict:find(Key,D1) of error -> dict:find(Key,D2); Res -> Res end. format_link(L) -> dict:fold( fun(af_spec,_V,A) -> A; (map,_V,A) -> A; (stats,_V,A) -> A; (stats64,_V,A) -> A; (change,_V,A) -> A; (K,V,A) -> [["\n ",name_to_list(K), " ",value_to_list(K,V),";"]|A] end, [], L#link.attr). format_addr(Y) -> ["\n", " addr {", dict:fold( fun(cacheinfo,_V,A) -> A; (K,V,A) -> [[" ",name_to_list(K), " ",value_to_list(K,V),";"]|A] end, [], Y#addr.attr), "}"]. name_to_list(K) when is_atom(K) -> atom_to_list(K); name_to_list(K) when is_integer(K) -> integer_to_list(K). value_to_list(local,V) -> format_a(V); value_to_list(address,V) -> format_a(V); value_to_list(broadcast,V) -> format_a(V); value_to_list(multicast,V) -> format_a(V); value_to_list(anycast,V) -> format_a(V); value_to_list(_, V) -> io_lib:format("~p", [V]). format_a(undefined) -> ""; format_a(A) when is_tuple(A), tuple_size(A) =:= 6 -> io_lib:format("~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b:~2.16.0b", tuple_to_list(A)); format_a(A) when is_tuple(A), tuple_size(A) =:= 4 -> inet_parse:ntoa(A); format_a(A) when is_tuple(A), tuple_size(A) =:= 8 -> inet_parse:ntoa(A). compare('==',A,B) -> A == B; compare('=:=',A,B) -> A =:= B; compare('<' ,A,B) -> A < B; compare('=<' ,A,B) -> A =< B; compare('>' ,A,B) -> A > B; compare('>=' ,A,B) -> A >= B; compare('/=' ,A,B) -> A /= B; compare('=/=' ,A,B) -> A =/= B; compare(_,_,_) -> false.
136d9a1c0f5f2bbdd763553c442ea1f569cc1af4baa684fbbfbc3e4d3b98487d
tweag/asterius
cgrun057.hs
-- For testing +RTS -xc import Control.Exception main = try (evaluate (f ())) :: IO (Either SomeException ()) f x = g x g x = error (show x)
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/codeGen/cgrun057.hs
haskell
For testing +RTS -xc
import Control.Exception main = try (evaluate (f ())) :: IO (Either SomeException ()) f x = g x g x = error (show x)
4f24231e6d411bde14608e4b2e27f913a7f5c653f7de110cb84f0f226daa9cc7
ankushdas/Nomos
Typecheck.ml
(* Type Checking *) Use the syntax - directed rules to check the types and * raises ErrorMsg . Error if an error is discovered * raises ErrorMsg.Error if an error is discovered *) module R = Arith module A = Ast module PP = Pprint module E = TpError module I = Infer module F = RastFlags let error = ErrorMsg.error ErrorMsg.Type;; (*********************) (* Validity of types *) (*********************) (* Equi-Synchronizing Session Types Purely linear types are always equi-synchronizing *) let rec esync env seen tp c ext is_shared = if !F.verbosity >= 3 then print_string ("checking esync: \n" ^ PP.pp_tp env tp ^ "\n" ^ PP.pp_tp env c ^ "\n") ; match tp with A.Plus(choice) -> esync_choices env seen choice c ext is_shared | A.With(choice) -> esync_choices env seen choice c ext is_shared | A.Tensor(_a,b,_m) -> esync env seen b c ext is_shared | A.Lolli(_a,b,_m) -> esync env seen b c ext is_shared | A.One -> if is_shared then error ext ("type not equi-synchronizing") else () | A.PayPot(_pot,a) -> esync env seen a c ext is_shared | A.GetPot(_pot,a) -> esync env seen a c ext is_shared | A.TpName(v) -> if List.exists (fun x -> x = v) seen then () else esync env (v::seen) (A.expd_tp env v) c ext is_shared | A.Up(a) -> esync env seen a c ext true | A.Down(a) -> esync env seen a c ext false and esync_choices env seen cs c ext is_shared = match cs with (_l,a)::as' -> esync env seen a c ext is_shared ; esync_choices env seen as' c ext is_shared | [] -> ();; let esync_tp env tp ext = esync env [] tp tp ext false;; (* Occurrences of |> and <| are restricted to * positive and negative positions in a type, respectively *) type polarity = Pos | Neg | Zero;; valid env ctx con polarity A ext = ( ) * raises ErrorMsg . Error if not a valid type * env must be the full environment which checking any * type to allow mutually recursive definitions * Type A must be an actual type ( not ' . ' = A.Dot ) * raises ErrorMsg.Error if not a valid type * env must be the full environment which checking any * type to allow mutually recursive definitions * Type A must be an actual type (not '.' = A.Dot) *) let rec valid env pol tp ext = match pol, tp with _, A.Plus(choice) -> valid_choice env Pos choice ext | _, A.With(choice) -> valid_choice env Neg choice ext | _, A.Tensor(s,t,_m) -> valid env pol s ext ; valid env Pos t ext | _, A.Lolli(s,t,_m) -> valid env pol s ext ; valid env Neg t ext | _, A.One -> () | _, A.Up(a) -> valid env pol a ext | _, A.Down(a) -> valid env pol a ext | Pos, A.PayPot(A.Arith pot,a) -> if not (R.non_neg pot) (* allowing 0, for uniformity *) then error ext ("potential " ^ PP.pp_arith pot ^ " not positive") else valid env Pos a ext | Pos, A.PayPot(A.Star,a) -> valid env Pos a ext | Neg, A.PayPot(_,_) -> error ext ("|> appears in a negative context") | Zero, A.PayPot(_,_) -> error ext ("|> appears in a neutral context") | Pos, A.GetPot(_,_a) -> error ext ("<| appears in a positive context") | Zero, A.GetPot(_,_a) -> error ext ("<| appears in a neutral context") | Neg, A.GetPot(A.Arith pot,a) -> if not (R.non_neg pot) (* allowing 0, for uniformity *) then error ext ("potential " ^ PP.pp_arith pot ^ " not positive") else valid env Neg a ext | Neg, A.GetPot(A.Star,a) -> valid env Neg a ext | _, A.TpName(a) -> (* allow forward references since 'env' is the full environment *) match A.lookup_tp env a with None -> error ext ("type name " ^ a ^ " undefined") | Some (_) -> () and valid_choice env pol cs ext = match cs with [] -> () | (_l,al)::choices -> valid env pol al ext ; valid_choice env pol choices ext;; (***********************) (* Properties of types *) (***********************) let contractive tp = match tp with A.TpName(_a) -> false | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> true;; (*****************) (* Type equality *) (*****************) (* Type equality, equirecursively defined *) (* Structural equality *) let zero = A.Arith (R.Int 0);; let eq pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> true | A.Arith p1, A.Arith p2 -> I.eq p1 p2;; let ge pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> true | A.Arith p1, A.Arith p2 -> I.ge p1 p2;; let minus pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> A.Star | A.Arith p1, A.Arith p2 -> A.Arith (R.minus p1 p2);; let plus pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> A.Star | A.Arith p1, A.Arith p2 -> A.Arith (R.plus p1 p2);; let pp_uneq pot1 pot2 = match pot1, pot2 with A.Star, A.Star -> "* != *" | A.Arith p1, A.Star -> R.pp_arith p1 ^ " != *" | A.Star, A.Arith p2 -> "* != " ^ R.pp_arith p2 | A.Arith p1, A.Arith p2 -> R.pp_uneq p1 p2;; let pp_lt pot1 pot2 = match pot1, pot2 with A.Star, A.Star -> "* < *" | A.Arith p1, A.Star -> R.pp_arith p1 ^ " < *" | A.Star, A.Arith p2 -> "* < " ^ R.pp_arith p2 | A.Arith p1, A.Arith p2 -> R.pp_lt p1 p2;; let mode_L (_c,m) = match m with A.Linear | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Linear | _ -> false;; let mode_S (_c,m) = match m with A.Shared | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Shared | _ -> false;; let mode_P (_c,m) = match m with A.Pure | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Pure | _ -> false;; let mode_T (_c,m) = match m with A.Transaction | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Transaction | _ -> false;; let mode_lin (_c,m) = match m with A.Pure | A.Linear | A.Transaction | A.Unknown -> true | A.Var v -> I.m_lin v | _ -> false;; let eqmode m1 m2 = match m1, m2 with A.Pure, A.Pure | A.Linear, A.Linear | A.Transaction, A.Transaction | A.Shared, A.Shared | A.Unknown, _ | _, A.Unknown -> true | A.Var v1, A.Var v2 -> I.m_eq v1 v2 | A.Var v, _ -> I.m_eq_const v m2 | _, A.Var v -> I.m_eq_const v m1 | _, _ -> false;; let mode_spawn m1 m2 = match m1, m2 with A.Pure, A.Pure | A.Pure, A.Shared | A.Pure, A.Linear | A.Pure, A.Transaction | A.Shared, A.Shared | A.Shared, A.Linear | A.Shared, A.Transaction | A.Transaction, A.Transaction -> true | _, _ -> false;; let mode_recv m1 m2 = match m1, m2 with A.Unknown, _ -> true | A.Pure, A.Pure -> true | A.Var v, A.Pure -> I.m_eq_const v A.Pure | _, A.Pure -> false | A.Pure, A.Shared | A.Shared, A.Shared -> true | A.Var v, A.Shared -> I.m_eq_pair v A.Pure A.Shared | _, A.Shared -> false | _, A.Linear -> true | _, A.Transaction -> true | _, _ -> false;; let rec mem_env env a a' = match env with {A.declaration = A.TpEq(A.TpName(b),A.TpName(b')); decl_extent = _ext}::env' -> if b = a && b' = a' then true else if b = a' && b' = a then true (* flip! *) else mem_env env' a a' | _decl::env' -> mem_env env' a a' | [] -> false let rec mem_seen env seen a a' = match seen with (b,b')::seen' -> if b = a && b' = a' then true else if b = a' && b' = a then true else mem_seen env seen' a a' | [] -> mem_env env a a' (* eq_tp env con seen A A' = true if (A = A'), defined coinductively *) let rec eq_tp' env seen a a' = if !F.verbosity >= 3 then print_string ("comparing " ^ PP.pp_tp env a ^ " and " ^ PP.pp_tp env a' ^ "\n") else () ; eq_tp env seen a a' and eq_tp env seen tp tp' = match tp, tp' with A.Plus(choice), A.Plus(choice') -> eq_choice env seen choice choice' | A.With(choice), A.With(choice') -> eq_choice env seen choice choice' | A.Tensor(s,t,m), A.Tensor(s',t',m') -> eqmode m m' && eq_tp' env seen s s' && eq_tp' env seen t t' | A.Lolli(s,t,m), A.Lolli(s',t',m') -> eqmode m m' && eq_tp' env seen s s' && eq_tp' env seen t t' | A.One, A.One -> true | A.PayPot(pot,a), A.PayPot(pot',a') -> eq pot pot' && eq_tp' env seen a a' | A.GetPot(pot,a), A.GetPot(pot',a') -> eq pot pot' && eq_tp' env seen a a' | A.Up(a), A.Up(a') -> eq_tp' env seen a a' | A.Down(a), A.Down(a') -> eq_tp' env seen a a' | A.TpName(a), A.TpName(a') -> eq_name_name env seen a a' (* coinductive type equality *) | A.TpName(a), a' -> eq_tp' env seen (A.expd_tp env a) a' | a, A.TpName(a') -> eq_tp' env seen a (A.expd_tp env a') | _a, _a' -> false and eq_choice env seen cs cs' = match cs, cs' with [], [] -> true | (l,a)::choice, (l',a')::choice' -> (* order must be equal *) l = l' && eq_tp' env seen a a' && eq_choice env seen choice choice' | _cs, [] -> false | [], _cs' -> false and eq_name_name env seen a a' = if mem_seen env seen a a' then true else eq_tp' env ((a,a')::seen) (A.expd_tp env a) (A.expd_tp env a');; let eqtp env tp tp' = eq_tp' env [] tp tp';; (*************************************) (* Type checking process expressions *) (*************************************) exception UnknownTypeError;; let chan_of (c, _tp) = c let tp_of (_c, tp) = tp;; let name_of (c,_m) = c;; let eq_name (c1,_m1) (c2,_m2) = c1 = c2;; let eq_mode (_c1,m1) (_c2,m2) = eqmode m1 m2;; let eq_chan c1 c2 = if eq_name c1 c2 && eq_mode c1 c2 then true else false;; let rec checktp c delta = match delta with [] -> false | (x,_t)::delta' -> if eq_name x c then true else checktp c delta';; let check_tp c delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in checktp c sdelta || checktp c ldelta;; let check_stp c delta = let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in checktp c sdelta;; let check_ltp c delta = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in checktp c ldelta;; let rec pure delta = match delta with [] -> true | (c,_t)::delta' -> if not (mode_P c) then false else pure delta';; let purelin delta = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in pure ldelta;; must check for existence first let rec findtp c delta ext = match delta with [] -> raise UnknownTypeError | (x,t)::delta' -> if eq_chan x c then t else findtp c delta' ext;; let find_stp c delta ext = let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in if not (mode_S c) then error ext ("mode of channel " ^ PP.pp_chan c ^ " not S") else findtp c sdelta ext;; let find_ltp c delta ext = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in if not (mode_lin c) then E.error_mode_shared_comm (c, ext) else findtp c ldelta ext;; let rec removetp x delta = match delta with [] -> [] | (y,t)::delta' -> if eq_name x y then delta' else (y,t)::(removetp x delta');; let remove_tp x delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in {A.shared = removetp x sdelta ; A.linear = removetp x ldelta ; A.ordered = removetp x odelta};; let add_chan env (x,a) delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in if A.is_shared env a then {A.shared = (x,a)::sdelta ; A.linear = ldelta ; A.ordered = (x,a)::odelta} else {A.shared = sdelta ; A.linear = (x,a)::ldelta ; A.ordered = (x,a)::odelta};; let update_tp env x t delta = let delta = remove_tp x delta in add_chan env (x,t) delta;; let rec match_ctx env sig_ctx ctx delta sig_len len ext = match sig_ctx, ctx with (sc,st)::sig_ctx', c::ctx' -> begin if not (check_tp c delta) then error ext ("unknown or duplicate variable: " ^ PP.pp_chan c) else if not (eq_mode sc c) then E.error_mode_mismatch (sc, c, ext) else let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in if checktp c sdelta then begin let t = find_stp c delta ext in if eqtp env st t then match_ctx env sig_ctx' ctx' delta sig_len len ext else error ext ("shared type mismatch: type of " ^ PP.pp_chan c ^ " : " ^ PP.pp_tp_compact env t ^ " does not match type in declaration: " ^ PP.pp_tp_compact env st) end else begin let t = find_ltp c delta ext in if eqtp env st t then match_ctx env sig_ctx' ctx' (remove_tp c delta) sig_len len ext else error ext ("linear type mismatch: type of " ^ PP.pp_chan c ^ " : " ^ PP.pp_tp_compact env t ^ " does not match type in declaration: " ^ PP.pp_tp_compact env st) end end | [], [] -> delta | _, _ -> error ext ("process defined with " ^ string_of_int sig_len ^ " arguments but called with " ^ string_of_int len ^ " arguments");; let join delta = let {A.shared = _sdelta ; A.linear = _ldelta ; A.ordered = odelta} = delta in odelta;; check_exp trace env ctx con A pot P C = ( ) if A |{pot}- P : C * raises ErrorMsg . Error otherwise * assumes ctx ; con |= A valid * ctx ; con |= C valid * ctx ; con |= pot nat * * trace = true means to print some tracing information * * entry point is check_exp ' * * We expand type definitions lazily , based on the direction of * interactions . This is done so tracing ( if enabled ) or error * message are more intelligible . * raises ErrorMsg.Error otherwise * assumes ctx ; con |= A valid * ctx ; con |= C valid * ctx ; con |= pot nat * * trace = true means to print some tracing information * * entry point is check_exp' * * We expand type definitions lazily, based on the direction of * interactions. This is done so tracing (if enabled) or error * message are more intelligible. *) let rec check_exp' trace env delta pot p zc ext mode = begin if trace then print_string ("[" ^ PP.pp_mode mode ^ "] : " ^ PP.pp_exp_prefix p ^ " : " ^ PP.pp_tpj_compact env delta pot zc ^ "\n") else () end ; check_exp trace env delta pot p zc ext mode (* judgmental constructs: id, cut, spawn, call *) and check_exp trace env delta pot exp zc ext mode = match exp with A.Fwd(x,y) -> begin let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in let tx = chan_of zc in let () = if not (eq_name x tx) then E.error_unknown_var_right (x,ext) else if not (eq_mode x tx) then E.error_mode_mismatch (x, tx, ext) else if not (eq_mode x y) then error ext ("mode mismatch: " ^ PP.pp_chan x ^ " != " ^ PP.pp_chan y) else () in let c = tp_of zc in if A.is_shared env c then begin if List.length sdelta = 0 then error ext ("shared context empty while offered channel is shared") else if not (checktp y sdelta) then E.error_unknown_var_ctx (y,ext) else let a = find_stp y delta ext in if eqtp env a c then () else error ext ("left type " ^ PP.pp_tp_compact env a ^ " not equal to right type " ^ PP.pp_tp_compact env c) end else begin let (ty, a) = List.hd ldelta in if List.length ldelta <> 1 then error ext ("linear context " ^ PP.pp_lsctx env ldelta ^ " must have only one channel") else if not (eq_name y ty) then E.error_unknown_var_ctx (y,ext) else if not (eq_mode y ty) then E.error_mode_mismatch (y, ty, ext) else if not (eq pot zero) then error ext ("unconsumed potential: " ^ pp_uneq pot zero) else if eqtp env a c then () else error ext ("left type " ^ PP.pp_tp_compact env a ^ " not equal to right type " ^ PP.pp_tp_compact env c) end end | A.Spawn(x,f,xs,q) -> begin match A.lookup_expdec env f with None -> E.error_undeclared (f, ext) | Some (ctx,lpot,(x',a'),mdef) -> let (_x,mx) = x in if not (ge pot lpot) then error ext ("insufficient potential to spawn: " ^ pp_lt pot lpot) else if not (eq_mode x x') then E.error_mode_mismatch (x, x', ext) else if not (eqmode mx mdef) then error ext ("mode mismatch: expected " ^ PP.pp_mode mdef ^ " at declaration, found: " ^ PP.pp_chan x) else if not (mode_spawn mdef mode) then error ext ("cannot spawn at mode " ^ PP.pp_mode mdef ^ " when current mode is " ^ PP.pp_mode mode) else let ctx = join ctx in let delta' = match_ctx env ctx xs delta (List.length ctx) (List.length xs) ext in check_exp' trace env (add_chan env (x,a') delta') (minus pot lpot) q zc ext mode end | A.ExpName(x,f,xs) -> begin match A.lookup_expdec env f with None -> E.error_undeclared (f, ext) | Some (ctx,lpot,(x',a'),mdef) -> let (_x,mx) = x in if not (eq pot lpot) then error ext ("potential mismatch for tail call: " ^ pp_uneq pot lpot) else if not (eq_mode x x') then E.error_mode_mismatch (x, x', ext) else if not (eqmode mx mdef) then error ext ("mode mismatch: expected " ^ PP.pp_mode mdef ^ " at declaration, found: " ^ PP.pp_chan x) else if not (mode_spawn mdef mode) then error ext ("cannot tail call at mode " ^ PP.pp_mode mdef ^ " when current mode is " ^ PP.pp_mode mode) else let (z,c) = zc in if not (eq_name x z) then E.error_unknown_var_right (x,ext) else if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (eqtp env a' c) then error ext ("type mismatch on right, expected: " ^ PP.pp_tp_compact env a' ^ ", found: " ^ PP.pp_tp_compact env c) else let ctx = join ctx in let delta' = match_ctx env ctx xs delta (List.length ctx) (List.length xs) ext in if List.length delta'.linear <> 0 then error ext ("unconsumed channel(s) from linear context: " ^ PP.pp_lsctx env delta'.linear) else () end | A.Lab(x,k,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be internal choice *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Plus(choices) -> begin match A.lookup_choice choices k with None -> E.error_label_invalid env (k,c,z,ext) | Some ck -> check_exp' trace env delta pot p (z,ck) ext mode end | A.With _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan z ^ ", expected internal choice, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be external choice *) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.With(choices) -> begin match A.lookup_choice choices k with None -> E.error_label_invalid env (k,a,x,ext) | Some ak -> check_exp' trace env (update_tp env x ak delta) pot p zc ext mode end | A.Plus _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected external choice, found: " ^ PP.pp_tp_compact env a) end | A.Case(x,branches) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be external choice *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.With(choices) -> check_branchesR trace env delta pot branches z choices ext mode | A.Plus _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan z ^ ", expected external choice, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be internal choice *) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Plus(choices) -> check_branchesL trace env delta x choices pot branches zc ext mode | A.With _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected internal choice, found: " ^ PP.pp_tp_compact env a) end | A.Send(x,w,p) -> begin if not (check_tp w delta) then E.error_unknown_var_ctx (w,ext) else if check_ltp w delta then begin let a' = find_ltp w delta ext in if not (check_tp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be tensor *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Tensor(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (remove_tp w delta) pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be lolli *) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Lolli(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (update_tp env x b (remove_tp w delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env d) end else begin let a' = find_stp w delta ext in if not (check_tp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be tensor *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Tensor(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env delta pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be lolli *) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Lolli(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (update_tp env x b delta) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env d) end end | A.Recv(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be lolli *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Lolli(a,b,m) -> let (_y,my) = y in if not (eqmode m my) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan y) else if not (mode_recv m mode) then error ext ("cannot receive at mode " ^ PP.pp_mode m ^ " when current mode is " ^ PP.pp_mode mode) else check_exp' trace env (add_chan env (y,a) delta) pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be tensor *) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Tensor(a,b,m) -> let (_y,my) = y in if not (eqmode m my) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan y) else if not (mode_recv m mode) then error ext ("cannot receive at mode " ^ PP.pp_mode m ^ " when current mode is " ^ PP.pp_mode mode) else check_exp' trace env (add_chan env (y,a) (update_tp env x b delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env d) end | A.Close(x) -> begin let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in if List.length ldelta > 0 then error ext ("linear context " ^ PP.pp_lsctx env ldelta ^ " not empty") else if not (checktp x [zc]) then E.error_unknown_var (x,ext) else if not (eq pot zero) then error ext ("unconsumed potential: " ^ pp_uneq pot zero) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else if not (eqtp env c A.One) then error ext ("type mismatch: type of " ^ PP.pp_chan x ^ ", expected: 1, " ^ "found: " ^ PP.pp_tp_compact env c) else () end | A.Wait(x,p) -> begin if not (check_ltp x delta) then E.error_unknown_var (x,ext) else let a = find_ltp x delta ext in if not (eqtp env a A.One) then error ext ("type mismatch: type of " ^ PP.pp_chan x ^ ", expected: 1, " ^ " found: " ^ PP.pp_tp_compact env a) else check_exp' trace env (remove_tp x delta) pot p zc ext mode end | A.Work(pot',p) -> begin if not (ge pot pot') then error ext ("insufficient potential to work: " ^ pp_lt pot pot') else if not (ge pot' zero) then error ext ("potential not positive: " ^ pp_lt pot' zero) else check_exp' trace env delta (minus pot pot') p zc ext mode end | A.Pay(x,epot,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) else (* the type c of z must be paypot *) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.PayPot(tpot,c') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else if not (ge pot tpot) then error ext ("insufficient potential to pay: " ^ pp_lt pot tpot) else check_exp' trace env delta (minus pot tpot) p (z,c') ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected paypot, found: " ^ PP.pp_tp_compact env c) the type a of x must be let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.GetPot(tpot,a') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else if not (ge pot epot) then error ext ("insufficient potential to pay: " ^ pp_lt pot epot) else check_exp' trace env (update_tp env x a' delta) (minus pot epot) p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected getpot, found: " ^ PP.pp_tp_compact env a) end | A.Get(x,epot,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) the type c of z must be let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.GetPot(tpot,c') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else check_exp' trace env delta (plus pot epot) p (z,c') ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected getpot, found: " ^ PP.pp_tp_compact env c) else (* the type a of x must be paypot *) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.PayPot(tpot,a') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else check_exp' trace env (update_tp env x a' delta) (plus pot epot) p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected paypot, found: " ^ PP.pp_tp_compact env a) end | A.Acquire(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_stp x delta) then E.error_unknown_var_ctx (x,ext) else if not (mode_L y) then error ext ("mode mismatch of acquired channel: expected L, found " ^ PP.pp_chan y) else if not (mode_S x) then error ext ("mode mismatch of acquiring channel: expected S, found " ^ PP.pp_chan x) else let a = find_stp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Up(a') -> check_exp' trace env (add_chan env (y,a') (remove_tp x delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected up, found: " ^ PP.pp_tp_compact env a) end | A.Accept(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (checktp x [zc]) then E.error_unknown_var_right (x,ext) else if not (mode_L y) then error ext ("mode mismatch of accepted channel: expected L, found " ^ PP.pp_chan y) else if not (mode_S x) then error ext ("mode mismatch of accepting channel: expected S, found " ^ PP.pp_chan x) else if not (purelin delta) then error ext ("independence principle violated: " ^ "expected pure linear context, found: " ^ PP.pp_lsctx env delta.linear) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Up(c') -> check_exp' trace env delta pot p (y,c') ext A.Linear | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected up, found: " ^ PP.pp_tp_compact env c) end | A.Release(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_ltp x delta) then E.error_unknown_var_ctx (x,ext) else if not (mode_S y) then error ext ("mode mismatch of released channel: expected S, found " ^ PP.pp_chan y) else if not (mode_L x) then error ext ("mode mismatch of releasing channel: expected L, found " ^ PP.pp_chan x) else let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Down(a') -> check_exp' trace env (add_chan env (y,a') (remove_tp x delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected down, found: " ^ PP.pp_tp_compact env a) end | A.Detach(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (checktp x [zc]) then E.error_unknown_var_right (x,ext) else if not (mode_S y) then error ext ("mode mismatch of detached channel: expected S, found " ^ PP.pp_chan y) else if not (mode_L x) then error ext ("mode mismatch of detaching channel: expected L, found " ^ PP.pp_chan x) else if not (purelin delta) then error ext ("independence principle violated: " ^ "expected empty linear context, found: " ^ PP.pp_lsctx env delta.linear) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Down(c') -> check_exp' trace env delta pot p (y,c') ext A.Shared | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected down, found: " ^ PP.pp_tp_compact env c) end | A.Marked(marked_P) -> check_exp trace env delta pot (Mark.data marked_P) zc (Mark.ext marked_P) mode and check_branchesR trace env delta pot branches z choices ext mode = match branches, choices with {lab_exp = (l1,p); exp_extent = bext}::branches', (l2,c)::choices' -> begin if trace then print_string ("| " ^ l1 ^ " => \n") else () ; if l1 = l2 then () else E.error_label_mismatch (l1, l2, bext) ; check_exp' trace env delta pot p (z,c) ext mode ; check_branchesR trace env delta pot branches' z choices' ext mode end | [], [] -> () | {lab_exp = (l,_p); exp_extent = bext}::_branches', [] -> E.error_label_missing_alt (l, bext) | [], (l,_c)::_choices' -> E.error_label_missing_branch (l, ext) and check_branchesL trace env delta x choices pot branches zc ext mode = match choices, branches with (l1,a)::choices', {lab_exp = (l2,p); exp_extent = bext}::branches' -> begin if trace then print_string ("| " ^ l1 ^ " => \n") else () ; if l1 = l2 then () else E.error_label_mismatch (l1, l2, bext) ; check_exp' trace env (update_tp env x a delta) pot p zc ext mode ; check_branchesL trace env delta x choices' pot branches' zc ext mode end | [], [] -> () | [], {lab_exp = (l,_p); exp_extent = bext}::_branches' -> E.error_label_missing_alt (l,bext) | (l,_a)::_choices', [] -> E.error_label_missing_branch (l,ext);; (* external interface *) let checkexp = check_exp';; let rec find_tp x sdelta ldelta = match sdelta, ldelta with [], [] -> raise UnknownTypeError | (y,_t1)::sdelta', (z,_t2)::ldelta' -> if eq_name x y then y else if eq_name x z then z else find_tp x sdelta' ldelta' | (y,_t)::sdelta', [] -> if eq_name x y then y else find_tp x sdelta' [] | [], (z,_t)::ldelta' -> if eq_name x z then z else find_tp x [] ldelta';; let rec consistent_mode f sdelta ldelta odelta ext = match odelta with [] -> () | (x,_t)::odelta' -> let y = find_tp x sdelta ldelta in if not (eq_mode x y) then E.error_mode_mismatch (x, y, ext) else consistent_mode f sdelta ldelta odelta' ext;; let rec mode_P_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_P x) then false else mode_P_list delta';; let pure env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_P x) then error ext ("asset process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if List.length sdelta > 0 then error ext ("asset process " ^ f ^ " has non-empty shared context: " ^ PP.pp_lsctx env sdelta) else if not (mode_P_list ldelta) then error ext ("asset process " ^ f ^ " has non-pure linear context: " ^ PP.pp_lsctx env ldelta) else ();; let rec mode_S_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_S x) then false else mode_S_list delta';; let shared env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_S x) then error ext ("shared process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if not (mode_S_list sdelta) then error ext ("shared process " ^ f ^ " has non-shared context: " ^ PP.pp_lsctx env sdelta) else if not (mode_P_list ldelta) then error ext ("shared process " ^ f ^ " has non-pure linear context: " ^ PP.pp_lsctx env ldelta) else ();; let rec mode_lin_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_lin x) then false else mode_lin_list delta';; let transaction env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_T x) then error ext ("transaction process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if not (mode_S_list sdelta) then error ext ("transaction process " ^ f ^ " has shared context not at shared mode: " ^ PP.pp_lsctx env sdelta) else if not (mode_lin_list ldelta) then error ext ("transaction process " ^ f ^ " has linear context not at linear mode: " ^ PP.pp_lsctx env ldelta) else ();; structure
null
https://raw.githubusercontent.com/ankushdas/Nomos/db678f3981e75a1b3310bb55f66009bb23430cb1/rast/Typecheck.ml
ocaml
Type Checking ******************* Validity of types ******************* Equi-Synchronizing Session Types Purely linear types are always equi-synchronizing Occurrences of |> and <| are restricted to * positive and negative positions in a type, respectively allowing 0, for uniformity allowing 0, for uniformity allow forward references since 'env' is the full environment ********************* Properties of types ********************* *************** Type equality *************** Type equality, equirecursively defined Structural equality flip! eq_tp env con seen A A' = true if (A = A'), defined coinductively coinductive type equality order must be equal *********************************** Type checking process expressions *********************************** judgmental constructs: id, cut, spawn, call the type c of z must be internal choice the type a of x must be external choice the type c of z must be external choice the type a of x must be internal choice the type c of z must be tensor the type a of x must be lolli the type c of z must be tensor the type a of x must be lolli the type c of z must be lolli the type a of x must be tensor the type c of z must be paypot the type a of x must be paypot external interface
Use the syntax - directed rules to check the types and * raises ErrorMsg . Error if an error is discovered * raises ErrorMsg.Error if an error is discovered *) module R = Arith module A = Ast module PP = Pprint module E = TpError module I = Infer module F = RastFlags let error = ErrorMsg.error ErrorMsg.Type;; let rec esync env seen tp c ext is_shared = if !F.verbosity >= 3 then print_string ("checking esync: \n" ^ PP.pp_tp env tp ^ "\n" ^ PP.pp_tp env c ^ "\n") ; match tp with A.Plus(choice) -> esync_choices env seen choice c ext is_shared | A.With(choice) -> esync_choices env seen choice c ext is_shared | A.Tensor(_a,b,_m) -> esync env seen b c ext is_shared | A.Lolli(_a,b,_m) -> esync env seen b c ext is_shared | A.One -> if is_shared then error ext ("type not equi-synchronizing") else () | A.PayPot(_pot,a) -> esync env seen a c ext is_shared | A.GetPot(_pot,a) -> esync env seen a c ext is_shared | A.TpName(v) -> if List.exists (fun x -> x = v) seen then () else esync env (v::seen) (A.expd_tp env v) c ext is_shared | A.Up(a) -> esync env seen a c ext true | A.Down(a) -> esync env seen a c ext false and esync_choices env seen cs c ext is_shared = match cs with (_l,a)::as' -> esync env seen a c ext is_shared ; esync_choices env seen as' c ext is_shared | [] -> ();; let esync_tp env tp ext = esync env [] tp tp ext false;; type polarity = Pos | Neg | Zero;; valid env ctx con polarity A ext = ( ) * raises ErrorMsg . Error if not a valid type * env must be the full environment which checking any * type to allow mutually recursive definitions * Type A must be an actual type ( not ' . ' = A.Dot ) * raises ErrorMsg.Error if not a valid type * env must be the full environment which checking any * type to allow mutually recursive definitions * Type A must be an actual type (not '.' = A.Dot) *) let rec valid env pol tp ext = match pol, tp with _, A.Plus(choice) -> valid_choice env Pos choice ext | _, A.With(choice) -> valid_choice env Neg choice ext | _, A.Tensor(s,t,_m) -> valid env pol s ext ; valid env Pos t ext | _, A.Lolli(s,t,_m) -> valid env pol s ext ; valid env Neg t ext | _, A.One -> () | _, A.Up(a) -> valid env pol a ext | _, A.Down(a) -> valid env pol a ext | Pos, A.PayPot(A.Arith pot,a) -> then error ext ("potential " ^ PP.pp_arith pot ^ " not positive") else valid env Pos a ext | Pos, A.PayPot(A.Star,a) -> valid env Pos a ext | Neg, A.PayPot(_,_) -> error ext ("|> appears in a negative context") | Zero, A.PayPot(_,_) -> error ext ("|> appears in a neutral context") | Pos, A.GetPot(_,_a) -> error ext ("<| appears in a positive context") | Zero, A.GetPot(_,_a) -> error ext ("<| appears in a neutral context") | Neg, A.GetPot(A.Arith pot,a) -> then error ext ("potential " ^ PP.pp_arith pot ^ " not positive") else valid env Neg a ext | Neg, A.GetPot(A.Star,a) -> valid env Neg a ext | _, A.TpName(a) -> match A.lookup_tp env a with None -> error ext ("type name " ^ a ^ " undefined") | Some (_) -> () and valid_choice env pol cs ext = match cs with [] -> () | (_l,al)::choices -> valid env pol al ext ; valid_choice env pol choices ext;; let contractive tp = match tp with A.TpName(_a) -> false | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> true;; let zero = A.Arith (R.Int 0);; let eq pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> true | A.Arith p1, A.Arith p2 -> I.eq p1 p2;; let ge pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> true | A.Arith p1, A.Arith p2 -> I.ge p1 p2;; let minus pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> A.Star | A.Arith p1, A.Arith p2 -> A.Arith (R.minus p1 p2);; let plus pot1 pot2 = match pot1, pot2 with A.Star, A.Star | A.Star, A.Arith _ | A.Arith _, A.Star -> A.Star | A.Arith p1, A.Arith p2 -> A.Arith (R.plus p1 p2);; let pp_uneq pot1 pot2 = match pot1, pot2 with A.Star, A.Star -> "* != *" | A.Arith p1, A.Star -> R.pp_arith p1 ^ " != *" | A.Star, A.Arith p2 -> "* != " ^ R.pp_arith p2 | A.Arith p1, A.Arith p2 -> R.pp_uneq p1 p2;; let pp_lt pot1 pot2 = match pot1, pot2 with A.Star, A.Star -> "* < *" | A.Arith p1, A.Star -> R.pp_arith p1 ^ " < *" | A.Star, A.Arith p2 -> "* < " ^ R.pp_arith p2 | A.Arith p1, A.Arith p2 -> R.pp_lt p1 p2;; let mode_L (_c,m) = match m with A.Linear | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Linear | _ -> false;; let mode_S (_c,m) = match m with A.Shared | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Shared | _ -> false;; let mode_P (_c,m) = match m with A.Pure | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Pure | _ -> false;; let mode_T (_c,m) = match m with A.Transaction | A.Unknown -> true | A.Var v -> I.m_eq_const v A.Transaction | _ -> false;; let mode_lin (_c,m) = match m with A.Pure | A.Linear | A.Transaction | A.Unknown -> true | A.Var v -> I.m_lin v | _ -> false;; let eqmode m1 m2 = match m1, m2 with A.Pure, A.Pure | A.Linear, A.Linear | A.Transaction, A.Transaction | A.Shared, A.Shared | A.Unknown, _ | _, A.Unknown -> true | A.Var v1, A.Var v2 -> I.m_eq v1 v2 | A.Var v, _ -> I.m_eq_const v m2 | _, A.Var v -> I.m_eq_const v m1 | _, _ -> false;; let mode_spawn m1 m2 = match m1, m2 with A.Pure, A.Pure | A.Pure, A.Shared | A.Pure, A.Linear | A.Pure, A.Transaction | A.Shared, A.Shared | A.Shared, A.Linear | A.Shared, A.Transaction | A.Transaction, A.Transaction -> true | _, _ -> false;; let mode_recv m1 m2 = match m1, m2 with A.Unknown, _ -> true | A.Pure, A.Pure -> true | A.Var v, A.Pure -> I.m_eq_const v A.Pure | _, A.Pure -> false | A.Pure, A.Shared | A.Shared, A.Shared -> true | A.Var v, A.Shared -> I.m_eq_pair v A.Pure A.Shared | _, A.Shared -> false | _, A.Linear -> true | _, A.Transaction -> true | _, _ -> false;; let rec mem_env env a a' = match env with {A.declaration = A.TpEq(A.TpName(b),A.TpName(b')); decl_extent = _ext}::env' -> if b = a && b' = a' then true else mem_env env' a a' | _decl::env' -> mem_env env' a a' | [] -> false let rec mem_seen env seen a a' = match seen with (b,b')::seen' -> if b = a && b' = a' then true else if b = a' && b' = a then true else mem_seen env seen' a a' | [] -> mem_env env a a' let rec eq_tp' env seen a a' = if !F.verbosity >= 3 then print_string ("comparing " ^ PP.pp_tp env a ^ " and " ^ PP.pp_tp env a' ^ "\n") else () ; eq_tp env seen a a' and eq_tp env seen tp tp' = match tp, tp' with A.Plus(choice), A.Plus(choice') -> eq_choice env seen choice choice' | A.With(choice), A.With(choice') -> eq_choice env seen choice choice' | A.Tensor(s,t,m), A.Tensor(s',t',m') -> eqmode m m' && eq_tp' env seen s s' && eq_tp' env seen t t' | A.Lolli(s,t,m), A.Lolli(s',t',m') -> eqmode m m' && eq_tp' env seen s s' && eq_tp' env seen t t' | A.One, A.One -> true | A.PayPot(pot,a), A.PayPot(pot',a') -> eq pot pot' && eq_tp' env seen a a' | A.GetPot(pot,a), A.GetPot(pot',a') -> eq pot pot' && eq_tp' env seen a a' | A.Up(a), A.Up(a') -> eq_tp' env seen a a' | A.Down(a), A.Down(a') -> eq_tp' env seen a a' | A.TpName(a), A.TpName(a') -> | A.TpName(a), a' -> eq_tp' env seen (A.expd_tp env a) a' | a, A.TpName(a') -> eq_tp' env seen a (A.expd_tp env a') | _a, _a' -> false and eq_choice env seen cs cs' = match cs, cs' with [], [] -> true l = l' && eq_tp' env seen a a' && eq_choice env seen choice choice' | _cs, [] -> false | [], _cs' -> false and eq_name_name env seen a a' = if mem_seen env seen a a' then true else eq_tp' env ((a,a')::seen) (A.expd_tp env a) (A.expd_tp env a');; let eqtp env tp tp' = eq_tp' env [] tp tp';; exception UnknownTypeError;; let chan_of (c, _tp) = c let tp_of (_c, tp) = tp;; let name_of (c,_m) = c;; let eq_name (c1,_m1) (c2,_m2) = c1 = c2;; let eq_mode (_c1,m1) (_c2,m2) = eqmode m1 m2;; let eq_chan c1 c2 = if eq_name c1 c2 && eq_mode c1 c2 then true else false;; let rec checktp c delta = match delta with [] -> false | (x,_t)::delta' -> if eq_name x c then true else checktp c delta';; let check_tp c delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in checktp c sdelta || checktp c ldelta;; let check_stp c delta = let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in checktp c sdelta;; let check_ltp c delta = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in checktp c ldelta;; let rec pure delta = match delta with [] -> true | (c,_t)::delta' -> if not (mode_P c) then false else pure delta';; let purelin delta = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in pure ldelta;; must check for existence first let rec findtp c delta ext = match delta with [] -> raise UnknownTypeError | (x,t)::delta' -> if eq_chan x c then t else findtp c delta' ext;; let find_stp c delta ext = let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in if not (mode_S c) then error ext ("mode of channel " ^ PP.pp_chan c ^ " not S") else findtp c sdelta ext;; let find_ltp c delta ext = let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in if not (mode_lin c) then E.error_mode_shared_comm (c, ext) else findtp c ldelta ext;; let rec removetp x delta = match delta with [] -> [] | (y,t)::delta' -> if eq_name x y then delta' else (y,t)::(removetp x delta');; let remove_tp x delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in {A.shared = removetp x sdelta ; A.linear = removetp x ldelta ; A.ordered = removetp x odelta};; let add_chan env (x,a) delta = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in if A.is_shared env a then {A.shared = (x,a)::sdelta ; A.linear = ldelta ; A.ordered = (x,a)::odelta} else {A.shared = sdelta ; A.linear = (x,a)::ldelta ; A.ordered = (x,a)::odelta};; let update_tp env x t delta = let delta = remove_tp x delta in add_chan env (x,t) delta;; let rec match_ctx env sig_ctx ctx delta sig_len len ext = match sig_ctx, ctx with (sc,st)::sig_ctx', c::ctx' -> begin if not (check_tp c delta) then error ext ("unknown or duplicate variable: " ^ PP.pp_chan c) else if not (eq_mode sc c) then E.error_mode_mismatch (sc, c, ext) else let {A.shared = sdelta ; A.linear = _ldelta ; A.ordered = _odelta} = delta in if checktp c sdelta then begin let t = find_stp c delta ext in if eqtp env st t then match_ctx env sig_ctx' ctx' delta sig_len len ext else error ext ("shared type mismatch: type of " ^ PP.pp_chan c ^ " : " ^ PP.pp_tp_compact env t ^ " does not match type in declaration: " ^ PP.pp_tp_compact env st) end else begin let t = find_ltp c delta ext in if eqtp env st t then match_ctx env sig_ctx' ctx' (remove_tp c delta) sig_len len ext else error ext ("linear type mismatch: type of " ^ PP.pp_chan c ^ " : " ^ PP.pp_tp_compact env t ^ " does not match type in declaration: " ^ PP.pp_tp_compact env st) end end | [], [] -> delta | _, _ -> error ext ("process defined with " ^ string_of_int sig_len ^ " arguments but called with " ^ string_of_int len ^ " arguments");; let join delta = let {A.shared = _sdelta ; A.linear = _ldelta ; A.ordered = odelta} = delta in odelta;; check_exp trace env ctx con A pot P C = ( ) if A |{pot}- P : C * raises ErrorMsg . Error otherwise * assumes ctx ; con |= A valid * ctx ; con |= C valid * ctx ; con |= pot nat * * trace = true means to print some tracing information * * entry point is check_exp ' * * We expand type definitions lazily , based on the direction of * interactions . This is done so tracing ( if enabled ) or error * message are more intelligible . * raises ErrorMsg.Error otherwise * assumes ctx ; con |= A valid * ctx ; con |= C valid * ctx ; con |= pot nat * * trace = true means to print some tracing information * * entry point is check_exp' * * We expand type definitions lazily, based on the direction of * interactions. This is done so tracing (if enabled) or error * message are more intelligible. *) let rec check_exp' trace env delta pot p zc ext mode = begin if trace then print_string ("[" ^ PP.pp_mode mode ^ "] : " ^ PP.pp_exp_prefix p ^ " : " ^ PP.pp_tpj_compact env delta pot zc ^ "\n") else () end ; check_exp trace env delta pot p zc ext mode and check_exp trace env delta pot exp zc ext mode = match exp with A.Fwd(x,y) -> begin let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in let tx = chan_of zc in let () = if not (eq_name x tx) then E.error_unknown_var_right (x,ext) else if not (eq_mode x tx) then E.error_mode_mismatch (x, tx, ext) else if not (eq_mode x y) then error ext ("mode mismatch: " ^ PP.pp_chan x ^ " != " ^ PP.pp_chan y) else () in let c = tp_of zc in if A.is_shared env c then begin if List.length sdelta = 0 then error ext ("shared context empty while offered channel is shared") else if not (checktp y sdelta) then E.error_unknown_var_ctx (y,ext) else let a = find_stp y delta ext in if eqtp env a c then () else error ext ("left type " ^ PP.pp_tp_compact env a ^ " not equal to right type " ^ PP.pp_tp_compact env c) end else begin let (ty, a) = List.hd ldelta in if List.length ldelta <> 1 then error ext ("linear context " ^ PP.pp_lsctx env ldelta ^ " must have only one channel") else if not (eq_name y ty) then E.error_unknown_var_ctx (y,ext) else if not (eq_mode y ty) then E.error_mode_mismatch (y, ty, ext) else if not (eq pot zero) then error ext ("unconsumed potential: " ^ pp_uneq pot zero) else if eqtp env a c then () else error ext ("left type " ^ PP.pp_tp_compact env a ^ " not equal to right type " ^ PP.pp_tp_compact env c) end end | A.Spawn(x,f,xs,q) -> begin match A.lookup_expdec env f with None -> E.error_undeclared (f, ext) | Some (ctx,lpot,(x',a'),mdef) -> let (_x,mx) = x in if not (ge pot lpot) then error ext ("insufficient potential to spawn: " ^ pp_lt pot lpot) else if not (eq_mode x x') then E.error_mode_mismatch (x, x', ext) else if not (eqmode mx mdef) then error ext ("mode mismatch: expected " ^ PP.pp_mode mdef ^ " at declaration, found: " ^ PP.pp_chan x) else if not (mode_spawn mdef mode) then error ext ("cannot spawn at mode " ^ PP.pp_mode mdef ^ " when current mode is " ^ PP.pp_mode mode) else let ctx = join ctx in let delta' = match_ctx env ctx xs delta (List.length ctx) (List.length xs) ext in check_exp' trace env (add_chan env (x,a') delta') (minus pot lpot) q zc ext mode end | A.ExpName(x,f,xs) -> begin match A.lookup_expdec env f with None -> E.error_undeclared (f, ext) | Some (ctx,lpot,(x',a'),mdef) -> let (_x,mx) = x in if not (eq pot lpot) then error ext ("potential mismatch for tail call: " ^ pp_uneq pot lpot) else if not (eq_mode x x') then E.error_mode_mismatch (x, x', ext) else if not (eqmode mx mdef) then error ext ("mode mismatch: expected " ^ PP.pp_mode mdef ^ " at declaration, found: " ^ PP.pp_chan x) else if not (mode_spawn mdef mode) then error ext ("cannot tail call at mode " ^ PP.pp_mode mdef ^ " when current mode is " ^ PP.pp_mode mode) else let (z,c) = zc in if not (eq_name x z) then E.error_unknown_var_right (x,ext) else if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (eqtp env a' c) then error ext ("type mismatch on right, expected: " ^ PP.pp_tp_compact env a' ^ ", found: " ^ PP.pp_tp_compact env c) else let ctx = join ctx in let delta' = match_ctx env ctx xs delta (List.length ctx) (List.length xs) ext in if List.length delta'.linear <> 0 then error ext ("unconsumed channel(s) from linear context: " ^ PP.pp_lsctx env delta'.linear) else () end | A.Lab(x,k,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Plus(choices) -> begin match A.lookup_choice choices k with None -> E.error_label_invalid env (k,c,z,ext) | Some ck -> check_exp' trace env delta pot p (z,ck) ext mode end | A.With _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan z ^ ", expected internal choice, found: " ^ PP.pp_tp_compact env c) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.With(choices) -> begin match A.lookup_choice choices k with None -> E.error_label_invalid env (k,a,x,ext) | Some ak -> check_exp' trace env (update_tp env x ak delta) pot p zc ext mode end | A.Plus _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected external choice, found: " ^ PP.pp_tp_compact env a) end | A.Case(x,branches) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.With(choices) -> check_branchesR trace env delta pot branches z choices ext mode | A.Plus _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan z ^ ", expected external choice, found: " ^ PP.pp_tp_compact env c) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Plus(choices) -> check_branchesL trace env delta x choices pot branches zc ext mode | A.With _ | A.One | A.Tensor _ | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected internal choice, found: " ^ PP.pp_tp_compact env a) end | A.Send(x,w,p) -> begin if not (check_tp w delta) then E.error_unknown_var_ctx (w,ext) else if check_ltp w delta then begin let a' = find_ltp w delta ext in if not (check_tp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Tensor(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (remove_tp w delta) pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env c) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Lolli(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (update_tp env x b (remove_tp w delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env d) end else begin let a' = find_stp w delta ext in if not (check_tp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Tensor(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env delta pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env c) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Lolli(a,b,m) -> let (_w,mw) = w in if not (eqmode m mw) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan w) else if not (eqtp env a a') then error ext ("type mismatch: type of " ^ PP.pp_chan w ^ ", expected: " ^ PP.pp_tp_compact env a ^ ", found: " ^ PP.pp_tp_compact env a') else check_exp' trace env (update_tp env x b delta) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env d) end end | A.Recv(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Lolli(a,b,m) -> let (_y,my) = y in if not (eqmode m my) then error ext ("mode mismatch, expected at lolli: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan y) else if not (mode_recv m mode) then error ext ("cannot receive at mode " ^ PP.pp_mode m ^ " when current mode is " ^ PP.pp_mode mode) else check_exp' trace env (add_chan env (y,a) delta) pot p (z,b) ext mode | A.Plus _ | A.With _ | A.One | A.Tensor _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected lolli, found: " ^ PP.pp_tp_compact env c) let d = find_ltp x delta ext in match d with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Tensor(a,b,m) -> let (_y,my) = y in if not (eqmode m my) then error ext ("mode mismatch, expected at tensor: " ^ PP.pp_mode m ^ ", found: " ^ PP.pp_chan y) else if not (mode_recv m mode) then error ext ("cannot receive at mode " ^ PP.pp_mode m ^ " when current mode is " ^ PP.pp_mode mode) else check_exp' trace env (add_chan env (y,a) (update_tp env x b delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.One | A.Lolli _ | A.PayPot _ | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected tensor, found: " ^ PP.pp_tp_compact env d) end | A.Close(x) -> begin let {A.shared = _sdelta ; A.linear = ldelta ; A.ordered = _odelta} = delta in if List.length ldelta > 0 then error ext ("linear context " ^ PP.pp_lsctx env ldelta ^ " not empty") else if not (checktp x [zc]) then E.error_unknown_var (x,ext) else if not (eq pot zero) then error ext ("unconsumed potential: " ^ pp_uneq pot zero) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else if not (eqtp env c A.One) then error ext ("type mismatch: type of " ^ PP.pp_chan x ^ ", expected: 1, " ^ "found: " ^ PP.pp_tp_compact env c) else () end | A.Wait(x,p) -> begin if not (check_ltp x delta) then E.error_unknown_var (x,ext) else let a = find_ltp x delta ext in if not (eqtp env a A.One) then error ext ("type mismatch: type of " ^ PP.pp_chan x ^ ", expected: 1, " ^ " found: " ^ PP.pp_tp_compact env a) else check_exp' trace env (remove_tp x delta) pot p zc ext mode end | A.Work(pot',p) -> begin if not (ge pot pot') then error ext ("insufficient potential to work: " ^ pp_lt pot pot') else if not (ge pot' zero) then error ext ("potential not positive: " ^ pp_lt pot' zero) else check_exp' trace env delta (minus pot pot') p zc ext mode end | A.Pay(x,epot,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.PayPot(tpot,c') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else if not (ge pot tpot) then error ext ("insufficient potential to pay: " ^ pp_lt pot tpot) else check_exp' trace env delta (minus pot tpot) p (z,c') ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected paypot, found: " ^ PP.pp_tp_compact env c) the type a of x must be let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.GetPot(tpot,a') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else if not (ge pot epot) then error ext ("insufficient potential to pay: " ^ pp_lt pot epot) else check_exp' trace env (update_tp env x a' delta) (minus pot epot) p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected getpot, found: " ^ PP.pp_tp_compact env a) end | A.Get(x,epot,p) -> begin if not (check_ltp x delta) then if not (checktp x [zc]) then E.error_unknown_var (x,ext) the type c of z must be let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else if not (mode_lin x) then E.error_mode_shared_comm (x, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.GetPot(tpot,c') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else check_exp' trace env delta (plus pot epot) p (z,c') ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected getpot, found: " ^ PP.pp_tp_compact env c) let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.PayPot(tpot,a') -> if not (eq epot tpot) then error ext ("potential mismatch: potential in type does not match " ^ "potential in expression: " ^ pp_uneq epot tpot) else check_exp' trace env (update_tp env x a' delta) (plus pot epot) p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.GetPot _ | A.Up _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected paypot, found: " ^ PP.pp_tp_compact env a) end | A.Acquire(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_stp x delta) then E.error_unknown_var_ctx (x,ext) else if not (mode_L y) then error ext ("mode mismatch of acquired channel: expected L, found " ^ PP.pp_chan y) else if not (mode_S x) then error ext ("mode mismatch of acquiring channel: expected S, found " ^ PP.pp_chan x) else let a = find_stp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Up(a') -> check_exp' trace env (add_chan env (y,a') (remove_tp x delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected up, found: " ^ PP.pp_tp_compact env a) end | A.Accept(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (checktp x [zc]) then E.error_unknown_var_right (x,ext) else if not (mode_L y) then error ext ("mode mismatch of accepted channel: expected L, found " ^ PP.pp_chan y) else if not (mode_S x) then error ext ("mode mismatch of accepting channel: expected S, found " ^ PP.pp_chan x) else if not (purelin delta) then error ext ("independence principle violated: " ^ "expected pure linear context, found: " ^ PP.pp_lsctx env delta.linear) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Up(c') -> check_exp' trace env delta pot p (y,c') ext A.Linear | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Down _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected up, found: " ^ PP.pp_tp_compact env c) end | A.Release(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (check_ltp x delta) then E.error_unknown_var_ctx (x,ext) else if not (mode_S y) then error ext ("mode mismatch of released channel: expected S, found " ^ PP.pp_chan y) else if not (mode_L x) then error ext ("mode mismatch of releasing channel: expected L, found " ^ PP.pp_chan x) else let a = find_ltp x delta ext in match a with A.TpName(v) -> check_exp' trace env (update_tp env x (A.expd_tp env v) delta) pot exp zc ext mode | A.Down(a') -> check_exp' trace env (add_chan env (y,a') (remove_tp x delta)) pot p zc ext mode | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected down, found: " ^ PP.pp_tp_compact env a) end | A.Detach(x,y,p) -> begin if check_tp y delta || checktp y [zc] then error ext ("variable " ^ name_of y ^ " is not fresh") else if not (checktp x [zc]) then E.error_unknown_var_right (x,ext) else if not (mode_S y) then error ext ("mode mismatch of detached channel: expected S, found " ^ PP.pp_chan y) else if not (mode_L x) then error ext ("mode mismatch of detaching channel: expected L, found " ^ PP.pp_chan x) else if not (purelin delta) then error ext ("independence principle violated: " ^ "expected empty linear context, found: " ^ PP.pp_lsctx env delta.linear) else let (z,c) = zc in if not (eq_mode x z) then E.error_mode_mismatch (x, z, ext) else match c with A.TpName(v) -> check_exp' trace env delta pot exp (z,A.expd_tp env v) ext mode | A.Down(c') -> check_exp' trace env delta pot p (y,c') ext A.Shared | A.Plus _ | A.With _ | A.Tensor _ | A.Lolli _ | A.One | A.PayPot _ | A.GetPot _ | A.Up _ -> error ext ("invalid type of " ^ PP.pp_chan x ^ ", expected down, found: " ^ PP.pp_tp_compact env c) end | A.Marked(marked_P) -> check_exp trace env delta pot (Mark.data marked_P) zc (Mark.ext marked_P) mode and check_branchesR trace env delta pot branches z choices ext mode = match branches, choices with {lab_exp = (l1,p); exp_extent = bext}::branches', (l2,c)::choices' -> begin if trace then print_string ("| " ^ l1 ^ " => \n") else () ; if l1 = l2 then () else E.error_label_mismatch (l1, l2, bext) ; check_exp' trace env delta pot p (z,c) ext mode ; check_branchesR trace env delta pot branches' z choices' ext mode end | [], [] -> () | {lab_exp = (l,_p); exp_extent = bext}::_branches', [] -> E.error_label_missing_alt (l, bext) | [], (l,_c)::_choices' -> E.error_label_missing_branch (l, ext) and check_branchesL trace env delta x choices pot branches zc ext mode = match choices, branches with (l1,a)::choices', {lab_exp = (l2,p); exp_extent = bext}::branches' -> begin if trace then print_string ("| " ^ l1 ^ " => \n") else () ; if l1 = l2 then () else E.error_label_mismatch (l1, l2, bext) ; check_exp' trace env (update_tp env x a delta) pot p zc ext mode ; check_branchesL trace env delta x choices' pot branches' zc ext mode end | [], [] -> () | [], {lab_exp = (l,_p); exp_extent = bext}::_branches' -> E.error_label_missing_alt (l,bext) | (l,_a)::_choices', [] -> E.error_label_missing_branch (l,ext);; let checkexp = check_exp';; let rec find_tp x sdelta ldelta = match sdelta, ldelta with [], [] -> raise UnknownTypeError | (y,_t1)::sdelta', (z,_t2)::ldelta' -> if eq_name x y then y else if eq_name x z then z else find_tp x sdelta' ldelta' | (y,_t)::sdelta', [] -> if eq_name x y then y else find_tp x sdelta' [] | [], (z,_t)::ldelta' -> if eq_name x z then z else find_tp x [] ldelta';; let rec consistent_mode f sdelta ldelta odelta ext = match odelta with [] -> () | (x,_t)::odelta' -> let y = find_tp x sdelta ldelta in if not (eq_mode x y) then E.error_mode_mismatch (x, y, ext) else consistent_mode f sdelta ldelta odelta' ext;; let rec mode_P_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_P x) then false else mode_P_list delta';; let pure env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_P x) then error ext ("asset process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if List.length sdelta > 0 then error ext ("asset process " ^ f ^ " has non-empty shared context: " ^ PP.pp_lsctx env sdelta) else if not (mode_P_list ldelta) then error ext ("asset process " ^ f ^ " has non-pure linear context: " ^ PP.pp_lsctx env ldelta) else ();; let rec mode_S_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_S x) then false else mode_S_list delta';; let shared env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_S x) then error ext ("shared process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if not (mode_S_list sdelta) then error ext ("shared process " ^ f ^ " has non-shared context: " ^ PP.pp_lsctx env sdelta) else if not (mode_P_list ldelta) then error ext ("shared process " ^ f ^ " has non-pure linear context: " ^ PP.pp_lsctx env ldelta) else ();; let rec mode_lin_list delta = match delta with [] -> true | (x,_t)::delta' -> if not (mode_lin x) then false else mode_lin_list delta';; let transaction env f delta x ext = let {A.shared = sdelta ; A.linear = ldelta ; A.ordered = odelta} = delta in let () = consistent_mode f sdelta ldelta odelta ext in if not (mode_T x) then error ext ("transaction process " ^ f ^ " has offered channel at mode " ^ PP.pp_chan x) else if not (mode_S_list sdelta) then error ext ("transaction process " ^ f ^ " has shared context not at shared mode: " ^ PP.pp_lsctx env sdelta) else if not (mode_lin_list ldelta) then error ext ("transaction process " ^ f ^ " has linear context not at linear mode: " ^ PP.pp_lsctx env ldelta) else ();; structure
f0f956cd89d38a2963a51c58c2c93b49655b0f9d004fd0ec6a2a5f146356e9ba
brunjlar/neural
Layer.hs
{-# OPTIONS_HADDOCK show-extensions #-} # LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE RankNTypes #-} | Module : Numeric . Neural . Layer Description : layer components Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : portable This modules defines special " layer " components and convenience functions for the creation of such layers . Module : Numeric.Neural.Layer Description : layer components Copyright : (c) Lars Brünjes, 2016 License : MIT Maintainer : Stability : experimental Portability : portable This modules defines special "layer" components and convenience functions for the creation of such layers. -} module Numeric.Neural.Layer ( Layer , linearLayer , layer , tanhLayer , tanhLayer' , logisticLayer , reLULayer , softmax , softmaxLayer ) where import Control.Category import Data.FixedSize import Data.Proxy import Data.Utils.Analytic import Data.Utils.Random import GHC.TypeLits import GHC.TypeLits.Witnesses import Numeric.Neural.Model import Prelude hiding (id, (.)) | A @'Layer ' i o@ is a component that maps a @'Vector'@ of length @i@ to a @'Vector'@ of length @o@. -- type Layer i o = Component (Vector i) (Vector o) linearLayer' :: forall i o s. Analytic s => ParamFun s (Matrix o (i + 1)) (Vector i s) (Vector o s) linearLayer' = ParamFun $ \xs ws -> ws <%%> cons 1 xs -- | Creates a /linear/ @'Layer'@, i.e. a layer that multiplies the input with a weight @'Matrix'@ and adds a bias to get the output. -- Random initialization follows the recommendation from chapter 3 of the online book < / Neural Networks and Deep Learning > by . linearLayer :: forall i o. (KnownNat i, KnownNat o) => Layer i o linearLayer = withNatOp (%+) p (Proxy :: Proxy 1) Component { weights = pure 0 , compute = linearLayer' , initR = sequenceA $ generate r } where p = Proxy :: Proxy i s = 1 / sqrt (fromIntegral $ natVal p) r (_, 0) = boxMuller r (_, _) = boxMuller' 0 s -- | Creates a @'Layer'@ as a combination of a linear layer and a non-linear activation function. -- layer :: (KnownNat i, KnownNat o) => Diff' -> Layer i o layer f = cArr (diff f) . linearLayer -- | This is a simple @'Layer'@, specialized to @'tanh'@-activation. Output values are all in the interval [-1,1]. -- tanhLayer :: (KnownNat i, KnownNat o) => Layer i o tanhLayer = layer tanh -- | This is a simple @'Layer'@, specialized to a modified @'tanh'@-activation, following the suggestion from < -98b.pdf Efficient BackProp > by LeCun et al . , where -- output values are all in the interval [-1.7159,1.7159]. tanhLayer' :: (KnownNat i, KnownNat o) => Layer i o tanhLayer' = layer $ \x -> 1.7159 * tanh (2 * x / 3) | This is a simple @'Layer'@ , specialized to the logistic function as activation . Output values are all in the interval [ 0,1 ] . -- logisticLayer :: (KnownNat i, KnownNat o) => Layer i o logisticLayer = layer $ \x -> 1 / (1 + exp (- x)) -- | This is a simple @'Layer'@, specialized to the /rectified linear unit/ activation function. -- Output values are all non-negative. -- reLULayer :: (KnownNat i, KnownNat o) => Layer i o reLULayer = layer $ \x -> max 0 x | The @'softmax'@ function normalizes a vector , so that all entries are in [ 0,1 ] with sum 1 . -- This means the output entries can be interpreted as probabilities. -- softmax :: (Floating a, Functor f, Foldable f) => f a -> f a softmax xs = let xs' = exp <$> xs s = sum xs' in (/ s) <$> xs' | A @'softmaxLayer'@ is a deterministic layer that performs a @'softmax'@ -- step. softmaxLayer :: Layer i i softmaxLayer = cArr $ Diff softmax
null
https://raw.githubusercontent.com/brunjlar/neural/1211d1a2bed14b4036f48c500f945fea027cd3b9/src/Numeric/Neural/Layer.hs
haskell
# OPTIONS_HADDOCK show-extensions # # LANGUAGE RankNTypes # | Creates a /linear/ @'Layer'@, i.e. a layer that multiplies the input with a weight @'Matrix'@ and adds a bias to get the output. | Creates a @'Layer'@ as a combination of a linear layer and a non-linear activation function. | This is a simple @'Layer'@, specialized to @'tanh'@-activation. Output values are all in the interval [-1,1]. | This is a simple @'Layer'@, specialized to a modified @'tanh'@-activation, following the suggestion from output values are all in the interval [-1.7159,1.7159]. | This is a simple @'Layer'@, specialized to the /rectified linear unit/ activation function. Output values are all non-negative. This means the output entries can be interpreted as probabilities. step.
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # # LANGUAGE ScopedTypeVariables # | Module : Numeric . Neural . Layer Description : layer components Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : portable This modules defines special " layer " components and convenience functions for the creation of such layers . Module : Numeric.Neural.Layer Description : layer components Copyright : (c) Lars Brünjes, 2016 License : MIT Maintainer : Stability : experimental Portability : portable This modules defines special "layer" components and convenience functions for the creation of such layers. -} module Numeric.Neural.Layer ( Layer , linearLayer , layer , tanhLayer , tanhLayer' , logisticLayer , reLULayer , softmax , softmaxLayer ) where import Control.Category import Data.FixedSize import Data.Proxy import Data.Utils.Analytic import Data.Utils.Random import GHC.TypeLits import GHC.TypeLits.Witnesses import Numeric.Neural.Model import Prelude hiding (id, (.)) | A @'Layer ' i o@ is a component that maps a @'Vector'@ of length @i@ to a @'Vector'@ of length @o@. type Layer i o = Component (Vector i) (Vector o) linearLayer' :: forall i o s. Analytic s => ParamFun s (Matrix o (i + 1)) (Vector i s) (Vector o s) linearLayer' = ParamFun $ \xs ws -> ws <%%> cons 1 xs Random initialization follows the recommendation from chapter 3 of the online book < / Neural Networks and Deep Learning > by . linearLayer :: forall i o. (KnownNat i, KnownNat o) => Layer i o linearLayer = withNatOp (%+) p (Proxy :: Proxy 1) Component { weights = pure 0 , compute = linearLayer' , initR = sequenceA $ generate r } where p = Proxy :: Proxy i s = 1 / sqrt (fromIntegral $ natVal p) r (_, 0) = boxMuller r (_, _) = boxMuller' 0 s layer :: (KnownNat i, KnownNat o) => Diff' -> Layer i o layer f = cArr (diff f) . linearLayer tanhLayer :: (KnownNat i, KnownNat o) => Layer i o tanhLayer = layer tanh < -98b.pdf Efficient BackProp > by LeCun et al . , where tanhLayer' :: (KnownNat i, KnownNat o) => Layer i o tanhLayer' = layer $ \x -> 1.7159 * tanh (2 * x / 3) | This is a simple @'Layer'@ , specialized to the logistic function as activation . Output values are all in the interval [ 0,1 ] . logisticLayer :: (KnownNat i, KnownNat o) => Layer i o logisticLayer = layer $ \x -> 1 / (1 + exp (- x)) reLULayer :: (KnownNat i, KnownNat o) => Layer i o reLULayer = layer $ \x -> max 0 x | The @'softmax'@ function normalizes a vector , so that all entries are in [ 0,1 ] with sum 1 . softmax :: (Floating a, Functor f, Foldable f) => f a -> f a softmax xs = let xs' = exp <$> xs s = sum xs' in (/ s) <$> xs' | A @'softmaxLayer'@ is a deterministic layer that performs a @'softmax'@ softmaxLayer :: Layer i i softmaxLayer = cArr $ Diff softmax
ccb5be6ac79ff0824fa1e6868c7a153bc81f594cb4d2ca433cb357826b53ebb8
HumbleUI/HumbleUI
7guis_converter.clj
(ns examples.7guis-converter (:require [clojure.string :as str] [io.github.humbleui.core :as core] [io.github.humbleui.ui :as ui])) (def *celsius (atom {:text "5" :from 1 :to 1})) (def *fahrenheit (atom {:text "41"})) (def ^:dynamic *editing* false) (add-watch *celsius ::update (fn [_ _ old new] (when-not *editing* (when (not= (:text old) (:text new)) (binding [*editing* true] (if-some [c (parse-long (str/trim (:text new)))] (let [f (-> c (* 9) (quot 5) (+ 32) str)] (swap! *fahrenheit assoc :text f :from (count f) :to (count f))) (swap! *fahrenheit assoc :text "" :from 0 :to 0))))))) (add-watch *fahrenheit ::update (fn [_ _ old new] (when-not *editing* (when (not= (:text old) (:text new)) (binding [*editing* true] (if-some [f (parse-long (str/trim (:text new)))] (let [c (-> f (- 32) (* 5) (quot 9) str)] (swap! *celsius assoc :text c :from (count c) :to (count c))) (swap! *celsius assoc :text "" :from 0 :to 0))))))) C = ( F - 32 ) * ( 5/9 ) F = C * ( 9/5 ) + 32 (def ui (ui/focus-controller (ui/center (ui/with-context {:hui.text-field/padding-top 10 :hui.text-field/padding-bottom 10 :hui.text-field/padding-left 5 :hui.text-field/padding-right 5} (ui/row (ui/width 50 (ui/text-field {:focused (core/now)} *celsius)) (ui/gap 5 0) (ui/valign 0.5 (ui/label "Celsius = ")) (ui/width 50 (ui/text-field *fahrenheit)) (ui/gap 5 0) (ui/valign 0.5 (ui/label "Fahrenheit")))))))
null
https://raw.githubusercontent.com/HumbleUI/HumbleUI/b0a596028dac8ebebf178a378e88d1c9f971e9dd/dev/examples/7guis_converter.clj
clojure
(ns examples.7guis-converter (:require [clojure.string :as str] [io.github.humbleui.core :as core] [io.github.humbleui.ui :as ui])) (def *celsius (atom {:text "5" :from 1 :to 1})) (def *fahrenheit (atom {:text "41"})) (def ^:dynamic *editing* false) (add-watch *celsius ::update (fn [_ _ old new] (when-not *editing* (when (not= (:text old) (:text new)) (binding [*editing* true] (if-some [c (parse-long (str/trim (:text new)))] (let [f (-> c (* 9) (quot 5) (+ 32) str)] (swap! *fahrenheit assoc :text f :from (count f) :to (count f))) (swap! *fahrenheit assoc :text "" :from 0 :to 0))))))) (add-watch *fahrenheit ::update (fn [_ _ old new] (when-not *editing* (when (not= (:text old) (:text new)) (binding [*editing* true] (if-some [f (parse-long (str/trim (:text new)))] (let [c (-> f (- 32) (* 5) (quot 9) str)] (swap! *celsius assoc :text c :from (count c) :to (count c))) (swap! *celsius assoc :text "" :from 0 :to 0))))))) C = ( F - 32 ) * ( 5/9 ) F = C * ( 9/5 ) + 32 (def ui (ui/focus-controller (ui/center (ui/with-context {:hui.text-field/padding-top 10 :hui.text-field/padding-bottom 10 :hui.text-field/padding-left 5 :hui.text-field/padding-right 5} (ui/row (ui/width 50 (ui/text-field {:focused (core/now)} *celsius)) (ui/gap 5 0) (ui/valign 0.5 (ui/label "Celsius = ")) (ui/width 50 (ui/text-field *fahrenheit)) (ui/gap 5 0) (ui/valign 0.5 (ui/label "Fahrenheit")))))))
2db55e17c2e468325ba4174747395d4f64ed9f2bf4286e7c73a8a4482d7922a4
acl2/acl2
defevaluator-theorems-tests.lisp
; Tests of defevaluator-theorems. ; Copyright ( C ) 2023 Kestrel Institute ; License : A 3 - clause BSD license . See the file books/3BSD - mod.txt . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "defevaluator-plus") (include-book "defevaluator-theorems") (defevaluator+ myev binary-*) (defevaluator-theorems myev myev-list)
null
https://raw.githubusercontent.com/acl2/acl2/2790a294db676f428d72175afcfa5dfff2b05979/books/kestrel/evaluators/defevaluator-theorems-tests.lisp
lisp
Tests of defevaluator-theorems.
Copyright ( C ) 2023 Kestrel Institute License : A 3 - clause BSD license . See the file books/3BSD - mod.txt . Author : ( ) (in-package "ACL2") (include-book "defevaluator-plus") (include-book "defevaluator-theorems") (defevaluator+ myev binary-*) (defevaluator-theorems myev myev-list)
42714ae0fae5b8519b422f285671b7119ddc6c516ed930be771e7bcde3298f99
Kah0ona/re-datagrid
core.cljs
(ns re-datagrid.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-datagrid.events] [re-datagrid.subs] [re-datagrid.schema] [re-datagrid.views] [re-datagrid.config]))
null
https://raw.githubusercontent.com/Kah0ona/re-datagrid/0dc1407a7da98adfec865cb02bbeecd950b18c1e/src/cljs/re_datagrid/core.cljs
clojure
(ns re-datagrid.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [re-datagrid.events] [re-datagrid.subs] [re-datagrid.schema] [re-datagrid.views] [re-datagrid.config]))
95ac1dcc82b4738524ff06cc3669034250c160ba148aa4a990f9a93915b2227b
lpw25/ocaml-typed-effects
bigrecmod.ml
module type Big = sig type a val f000 : a val f001 : a val f002 : a val f003 : a val f004 : a val f005 : a val f006 : a val f007 : a val f008 : a val f009 : a val f010 : a val f011 : a val f012 : a val f013 : a val f014 : a val f015 : a val f016 : a val f017 : a val f018 : a val f019 : a val f020 : a val f021 : a val f022 : a val f023 : a val f024 : a val f025 : a val f026 : a val f027 : a val f028 : a val f029 : a val f030 : a val f031 : a val f032 : a val f033 : a val f034 : a val f035 : a val f036 : a val f037 : a val f038 : a val f039 : a val f040 : a val f041 : a val f042 : a val f043 : a val f044 : a val f045 : a val f046 : a val f047 : a val f048 : a val f049 : a val f050 : a val f051 : a val f052 : a val f053 : a val f054 : a val f055 : a val f056 : a val f057 : a val f058 : a val f059 : a val f060 : a val f061 : a val f062 : a val f063 : a val f064 : a val f065 : a val f066 : a val f067 : a val f068 : a val f069 : a val f070 : a val f071 : a val f072 : a val f073 : a val f074 : a val f075 : a val f076 : a val f077 : a val f078 : a val f079 : a val f080 : a val f081 : a val f082 : a val f083 : a val f084 : a val f085 : a val f086 : a val f087 : a val f088 : a val f089 : a val f090 : a val f091 : a val f092 : a val f093 : a val f094 : a val f095 : a val f096 : a val f097 : a val f098 : a val f099 : a val f100 : a val f101 : a val f102 : a val f103 : a val f104 : a val f105 : a val f106 : a val f107 : a val f108 : a val f109 : a val f110 : a val f111 : a val f112 : a val f113 : a val f114 : a val f115 : a val f116 : a val f117 : a val f118 : a val f119 : a val f120 : a val f121 : a val f122 : a val f123 : a val f124 : a val f125 : a val f126 : a val f127 : a val f128 : a val f129 : a val f130 : a val f131 : a val f132 : a val f133 : a val f134 : a val f135 : a val f136 : a val f137 : a val f138 : a val f139 : a val f140 : a val f141 : a val f142 : a val f143 : a val f144 : a val f145 : a val f146 : a val f147 : a val f148 : a val f149 : a val f150 : a val f151 : a val f152 : a val f153 : a val f154 : a val f155 : a val f156 : a val f157 : a val f158 : a val f159 : a val f160 : a val f161 : a val f162 : a val f163 : a val f164 : a val f165 : a val f166 : a val f167 : a val f168 : a val f169 : a val f170 : a val f171 : a val f172 : a val f173 : a val f174 : a val f175 : a val f176 : a val f177 : a val f178 : a val f179 : a val f180 : a val f181 : a val f182 : a val f183 : a val f184 : a val f185 : a val f186 : a val f187 : a val f188 : a val f189 : a val f190 : a val f191 : a val f192 : a val f193 : a val f194 : a val f195 : a val f196 : a val f197 : a val f198 : a val f199 : a val f200 : a val f201 : a val f202 : a val f203 : a val f204 : a val f205 : a val f206 : a val f207 : a val f208 : a val f209 : a val f210 : a val f211 : a val f212 : a val f213 : a val f214 : a val f215 : a val f216 : a val f217 : a val f218 : a val f219 : a val f220 : a val f221 : a val f222 : a val f223 : a val f224 : a val f225 : a val f226 : a val f227 : a val f228 : a val f229 : a val f230 : a val f231 : a val f232 : a val f233 : a val f234 : a val f235 : a val f236 : a val f237 : a val f238 : a val f239 : a val f240 : a val f241 : a val f242 : a val f243 : a val f244 : a val f245 : a val f246 : a val f247 : a val f248 : a val f249 : a val f250 : a val f251 : a val f252 : a val f253 : a val f254 : a val f255 : a val f256 : a val f257 : a val f258 : a val f259 : a val f260 : a val f261 : a val f262 : a val f263 : a val f264 : a val f265 : a val f266 : a val f267 : a val f268 : a val f269 : a val f270 : a val f271 : a val f272 : a val f273 : a val f274 : a val f275 : a val f276 : a val f277 : a val f278 : a val f279 : a val f280 : a val f281 : a val f282 : a val f283 : a val f284 : a val f285 : a val f286 : a val f287 : a val f288 : a val f289 : a val f290 : a val f291 : a val f292 : a val f293 : a val f294 : a val f295 : a val f296 : a val f297 : a val f298 : a val f299 : a val f300 : a end let p = ref 42 module Big = struct type a = [`Foo of int ref] let a : a = `Foo p let f000 = a let f001 = a let f002 = a let f003 = a let f004 = a let f005 = a let f006 = a let f007 = a let f008 = a let f009 = a let f010 = a let f011 = a let f012 = a let f013 = a let f014 = a let f015 = a let f016 = a let f017 = a let f018 = a let f019 = a let f020 = a let f021 = a let f022 = a let f023 = a let f024 = a let f025 = a let f026 = a let f027 = a let f028 = a let f029 = a let f030 = a let f031 = a let f032 = a let f033 = a let f034 = a let f035 = a let f036 = a let f037 = a let f038 = a let f039 = a let f040 = a let f041 = a let f042 = a let f043 = a let f044 = a let f045 = a let f046 = a let f047 = a let f048 = a let f049 = a let f050 = a let f051 = a let f052 = a let f053 = a let f054 = a let f055 = a let f056 = a let f057 = a let f058 = a let f059 = a let f060 = a let f061 = a let f062 = a let f063 = a let f064 = a let f065 = a let f066 = a let f067 = a let f068 = a let f069 = a let f070 = a let f071 = a let f072 = a let f073 = a let f074 = a let f075 = a let f076 = a let f077 = a let f078 = a let f079 = a let f080 = a let f081 = a let f082 = a let f083 = a let f084 = a let f085 = a let f086 = a let f087 = a let f088 = a let f089 = a let f090 = a let f091 = a let f092 = a let f093 = a let f094 = a let f095 = a let f096 = a let f097 = a let f098 = a let f099 = a let f100 = a let f101 = a let f102 = a let f103 = a let f104 = a let f105 = a let f106 = a let f107 = a let f108 = a let f109 = a let f110 = a let f111 = a let f112 = a let f113 = a let f114 = a let f115 = a let f116 = a let f117 = a let f118 = a let f119 = a let f120 = a let f121 = a let f122 = a let f123 = a let f124 = a let f125 = a let f126 = a let f127 = a let f128 = a let f129 = a let f130 = a let f131 = a let f132 = a let f133 = a let f134 = a let f135 = a let f136 = a let f137 = a let f138 = a let f139 = a let f140 = a let f141 = a let f142 = a let f143 = a let f144 = a let f145 = a let f146 = a let f147 = a let f148 = a let f149 = a let f150 = a let f151 = a let f152 = a let f153 = a let f154 = a let f155 = a let f156 = a let f157 = a let f158 = a let f159 = a let f160 = a let f161 = a let f162 = a let f163 = a let f164 = a let f165 = a let f166 = a let f167 = a let f168 = a let f169 = a let f170 = a let f171 = a let f172 = a let f173 = a let f174 = a let f175 = a let f176 = a let f177 = a let f178 = a let f179 = a let f180 = a let f181 = a let f182 = a let f183 = a let f184 = a let f185 = a let f186 = a let f187 = a let f188 = a let f189 = a let f190 = a let f191 = a let f192 = a let f193 = a let f194 = a let f195 = a let f196 = a let f197 = a let f198 = a let f199 = a let f200 = a let f201 = a let f202 = a let f203 = a let f204 = a let f205 = a let f206 = a let f207 = a let f208 = a let f209 = a let f210 = a let f211 = a let f212 = a let f213 = a let f214 = a let f215 = a let f216 = a let f217 = a let f218 = a let f219 = a let f220 = a let f221 = a let f222 = a let f223 = a let f224 = a let f225 = a let f226 = a let f227 = a let f228 = a let f229 = a let f230 = a let f231 = a let f232 = a let f233 = a let f234 = a let f235 = a let f236 = a let f237 = a let f238 = a let f239 = a let f240 = a let f241 = a let f242 = a let f243 = a let f244 = a let f245 = a let f246 = a let f247 = a let f248 = a let f249 = a let f250 = a let f251 = a let f252 = a let f253 = a let f254 = a let f255 = a let f256 = a let f257 = a let f258 = a let f259 = a let f260 = a let f261 = a let f262 = a let f263 = a let f264 = a let f265 = a let f266 = a let f267 = a let f268 = a let f269 = a let f270 = a let f271 = a let f272 = a let f273 = a let f274 = a let f275 = a let f276 = a let f277 = a let f278 = a let f279 = a let f280 = a let f281 = a let f282 = a let f283 = a let f284 = a let f285 = a let f286 = a let f287 = a let f288 = a let f289 = a let f290 = a let f291 = a let f292 = a let f293 = a let f294 = a let f295 = a let f296 = a let f297 = a let f298 = a let f299 = a let f300 = a end let () = let p' = match Big.f132 with `Foo p -> p in Printf.printf "%b %b %b %b\n%!" (Obj.is_shared (Obj.repr (module Big : Big))) (Obj.is_shared (Obj.repr Big.f000)) (Obj.is_shared (Obj.repr p)) (p == p') let () = Gc.full_major () module type T = sig val f : unit -> int ref val g : unit -> int ref end module type Big' = Big with type a = unit -> int ref module F (X : sig val p : int ref end) = struct module rec M : T = struct let f () = Big'.f000 () let g () = N.g () end and Big' : Big' = struct type a = unit -> int ref let a () = N.f () let f000 () = M.g () let f001 () = a () let f002 () = a () let f003 () = a () let f004 () = a () let f005 () = a () let f006 () = a () let f007 () = a () let f008 () = a () let f009 () = a () let f010 () = a () let f011 () = a () let f012 () = a () let f013 () = a () let f014 () = a () let f015 () = a () let f016 () = a () let f017 () = a () let f018 () = a () let f019 () = a () let f020 () = a () let f021 () = a () let f022 () = a () let f023 () = a () let f024 () = a () let f025 () = a () let f026 () = a () let f027 () = a () let f028 () = a () let f029 () = a () let f030 () = a () let f031 () = a () let f032 () = a () let f033 () = a () let f034 () = a () let f035 () = a () let f036 () = a () let f037 () = a () let f038 () = a () let f039 () = a () let f040 () = a () let f041 () = a () let f042 () = a () let f043 () = a () let f044 () = a () let f045 () = a () let f046 () = a () let f047 () = a () let f048 () = a () let f049 () = a () let f050 () = a () let f051 () = a () let f052 () = a () let f053 () = a () let f054 () = a () let f055 () = a () let f056 () = a () let f057 () = a () let f058 () = a () let f059 () = a () let f060 () = a () let f061 () = a () let f062 () = a () let f063 () = a () let f064 () = a () let f065 () = a () let f066 () = a () let f067 () = a () let f068 () = a () let f069 () = a () let f070 () = a () let f071 () = a () let f072 () = a () let f073 () = a () let f074 () = a () let f075 () = a () let f076 () = a () let f077 () = a () let f078 () = a () let f079 () = a () let f080 () = a () let f081 () = a () let f082 () = a () let f083 () = a () let f084 () = a () let f085 () = a () let f086 () = a () let f087 () = a () let f088 () = a () let f089 () = a () let f090 () = a () let f091 () = a () let f092 () = a () let f093 () = a () let f094 () = a () let f095 () = a () let f096 () = a () let f097 () = a () let f098 () = a () let f099 () = a () let f100 () = a () let f101 () = a () let f102 () = a () let f103 () = a () let f104 () = a () let f105 () = a () let f106 () = a () let f107 () = a () let f108 () = a () let f109 () = a () let f110 () = a () let f111 () = a () let f112 () = a () let f113 () = a () let f114 () = a () let f115 () = a () let f116 () = a () let f117 () = a () let f118 () = a () let f119 () = a () let f120 () = a () let f121 () = a () let f122 () = a () let f123 () = a () let f124 () = a () let f125 () = a () let f126 () = a () let f127 () = a () let f128 () = a () let f129 () = a () let f130 () = a () let f131 () = a () let f132 () = a () let f133 () = a () let f134 () = a () let f135 () = a () let f136 () = a () let f137 () = a () let f138 () = a () let f139 () = a () let f140 () = a () let f141 () = a () let f142 () = a () let f143 () = a () let f144 () = a () let f145 () = a () let f146 () = a () let f147 () = a () let f148 () = a () let f149 () = a () let f150 () = a () let f151 () = a () let f152 () = a () let f153 () = a () let f154 () = a () let f155 () = a () let f156 () = a () let f157 () = a () let f158 () = a () let f159 () = a () let f160 () = a () let f161 () = a () let f162 () = a () let f163 () = a () let f164 () = a () let f165 () = a () let f166 () = a () let f167 () = a () let f168 () = a () let f169 () = a () let f170 () = a () let f171 () = a () let f172 () = a () let f173 () = a () let f174 () = a () let f175 () = a () let f176 () = a () let f177 () = a () let f178 () = a () let f179 () = a () let f180 () = a () let f181 () = a () let f182 () = a () let f183 () = a () let f184 () = a () let f185 () = a () let f186 () = a () let f187 () = a () let f188 () = a () let f189 () = a () let f190 () = a () let f191 () = a () let f192 () = a () let f193 () = a () let f194 () = a () let f195 () = a () let f196 () = a () let f197 () = a () let f198 () = a () let f199 () = a () let f200 () = a () let f201 () = a () let f202 () = a () let f203 () = a () let f204 () = a () let f205 () = a () let f206 () = a () let f207 () = a () let f208 () = a () let f209 () = a () let f210 () = a () let f211 () = a () let f212 () = a () let f213 () = a () let f214 () = a () let f215 () = a () let f216 () = a () let f217 () = a () let f218 () = a () let f219 () = a () let f220 () = a () let f221 () = a () let f222 () = a () let f223 () = a () let f224 () = a () let f225 () = a () let f226 () = a () let f227 () = a () let f228 () = a () let f229 () = a () let f230 () = a () let f231 () = a () let f232 () = a () let f233 () = a () let f234 () = a () let f235 () = a () let f236 () = a () let f237 () = a () let f238 () = a () let f239 () = a () let f240 () = a () let f241 () = a () let f242 () = a () let f243 () = a () let f244 () = a () let f245 () = a () let f246 () = a () let f247 () = a () let f248 () = a () let f249 () = a () let f250 () = a () let f251 () = a () let f252 () = a () let f253 () = a () let f254 () = a () let f255 () = a () let f256 () = a () let f257 () = a () let f258 () = a () let f259 () = a () let f260 () = a () let f261 () = a () let f262 () = a () let f263 () = a () let f264 () = a () let f265 () = a () let f266 () = a () let f267 () = a () let f268 () = a () let f269 () = a () let f270 () = a () let f271 () = a () let f272 () = a () let f273 () = a () let f274 () = a () let f275 () = a () let f276 () = a () let f277 () = a () let f278 () = a () let f279 () = a () let f280 () = a () let f281 () = a () let f282 () = a () let f283 () = a () let f284 () = a () let f285 () = a () let f286 () = a () let f287 () = a () let f288 () = a () let f289 () = a () let f290 () = a () let f291 () = a () let f292 () = a () let f293 () = a () let f294 () = a () let f295 () = a () let f296 () = a () let f297 () = a () let f298 () = a () let f299 () = a () let f300 () = a () end and N : T = struct let f () = Big'.f000 () let g () = X.p end end let () = let module FX = F (struct let p = p end) in let open FX in let p' = M.f () in Printf.printf "%b %b %b %b %b %b %b %b %b\n%!" (Obj.is_shared (Obj.repr (module Big' : Big'))) (Obj.is_shared (Obj.repr Big.f123)) (Obj.is_shared (Obj.repr (module M : T))) (Obj.is_shared (Obj.repr M.f)) (Obj.is_shared (Obj.repr M.g)) (Obj.is_shared (Obj.repr (module N : T))) (Obj.is_shared (Obj.repr N.f)) (Obj.is_shared (Obj.repr N.g)) (p == p')
null
https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/testsuite/tests/promotion/bigrecmod.ml
ocaml
module type Big = sig type a val f000 : a val f001 : a val f002 : a val f003 : a val f004 : a val f005 : a val f006 : a val f007 : a val f008 : a val f009 : a val f010 : a val f011 : a val f012 : a val f013 : a val f014 : a val f015 : a val f016 : a val f017 : a val f018 : a val f019 : a val f020 : a val f021 : a val f022 : a val f023 : a val f024 : a val f025 : a val f026 : a val f027 : a val f028 : a val f029 : a val f030 : a val f031 : a val f032 : a val f033 : a val f034 : a val f035 : a val f036 : a val f037 : a val f038 : a val f039 : a val f040 : a val f041 : a val f042 : a val f043 : a val f044 : a val f045 : a val f046 : a val f047 : a val f048 : a val f049 : a val f050 : a val f051 : a val f052 : a val f053 : a val f054 : a val f055 : a val f056 : a val f057 : a val f058 : a val f059 : a val f060 : a val f061 : a val f062 : a val f063 : a val f064 : a val f065 : a val f066 : a val f067 : a val f068 : a val f069 : a val f070 : a val f071 : a val f072 : a val f073 : a val f074 : a val f075 : a val f076 : a val f077 : a val f078 : a val f079 : a val f080 : a val f081 : a val f082 : a val f083 : a val f084 : a val f085 : a val f086 : a val f087 : a val f088 : a val f089 : a val f090 : a val f091 : a val f092 : a val f093 : a val f094 : a val f095 : a val f096 : a val f097 : a val f098 : a val f099 : a val f100 : a val f101 : a val f102 : a val f103 : a val f104 : a val f105 : a val f106 : a val f107 : a val f108 : a val f109 : a val f110 : a val f111 : a val f112 : a val f113 : a val f114 : a val f115 : a val f116 : a val f117 : a val f118 : a val f119 : a val f120 : a val f121 : a val f122 : a val f123 : a val f124 : a val f125 : a val f126 : a val f127 : a val f128 : a val f129 : a val f130 : a val f131 : a val f132 : a val f133 : a val f134 : a val f135 : a val f136 : a val f137 : a val f138 : a val f139 : a val f140 : a val f141 : a val f142 : a val f143 : a val f144 : a val f145 : a val f146 : a val f147 : a val f148 : a val f149 : a val f150 : a val f151 : a val f152 : a val f153 : a val f154 : a val f155 : a val f156 : a val f157 : a val f158 : a val f159 : a val f160 : a val f161 : a val f162 : a val f163 : a val f164 : a val f165 : a val f166 : a val f167 : a val f168 : a val f169 : a val f170 : a val f171 : a val f172 : a val f173 : a val f174 : a val f175 : a val f176 : a val f177 : a val f178 : a val f179 : a val f180 : a val f181 : a val f182 : a val f183 : a val f184 : a val f185 : a val f186 : a val f187 : a val f188 : a val f189 : a val f190 : a val f191 : a val f192 : a val f193 : a val f194 : a val f195 : a val f196 : a val f197 : a val f198 : a val f199 : a val f200 : a val f201 : a val f202 : a val f203 : a val f204 : a val f205 : a val f206 : a val f207 : a val f208 : a val f209 : a val f210 : a val f211 : a val f212 : a val f213 : a val f214 : a val f215 : a val f216 : a val f217 : a val f218 : a val f219 : a val f220 : a val f221 : a val f222 : a val f223 : a val f224 : a val f225 : a val f226 : a val f227 : a val f228 : a val f229 : a val f230 : a val f231 : a val f232 : a val f233 : a val f234 : a val f235 : a val f236 : a val f237 : a val f238 : a val f239 : a val f240 : a val f241 : a val f242 : a val f243 : a val f244 : a val f245 : a val f246 : a val f247 : a val f248 : a val f249 : a val f250 : a val f251 : a val f252 : a val f253 : a val f254 : a val f255 : a val f256 : a val f257 : a val f258 : a val f259 : a val f260 : a val f261 : a val f262 : a val f263 : a val f264 : a val f265 : a val f266 : a val f267 : a val f268 : a val f269 : a val f270 : a val f271 : a val f272 : a val f273 : a val f274 : a val f275 : a val f276 : a val f277 : a val f278 : a val f279 : a val f280 : a val f281 : a val f282 : a val f283 : a val f284 : a val f285 : a val f286 : a val f287 : a val f288 : a val f289 : a val f290 : a val f291 : a val f292 : a val f293 : a val f294 : a val f295 : a val f296 : a val f297 : a val f298 : a val f299 : a val f300 : a end let p = ref 42 module Big = struct type a = [`Foo of int ref] let a : a = `Foo p let f000 = a let f001 = a let f002 = a let f003 = a let f004 = a let f005 = a let f006 = a let f007 = a let f008 = a let f009 = a let f010 = a let f011 = a let f012 = a let f013 = a let f014 = a let f015 = a let f016 = a let f017 = a let f018 = a let f019 = a let f020 = a let f021 = a let f022 = a let f023 = a let f024 = a let f025 = a let f026 = a let f027 = a let f028 = a let f029 = a let f030 = a let f031 = a let f032 = a let f033 = a let f034 = a let f035 = a let f036 = a let f037 = a let f038 = a let f039 = a let f040 = a let f041 = a let f042 = a let f043 = a let f044 = a let f045 = a let f046 = a let f047 = a let f048 = a let f049 = a let f050 = a let f051 = a let f052 = a let f053 = a let f054 = a let f055 = a let f056 = a let f057 = a let f058 = a let f059 = a let f060 = a let f061 = a let f062 = a let f063 = a let f064 = a let f065 = a let f066 = a let f067 = a let f068 = a let f069 = a let f070 = a let f071 = a let f072 = a let f073 = a let f074 = a let f075 = a let f076 = a let f077 = a let f078 = a let f079 = a let f080 = a let f081 = a let f082 = a let f083 = a let f084 = a let f085 = a let f086 = a let f087 = a let f088 = a let f089 = a let f090 = a let f091 = a let f092 = a let f093 = a let f094 = a let f095 = a let f096 = a let f097 = a let f098 = a let f099 = a let f100 = a let f101 = a let f102 = a let f103 = a let f104 = a let f105 = a let f106 = a let f107 = a let f108 = a let f109 = a let f110 = a let f111 = a let f112 = a let f113 = a let f114 = a let f115 = a let f116 = a let f117 = a let f118 = a let f119 = a let f120 = a let f121 = a let f122 = a let f123 = a let f124 = a let f125 = a let f126 = a let f127 = a let f128 = a let f129 = a let f130 = a let f131 = a let f132 = a let f133 = a let f134 = a let f135 = a let f136 = a let f137 = a let f138 = a let f139 = a let f140 = a let f141 = a let f142 = a let f143 = a let f144 = a let f145 = a let f146 = a let f147 = a let f148 = a let f149 = a let f150 = a let f151 = a let f152 = a let f153 = a let f154 = a let f155 = a let f156 = a let f157 = a let f158 = a let f159 = a let f160 = a let f161 = a let f162 = a let f163 = a let f164 = a let f165 = a let f166 = a let f167 = a let f168 = a let f169 = a let f170 = a let f171 = a let f172 = a let f173 = a let f174 = a let f175 = a let f176 = a let f177 = a let f178 = a let f179 = a let f180 = a let f181 = a let f182 = a let f183 = a let f184 = a let f185 = a let f186 = a let f187 = a let f188 = a let f189 = a let f190 = a let f191 = a let f192 = a let f193 = a let f194 = a let f195 = a let f196 = a let f197 = a let f198 = a let f199 = a let f200 = a let f201 = a let f202 = a let f203 = a let f204 = a let f205 = a let f206 = a let f207 = a let f208 = a let f209 = a let f210 = a let f211 = a let f212 = a let f213 = a let f214 = a let f215 = a let f216 = a let f217 = a let f218 = a let f219 = a let f220 = a let f221 = a let f222 = a let f223 = a let f224 = a let f225 = a let f226 = a let f227 = a let f228 = a let f229 = a let f230 = a let f231 = a let f232 = a let f233 = a let f234 = a let f235 = a let f236 = a let f237 = a let f238 = a let f239 = a let f240 = a let f241 = a let f242 = a let f243 = a let f244 = a let f245 = a let f246 = a let f247 = a let f248 = a let f249 = a let f250 = a let f251 = a let f252 = a let f253 = a let f254 = a let f255 = a let f256 = a let f257 = a let f258 = a let f259 = a let f260 = a let f261 = a let f262 = a let f263 = a let f264 = a let f265 = a let f266 = a let f267 = a let f268 = a let f269 = a let f270 = a let f271 = a let f272 = a let f273 = a let f274 = a let f275 = a let f276 = a let f277 = a let f278 = a let f279 = a let f280 = a let f281 = a let f282 = a let f283 = a let f284 = a let f285 = a let f286 = a let f287 = a let f288 = a let f289 = a let f290 = a let f291 = a let f292 = a let f293 = a let f294 = a let f295 = a let f296 = a let f297 = a let f298 = a let f299 = a let f300 = a end let () = let p' = match Big.f132 with `Foo p -> p in Printf.printf "%b %b %b %b\n%!" (Obj.is_shared (Obj.repr (module Big : Big))) (Obj.is_shared (Obj.repr Big.f000)) (Obj.is_shared (Obj.repr p)) (p == p') let () = Gc.full_major () module type T = sig val f : unit -> int ref val g : unit -> int ref end module type Big' = Big with type a = unit -> int ref module F (X : sig val p : int ref end) = struct module rec M : T = struct let f () = Big'.f000 () let g () = N.g () end and Big' : Big' = struct type a = unit -> int ref let a () = N.f () let f000 () = M.g () let f001 () = a () let f002 () = a () let f003 () = a () let f004 () = a () let f005 () = a () let f006 () = a () let f007 () = a () let f008 () = a () let f009 () = a () let f010 () = a () let f011 () = a () let f012 () = a () let f013 () = a () let f014 () = a () let f015 () = a () let f016 () = a () let f017 () = a () let f018 () = a () let f019 () = a () let f020 () = a () let f021 () = a () let f022 () = a () let f023 () = a () let f024 () = a () let f025 () = a () let f026 () = a () let f027 () = a () let f028 () = a () let f029 () = a () let f030 () = a () let f031 () = a () let f032 () = a () let f033 () = a () let f034 () = a () let f035 () = a () let f036 () = a () let f037 () = a () let f038 () = a () let f039 () = a () let f040 () = a () let f041 () = a () let f042 () = a () let f043 () = a () let f044 () = a () let f045 () = a () let f046 () = a () let f047 () = a () let f048 () = a () let f049 () = a () let f050 () = a () let f051 () = a () let f052 () = a () let f053 () = a () let f054 () = a () let f055 () = a () let f056 () = a () let f057 () = a () let f058 () = a () let f059 () = a () let f060 () = a () let f061 () = a () let f062 () = a () let f063 () = a () let f064 () = a () let f065 () = a () let f066 () = a () let f067 () = a () let f068 () = a () let f069 () = a () let f070 () = a () let f071 () = a () let f072 () = a () let f073 () = a () let f074 () = a () let f075 () = a () let f076 () = a () let f077 () = a () let f078 () = a () let f079 () = a () let f080 () = a () let f081 () = a () let f082 () = a () let f083 () = a () let f084 () = a () let f085 () = a () let f086 () = a () let f087 () = a () let f088 () = a () let f089 () = a () let f090 () = a () let f091 () = a () let f092 () = a () let f093 () = a () let f094 () = a () let f095 () = a () let f096 () = a () let f097 () = a () let f098 () = a () let f099 () = a () let f100 () = a () let f101 () = a () let f102 () = a () let f103 () = a () let f104 () = a () let f105 () = a () let f106 () = a () let f107 () = a () let f108 () = a () let f109 () = a () let f110 () = a () let f111 () = a () let f112 () = a () let f113 () = a () let f114 () = a () let f115 () = a () let f116 () = a () let f117 () = a () let f118 () = a () let f119 () = a () let f120 () = a () let f121 () = a () let f122 () = a () let f123 () = a () let f124 () = a () let f125 () = a () let f126 () = a () let f127 () = a () let f128 () = a () let f129 () = a () let f130 () = a () let f131 () = a () let f132 () = a () let f133 () = a () let f134 () = a () let f135 () = a () let f136 () = a () let f137 () = a () let f138 () = a () let f139 () = a () let f140 () = a () let f141 () = a () let f142 () = a () let f143 () = a () let f144 () = a () let f145 () = a () let f146 () = a () let f147 () = a () let f148 () = a () let f149 () = a () let f150 () = a () let f151 () = a () let f152 () = a () let f153 () = a () let f154 () = a () let f155 () = a () let f156 () = a () let f157 () = a () let f158 () = a () let f159 () = a () let f160 () = a () let f161 () = a () let f162 () = a () let f163 () = a () let f164 () = a () let f165 () = a () let f166 () = a () let f167 () = a () let f168 () = a () let f169 () = a () let f170 () = a () let f171 () = a () let f172 () = a () let f173 () = a () let f174 () = a () let f175 () = a () let f176 () = a () let f177 () = a () let f178 () = a () let f179 () = a () let f180 () = a () let f181 () = a () let f182 () = a () let f183 () = a () let f184 () = a () let f185 () = a () let f186 () = a () let f187 () = a () let f188 () = a () let f189 () = a () let f190 () = a () let f191 () = a () let f192 () = a () let f193 () = a () let f194 () = a () let f195 () = a () let f196 () = a () let f197 () = a () let f198 () = a () let f199 () = a () let f200 () = a () let f201 () = a () let f202 () = a () let f203 () = a () let f204 () = a () let f205 () = a () let f206 () = a () let f207 () = a () let f208 () = a () let f209 () = a () let f210 () = a () let f211 () = a () let f212 () = a () let f213 () = a () let f214 () = a () let f215 () = a () let f216 () = a () let f217 () = a () let f218 () = a () let f219 () = a () let f220 () = a () let f221 () = a () let f222 () = a () let f223 () = a () let f224 () = a () let f225 () = a () let f226 () = a () let f227 () = a () let f228 () = a () let f229 () = a () let f230 () = a () let f231 () = a () let f232 () = a () let f233 () = a () let f234 () = a () let f235 () = a () let f236 () = a () let f237 () = a () let f238 () = a () let f239 () = a () let f240 () = a () let f241 () = a () let f242 () = a () let f243 () = a () let f244 () = a () let f245 () = a () let f246 () = a () let f247 () = a () let f248 () = a () let f249 () = a () let f250 () = a () let f251 () = a () let f252 () = a () let f253 () = a () let f254 () = a () let f255 () = a () let f256 () = a () let f257 () = a () let f258 () = a () let f259 () = a () let f260 () = a () let f261 () = a () let f262 () = a () let f263 () = a () let f264 () = a () let f265 () = a () let f266 () = a () let f267 () = a () let f268 () = a () let f269 () = a () let f270 () = a () let f271 () = a () let f272 () = a () let f273 () = a () let f274 () = a () let f275 () = a () let f276 () = a () let f277 () = a () let f278 () = a () let f279 () = a () let f280 () = a () let f281 () = a () let f282 () = a () let f283 () = a () let f284 () = a () let f285 () = a () let f286 () = a () let f287 () = a () let f288 () = a () let f289 () = a () let f290 () = a () let f291 () = a () let f292 () = a () let f293 () = a () let f294 () = a () let f295 () = a () let f296 () = a () let f297 () = a () let f298 () = a () let f299 () = a () let f300 () = a () end and N : T = struct let f () = Big'.f000 () let g () = X.p end end let () = let module FX = F (struct let p = p end) in let open FX in let p' = M.f () in Printf.printf "%b %b %b %b %b %b %b %b %b\n%!" (Obj.is_shared (Obj.repr (module Big' : Big'))) (Obj.is_shared (Obj.repr Big.f123)) (Obj.is_shared (Obj.repr (module M : T))) (Obj.is_shared (Obj.repr M.f)) (Obj.is_shared (Obj.repr M.g)) (Obj.is_shared (Obj.repr (module N : T))) (Obj.is_shared (Obj.repr N.f)) (Obj.is_shared (Obj.repr N.g)) (p == p')
cb9fe5ea4bb4f52585869a9662a878eca2d658764a0bdec43260b2085f670e85
brendanhay/amazonka
Types.hs
# LANGUAGE DisambiguateRecordFields # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | -- Module : Amazonka.WorkLink.Types Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.WorkLink.Types ( -- * Service Configuration defaultService, -- * Errors _InternalServerErrorException, _InvalidRequestException, _ResourceAlreadyExistsException, _ResourceNotFoundException, _TooManyRequestsException, _UnauthorizedException, ) where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Prelude as Prelude import qualified Amazonka.Sign.V4 as Sign | API version @2018 - 09 - 25@ of the Amazon WorkLink SDK configuration . defaultService :: Core.Service defaultService = Core.Service { Core.abbrev = "WorkLink", Core.signer = Sign.v4, Core.endpointPrefix = "worklink", Core.signingName = "worklink", Core.version = "2018-09-25", Core.s3AddressingStyle = Core.S3AddressingStyleAuto, Core.endpoint = Core.defaultEndpoint defaultService, Core.timeout = Prelude.Just 70, Core.check = Core.statusSuccess, Core.error = Core.parseJSONError "WorkLink", Core.retry = retry } where retry = Core.Exponential { Core.base = 5.0e-2, Core.growth = 2, Core.attempts = 5, Core.check = check } check e | Lens.has (Core.hasStatus 502) e = Prelude.Just "bad_gateway" | Lens.has (Core.hasStatus 504) e = Prelude.Just "gateway_timeout" | Lens.has (Core.hasStatus 500) e = Prelude.Just "general_server_error" | Lens.has (Core.hasStatus 509) e = Prelude.Just "limit_exceeded" | Lens.has ( Core.hasCode "RequestThrottledException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "request_throttled_exception" | Lens.has (Core.hasStatus 503) e = Prelude.Just "service_unavailable" | Lens.has ( Core.hasCode "ThrottledException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttled_exception" | Lens.has ( Core.hasCode "Throttling" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttling" | Lens.has ( Core.hasCode "ThrottlingException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttling_exception" | Lens.has ( Core.hasCode "ProvisionedThroughputExceededException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throughput_exceeded" | Lens.has (Core.hasStatus 429) e = Prelude.Just "too_many_requests" | Prelude.otherwise = Prelude.Nothing -- | The service is temporarily unavailable. _InternalServerErrorException :: Core.AsError a => Lens.Fold a Core.ServiceError _InternalServerErrorException = Core._MatchServiceError defaultService "InternalServerErrorException" Prelude.. Core.hasStatus 500 -- | The request is not valid. _InvalidRequestException :: Core.AsError a => Lens.Fold a Core.ServiceError _InvalidRequestException = Core._MatchServiceError defaultService "InvalidRequestException" Prelude.. Core.hasStatus 400 -- | The resource already exists. _ResourceAlreadyExistsException :: Core.AsError a => Lens.Fold a Core.ServiceError _ResourceAlreadyExistsException = Core._MatchServiceError defaultService "ResourceAlreadyExistsException" Prelude.. Core.hasStatus 400 -- | The requested resource was not found. _ResourceNotFoundException :: Core.AsError a => Lens.Fold a Core.ServiceError _ResourceNotFoundException = Core._MatchServiceError defaultService "ResourceNotFoundException" Prelude.. Core.hasStatus 404 -- | The number of requests exceeds the limit. _TooManyRequestsException :: Core.AsError a => Lens.Fold a Core.ServiceError _TooManyRequestsException = Core._MatchServiceError defaultService "TooManyRequestsException" Prelude.. Core.hasStatus 429 -- | You are not authorized to perform this action. _UnauthorizedException :: Core.AsError a => Lens.Fold a Core.ServiceError _UnauthorizedException = Core._MatchServiceError defaultService "UnauthorizedException" Prelude.. Core.hasStatus 403
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-worklink/gen/Amazonka/WorkLink/Types.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Module : Amazonka.WorkLink.Types Stability : auto-generated * Service Configuration * Errors | The service is temporarily unavailable. | The request is not valid. | The resource already exists. | The requested resource was not found. | The number of requests exceeds the limit. | You are not authorized to perform this action.
# LANGUAGE DisambiguateRecordFields # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.WorkLink.Types defaultService, _InternalServerErrorException, _InvalidRequestException, _ResourceAlreadyExistsException, _ResourceNotFoundException, _TooManyRequestsException, _UnauthorizedException, ) where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Prelude as Prelude import qualified Amazonka.Sign.V4 as Sign | API version @2018 - 09 - 25@ of the Amazon WorkLink SDK configuration . defaultService :: Core.Service defaultService = Core.Service { Core.abbrev = "WorkLink", Core.signer = Sign.v4, Core.endpointPrefix = "worklink", Core.signingName = "worklink", Core.version = "2018-09-25", Core.s3AddressingStyle = Core.S3AddressingStyleAuto, Core.endpoint = Core.defaultEndpoint defaultService, Core.timeout = Prelude.Just 70, Core.check = Core.statusSuccess, Core.error = Core.parseJSONError "WorkLink", Core.retry = retry } where retry = Core.Exponential { Core.base = 5.0e-2, Core.growth = 2, Core.attempts = 5, Core.check = check } check e | Lens.has (Core.hasStatus 502) e = Prelude.Just "bad_gateway" | Lens.has (Core.hasStatus 504) e = Prelude.Just "gateway_timeout" | Lens.has (Core.hasStatus 500) e = Prelude.Just "general_server_error" | Lens.has (Core.hasStatus 509) e = Prelude.Just "limit_exceeded" | Lens.has ( Core.hasCode "RequestThrottledException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "request_throttled_exception" | Lens.has (Core.hasStatus 503) e = Prelude.Just "service_unavailable" | Lens.has ( Core.hasCode "ThrottledException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttled_exception" | Lens.has ( Core.hasCode "Throttling" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttling" | Lens.has ( Core.hasCode "ThrottlingException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throttling_exception" | Lens.has ( Core.hasCode "ProvisionedThroughputExceededException" Prelude.. Core.hasStatus 400 ) e = Prelude.Just "throughput_exceeded" | Lens.has (Core.hasStatus 429) e = Prelude.Just "too_many_requests" | Prelude.otherwise = Prelude.Nothing _InternalServerErrorException :: Core.AsError a => Lens.Fold a Core.ServiceError _InternalServerErrorException = Core._MatchServiceError defaultService "InternalServerErrorException" Prelude.. Core.hasStatus 500 _InvalidRequestException :: Core.AsError a => Lens.Fold a Core.ServiceError _InvalidRequestException = Core._MatchServiceError defaultService "InvalidRequestException" Prelude.. Core.hasStatus 400 _ResourceAlreadyExistsException :: Core.AsError a => Lens.Fold a Core.ServiceError _ResourceAlreadyExistsException = Core._MatchServiceError defaultService "ResourceAlreadyExistsException" Prelude.. Core.hasStatus 400 _ResourceNotFoundException :: Core.AsError a => Lens.Fold a Core.ServiceError _ResourceNotFoundException = Core._MatchServiceError defaultService "ResourceNotFoundException" Prelude.. Core.hasStatus 404 _TooManyRequestsException :: Core.AsError a => Lens.Fold a Core.ServiceError _TooManyRequestsException = Core._MatchServiceError defaultService "TooManyRequestsException" Prelude.. Core.hasStatus 429 _UnauthorizedException :: Core.AsError a => Lens.Fold a Core.ServiceError _UnauthorizedException = Core._MatchServiceError defaultService "UnauthorizedException" Prelude.. Core.hasStatus 403
4360480aba3fec0828012be14a895d217e5ac2d21f8808174287842123256636
levand/qttt
reagent.cljs
(ns qttt.ui.reagent (:require [reagent.core :as r] [qttt.game :as game])) (def game (r/atom game/new-game)) (def css-transition-group (js/React.createFactory js/React.addons.CSSTransitionGroup)) (defn class-name "Return a class name string given multiple CSS classes. Nil classes are filtered out." [& classes] (apply str (interpose " " (filter identity classes)))) (defn mark [{:keys [player turn focus collapsing]}] (let [icon (if (= 0 player) "fa-plus" "fa-circle-o") player-class (if (= 0 player) "player-x" "player-o")] [:span {:class (class-name "mark" player-class (when focus "highlight") (when collapsing "shake") (when collapsing "shake-constant"))} [:span {:class (class-name "fa" icon)}] [:span.turn turn]])) (defn entanglement [e cell subcell] [:td {:class (if (empty? e) "empty-mark" "spooky-mark") :on-click (fn [evt] (swap! game #(game/play (game/unspeculate %) cell subcell))) :on-mouse-enter (fn [evt] (swap! game #(game/speculate % cell subcell))) :on-mouse-leave (fn [evt] (swap! game game/unspeculate))} (css-transition-group #js {:transitionName "mark-transition"} (when-not (empty? e) (r/as-element (mark e))))]) (defn superposition [cell cell-idx] [:td.superposition [:table (for [row (partition 3 (range 9))] ^{:key (str row)} [:tr (for [idx row] (let [e (get-in cell [:entanglements idx] {})] ^{:key idx} [entanglement e cell-idx idx]))])]]) (defn classical [cell cell-idx] [:td.classical (mark (:classical cell))]) (defn cell [cell cell-idx] (if (:classical cell) ^{:key cell-idx} [classical cell cell-idx] ^{:key cell-idx} [superposition cell cell-idx])) (defn instructions [game] (let [[player phase] (game/instructions game) player-classes (if (zero? player) ["player-x" "fa-plus"] ["player-o" "fa-circle-o"])] [:div.instructions [:span {:class (apply class-name "mark" "fa" player-classes)}] (str "'s turn: " phase)])) (defn board [game] [:div.board-container [instructions game] [:table.board (for [row (partition 3 (range 9))] ^{:key (str row)} [:tr (for [idx row] (cell (get-in game [:board idx]) idx))])] [:div.repo-link [:a {:href ""} ""]]]) (defn screen [] [:div.play-area [board @game]]) (defn ^:export main [] (r/render [screen] (. js/document (getElementById "root"))))
null
https://raw.githubusercontent.com/levand/qttt/5be7e03a181a7d621638e112a2a514badfa065c2/src/qttt/ui/reagent.cljs
clojure
(ns qttt.ui.reagent (:require [reagent.core :as r] [qttt.game :as game])) (def game (r/atom game/new-game)) (def css-transition-group (js/React.createFactory js/React.addons.CSSTransitionGroup)) (defn class-name "Return a class name string given multiple CSS classes. Nil classes are filtered out." [& classes] (apply str (interpose " " (filter identity classes)))) (defn mark [{:keys [player turn focus collapsing]}] (let [icon (if (= 0 player) "fa-plus" "fa-circle-o") player-class (if (= 0 player) "player-x" "player-o")] [:span {:class (class-name "mark" player-class (when focus "highlight") (when collapsing "shake") (when collapsing "shake-constant"))} [:span {:class (class-name "fa" icon)}] [:span.turn turn]])) (defn entanglement [e cell subcell] [:td {:class (if (empty? e) "empty-mark" "spooky-mark") :on-click (fn [evt] (swap! game #(game/play (game/unspeculate %) cell subcell))) :on-mouse-enter (fn [evt] (swap! game #(game/speculate % cell subcell))) :on-mouse-leave (fn [evt] (swap! game game/unspeculate))} (css-transition-group #js {:transitionName "mark-transition"} (when-not (empty? e) (r/as-element (mark e))))]) (defn superposition [cell cell-idx] [:td.superposition [:table (for [row (partition 3 (range 9))] ^{:key (str row)} [:tr (for [idx row] (let [e (get-in cell [:entanglements idx] {})] ^{:key idx} [entanglement e cell-idx idx]))])]]) (defn classical [cell cell-idx] [:td.classical (mark (:classical cell))]) (defn cell [cell cell-idx] (if (:classical cell) ^{:key cell-idx} [classical cell cell-idx] ^{:key cell-idx} [superposition cell cell-idx])) (defn instructions [game] (let [[player phase] (game/instructions game) player-classes (if (zero? player) ["player-x" "fa-plus"] ["player-o" "fa-circle-o"])] [:div.instructions [:span {:class (apply class-name "mark" "fa" player-classes)}] (str "'s turn: " phase)])) (defn board [game] [:div.board-container [instructions game] [:table.board (for [row (partition 3 (range 9))] ^{:key (str row)} [:tr (for [idx row] (cell (get-in game [:board idx]) idx))])] [:div.repo-link [:a {:href ""} ""]]]) (defn screen [] [:div.play-area [board @game]]) (defn ^:export main [] (r/render [screen] (. js/document (getElementById "root"))))
d5393b176694898cbfd2edd804b075c5bc9f001ba4ee575236db97d37f9cea83
input-output-hk/marlowe-cardano
Server.hs
# LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # {-# LANGUAGE RankNTypes #-} -- | A view of the chain sync protocol from the point of view of the -- server. This provides a simplified interface for implementing the server -- role of the protocol. The types should be much easier to use than the -- underlying typed protocol types. module Network.Protocol.ChainSeek.Server where import Network.Protocol.ChainSeek.Types import Network.TypedProtocol (Peer(..), PeerHasAgency(..)) import Network.TypedProtocol.Core (PeerRole(..)) -- | A chain sync protocol server that runs in some monad 'm'. newtype ChainSeekServer query point tip m a = ChainSeekServer { runChainSeekServer :: m (ServerStInit query point tip m a) } | In the ' StInit ' protocol state , the server does not have agency . Instead , -- it is waiting to handle a handshake request from the client, which it must -- handle. newtype ServerStInit query point tip m a = ServerStInit { recvMsgRequestHandshake :: SchemaVersion -> m (ServerStHandshake query point tip m a) } -- | In the 'StHandshake' protocol state, the server has agency. It must send -- either: -- -- * a handshake rejection message -- * a handshake confirmation message data ServerStHandshake query point tip m a where -- | Reject the handshake request SendMsgHandshakeRejected :: [SchemaVersion] -- ^ A list of supported schema versions. -> a -- ^ The result of running the protocol. -> ServerStHandshake query point tip m a -- | Accept the handshake request SendMsgHandshakeConfirmed :: m (ServerStIdle query point tip m a) -- ^ An action that computes the idle handlers. -> ServerStHandshake query point tip m a -- | In the `StIdle` protocol state, the server does not have agency. Instead, -- it is waiting to handle either: -- -- * A query next update request -- * A termination message -- -- It must be prepared to handle either. data ServerStIdle query point tip m a = ServerStIdle { recvMsgQueryNext :: forall err result . query err result -> m (ServerStNext query err result point tip m a) , recvMsgDone :: m a } | In the ` StNext ` protocol state , the server has agency . It must send -- either: -- -- * A query rejection response -- * A roll forward response -- * A roll backward response data ServerStNext query err result point tip m a where -- | Reject the query with an error message. SendMsgQueryRejected :: err -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a -- | Send a query response and advance the client to a new point in the -- chain. SendMsgRollForward :: result -> point -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a -- | Roll the client back to a previous point. SendMsgRollBackward :: point -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a -- | Tell the client to wait SendMsgWait :: m (ServerStPoll query err result point tip m a) -> ServerStNext query err result point tip m a | In the ` StPoll ` protocol state , the server does not have agency . Instead , -- it is waiting to handle either: -- -- * A poll message -- * A cancel poll message -- -- It must be prepared to handle either. data ServerStPoll query err result point tip m a = ServerStPoll { recvMsgPoll :: m (ServerStNext query err result point tip m a) , recvMsgCancel :: m (ServerStIdle query point tip m a) } -- | Transform the query, point, and tip types in the server. mapChainSeekServer :: forall query query' point point' tip tip' m a . Functor m => (forall err result. query' err result -> query err result) -> (point -> point') -> (tip -> tip') -> ChainSeekServer query point tip m a -> ChainSeekServer query' point' tip' m a mapChainSeekServer cmapQuery mapPoint mapTip = ChainSeekServer . fmap mapInit . runChainSeekServer where mapInit = ServerStInit . (fmap . fmap) mapHandshake . recvMsgRequestHandshake mapHandshake :: ServerStHandshake query point tip m a -> ServerStHandshake query' point' tip' m a mapHandshake (SendMsgHandshakeRejected vs m) = SendMsgHandshakeRejected vs m mapHandshake (SendMsgHandshakeConfirmed idle) = SendMsgHandshakeConfirmed $ mapIdle <$> idle mapIdle :: ServerStIdle query point tip m a -> ServerStIdle query' point' tip' m a mapIdle ServerStIdle{..} = ServerStIdle { recvMsgQueryNext = fmap mapNext . recvMsgQueryNext . cmapQuery , recvMsgDone } mapNext :: forall err result . ServerStNext query err result point tip m a -> ServerStNext query' err result point' tip' m a mapNext (SendMsgQueryRejected err tip idle) = SendMsgQueryRejected err (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgRollForward result point tip idle) = SendMsgRollForward result (mapPoint point) (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgRollBackward point tip idle) = SendMsgRollBackward (mapPoint point) (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgWait mnext) = SendMsgWait $ mapPoll <$> mnext mapPoll :: forall err result . ServerStPoll query err result point tip m a -> ServerStPoll query' err result point' tip' m a mapPoll ServerStPoll{..} = ServerStPoll { recvMsgPoll = fmap mapNext recvMsgPoll , recvMsgCancel = fmap mapIdle recvMsgCancel } -- | Change the underlying monad with a natural transformation. hoistChainSeekServer :: forall query point tip m n a . Functor m => (forall x. m x -> n x) -> ChainSeekServer query point tip m a -> ChainSeekServer query point tip n a hoistChainSeekServer f = ChainSeekServer . f . fmap hoistInit . runChainSeekServer where hoistInit :: ServerStInit query point tip m a -> ServerStInit query point tip n a hoistInit = ServerStInit . fmap (f . fmap hoistHandshake) . recvMsgRequestHandshake hoistHandshake :: ServerStHandshake query point tip m a -> ServerStHandshake query point tip n a hoistHandshake (SendMsgHandshakeRejected vs a) = SendMsgHandshakeRejected vs a hoistHandshake (SendMsgHandshakeConfirmed idle) = SendMsgHandshakeConfirmed $ f $ hoistIdle <$> idle hoistIdle :: ServerStIdle query point tip m a -> ServerStIdle query point tip n a hoistIdle ServerStIdle{..} = ServerStIdle { recvMsgQueryNext = f . fmap hoistNext . recvMsgQueryNext , recvMsgDone = f recvMsgDone } hoistNext :: forall err result . ServerStNext query err result point tip m a -> ServerStNext query err result point tip n a hoistNext (SendMsgQueryRejected err tip idle) = SendMsgQueryRejected err tip $ f $ hoistIdle <$> idle hoistNext (SendMsgRollForward result point tip idle) = SendMsgRollForward result point tip $ f $ hoistIdle <$> idle hoistNext (SendMsgRollBackward point tip idle) = SendMsgRollBackward point tip $ f $ hoistIdle <$> idle hoistNext (SendMsgWait mnext) = SendMsgWait $ f $ hoistPoll <$> mnext hoistPoll :: forall err result . ServerStPoll query err result point tip m a -> ServerStPoll query err result point tip n a hoistPoll ServerStPoll{..} = ServerStPoll { recvMsgPoll = f $ fmap hoistNext recvMsgPoll , recvMsgCancel = f $ fmap hoistIdle recvMsgCancel } -- | Interpret the server as a 'typed-protocols' 'Peer'. chainSeekServerPeer :: forall query point tip m a . (Monad m, Query query) => point -> ChainSeekServer query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StInit m a chainSeekServerPeer initialPoint (ChainSeekServer mClient) = Effect $ peerInit <$> mClient where peerInit :: ServerStInit query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StInit m a peerInit ServerStInit{..} = Await (ClientAgency TokInit) \case MsgRequestHandshake version -> Effect $ peerHandshake <$> recvMsgRequestHandshake version peerHandshake :: ServerStHandshake query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StHandshake m a peerHandshake = \case SendMsgHandshakeRejected versions ma -> Yield (ServerAgency TokHandshake) (MsgRejectHandshake versions) $ Done TokDone ma SendMsgHandshakeConfirmed mIdle -> Yield (ServerAgency TokHandshake) MsgConfirmHandshake $ peerIdle initialPoint mIdle peerIdle :: point -> m (ServerStIdle query point tip m a) -> Peer (ChainSeek query point tip) 'AsServer 'StIdle m a peerIdle pos = Effect . fmap (peerIdle_ pos) peerIdle_ :: point -> ServerStIdle query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StIdle m a peerIdle_ pos ServerStIdle{..} = Await (ClientAgency TokIdle) \case MsgQueryNext query -> Effect $ fmap (peerNext pos query) $ recvMsgQueryNext query MsgDone -> Effect $ Done TokDone <$> recvMsgDone peerNext :: forall err result . point -> query err result -> ServerStNext query err result point tip m a -> Peer (ChainSeek query point tip) 'AsServer ('StNext err result) m a peerNext pos query = \case SendMsgQueryRejected err tip mIdle -> yield pos (MsgRejectQuery err tip) mIdle SendMsgRollForward result pos' tip mIdle -> yield pos' (MsgRollForward result pos' tip) mIdle SendMsgRollBackward pos' tip mIdle -> yield pos' (MsgRollBackward pos' tip) mIdle SendMsgWait mPoll -> Yield (ServerAgency (TokNext (tagFromQuery query))) MsgWait $ Effect $ peerPoll pos query <$> mPoll where yield pos' msg = Yield (ServerAgency (TokNext (tagFromQuery query))) msg . peerIdle pos' peerPoll :: forall err result . point -> query err result -> ServerStPoll query err result point tip m a -> Peer (ChainSeek query point tip) 'AsServer ('StPoll err result) m a peerPoll pos query ServerStPoll{..} = Await (ClientAgency TokPoll) \case MsgPoll -> Effect $ fmap (peerNext pos query) recvMsgPoll MsgCancel -> Effect $ fmap (peerIdle_ pos) recvMsgCancel
null
https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/a1bc3d0fde8774c91bb7e12f547503c643230be9/marlowe-protocols/src/Network/Protocol/ChainSeek/Server.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # | A view of the chain sync protocol from the point of view of the server. This provides a simplified interface for implementing the server role of the protocol. The types should be much easier to use than the underlying typed protocol types. | A chain sync protocol server that runs in some monad 'm'. it is waiting to handle a handshake request from the client, which it must handle. | In the 'StHandshake' protocol state, the server has agency. It must send either: * a handshake rejection message * a handshake confirmation message | Reject the handshake request ^ A list of supported schema versions. ^ The result of running the protocol. | Accept the handshake request ^ An action that computes the idle handlers. | In the `StIdle` protocol state, the server does not have agency. Instead, it is waiting to handle either: * A query next update request * A termination message It must be prepared to handle either. either: * A query rejection response * A roll forward response * A roll backward response | Reject the query with an error message. | Send a query response and advance the client to a new point in the chain. | Roll the client back to a previous point. | Tell the client to wait it is waiting to handle either: * A poll message * A cancel poll message It must be prepared to handle either. | Transform the query, point, and tip types in the server. | Change the underlying monad with a natural transformation. | Interpret the server as a 'typed-protocols' 'Peer'.
# LANGUAGE DataKinds # # LANGUAGE KindSignatures # module Network.Protocol.ChainSeek.Server where import Network.Protocol.ChainSeek.Types import Network.TypedProtocol (Peer(..), PeerHasAgency(..)) import Network.TypedProtocol.Core (PeerRole(..)) newtype ChainSeekServer query point tip m a = ChainSeekServer { runChainSeekServer :: m (ServerStInit query point tip m a) } | In the ' StInit ' protocol state , the server does not have agency . Instead , newtype ServerStInit query point tip m a = ServerStInit { recvMsgRequestHandshake :: SchemaVersion -> m (ServerStHandshake query point tip m a) } data ServerStHandshake query point tip m a where SendMsgHandshakeRejected -> ServerStHandshake query point tip m a SendMsgHandshakeConfirmed -> ServerStHandshake query point tip m a data ServerStIdle query point tip m a = ServerStIdle { recvMsgQueryNext :: forall err result . query err result -> m (ServerStNext query err result point tip m a) , recvMsgDone :: m a } | In the ` StNext ` protocol state , the server has agency . It must send data ServerStNext query err result point tip m a where SendMsgQueryRejected :: err -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a SendMsgRollForward :: result -> point -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a SendMsgRollBackward :: point -> tip -> m (ServerStIdle query point tip m a) -> ServerStNext query err result point tip m a SendMsgWait :: m (ServerStPoll query err result point tip m a) -> ServerStNext query err result point tip m a | In the ` StPoll ` protocol state , the server does not have agency . Instead , data ServerStPoll query err result point tip m a = ServerStPoll { recvMsgPoll :: m (ServerStNext query err result point tip m a) , recvMsgCancel :: m (ServerStIdle query point tip m a) } mapChainSeekServer :: forall query query' point point' tip tip' m a . Functor m => (forall err result. query' err result -> query err result) -> (point -> point') -> (tip -> tip') -> ChainSeekServer query point tip m a -> ChainSeekServer query' point' tip' m a mapChainSeekServer cmapQuery mapPoint mapTip = ChainSeekServer . fmap mapInit . runChainSeekServer where mapInit = ServerStInit . (fmap . fmap) mapHandshake . recvMsgRequestHandshake mapHandshake :: ServerStHandshake query point tip m a -> ServerStHandshake query' point' tip' m a mapHandshake (SendMsgHandshakeRejected vs m) = SendMsgHandshakeRejected vs m mapHandshake (SendMsgHandshakeConfirmed idle) = SendMsgHandshakeConfirmed $ mapIdle <$> idle mapIdle :: ServerStIdle query point tip m a -> ServerStIdle query' point' tip' m a mapIdle ServerStIdle{..} = ServerStIdle { recvMsgQueryNext = fmap mapNext . recvMsgQueryNext . cmapQuery , recvMsgDone } mapNext :: forall err result . ServerStNext query err result point tip m a -> ServerStNext query' err result point' tip' m a mapNext (SendMsgQueryRejected err tip idle) = SendMsgQueryRejected err (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgRollForward result point tip idle) = SendMsgRollForward result (mapPoint point) (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgRollBackward point tip idle) = SendMsgRollBackward (mapPoint point) (mapTip tip) $ mapIdle <$> idle mapNext (SendMsgWait mnext) = SendMsgWait $ mapPoll <$> mnext mapPoll :: forall err result . ServerStPoll query err result point tip m a -> ServerStPoll query' err result point' tip' m a mapPoll ServerStPoll{..} = ServerStPoll { recvMsgPoll = fmap mapNext recvMsgPoll , recvMsgCancel = fmap mapIdle recvMsgCancel } hoistChainSeekServer :: forall query point tip m n a . Functor m => (forall x. m x -> n x) -> ChainSeekServer query point tip m a -> ChainSeekServer query point tip n a hoistChainSeekServer f = ChainSeekServer . f . fmap hoistInit . runChainSeekServer where hoistInit :: ServerStInit query point tip m a -> ServerStInit query point tip n a hoistInit = ServerStInit . fmap (f . fmap hoistHandshake) . recvMsgRequestHandshake hoistHandshake :: ServerStHandshake query point tip m a -> ServerStHandshake query point tip n a hoistHandshake (SendMsgHandshakeRejected vs a) = SendMsgHandshakeRejected vs a hoistHandshake (SendMsgHandshakeConfirmed idle) = SendMsgHandshakeConfirmed $ f $ hoistIdle <$> idle hoistIdle :: ServerStIdle query point tip m a -> ServerStIdle query point tip n a hoistIdle ServerStIdle{..} = ServerStIdle { recvMsgQueryNext = f . fmap hoistNext . recvMsgQueryNext , recvMsgDone = f recvMsgDone } hoistNext :: forall err result . ServerStNext query err result point tip m a -> ServerStNext query err result point tip n a hoistNext (SendMsgQueryRejected err tip idle) = SendMsgQueryRejected err tip $ f $ hoistIdle <$> idle hoistNext (SendMsgRollForward result point tip idle) = SendMsgRollForward result point tip $ f $ hoistIdle <$> idle hoistNext (SendMsgRollBackward point tip idle) = SendMsgRollBackward point tip $ f $ hoistIdle <$> idle hoistNext (SendMsgWait mnext) = SendMsgWait $ f $ hoistPoll <$> mnext hoistPoll :: forall err result . ServerStPoll query err result point tip m a -> ServerStPoll query err result point tip n a hoistPoll ServerStPoll{..} = ServerStPoll { recvMsgPoll = f $ fmap hoistNext recvMsgPoll , recvMsgCancel = f $ fmap hoistIdle recvMsgCancel } chainSeekServerPeer :: forall query point tip m a . (Monad m, Query query) => point -> ChainSeekServer query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StInit m a chainSeekServerPeer initialPoint (ChainSeekServer mClient) = Effect $ peerInit <$> mClient where peerInit :: ServerStInit query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StInit m a peerInit ServerStInit{..} = Await (ClientAgency TokInit) \case MsgRequestHandshake version -> Effect $ peerHandshake <$> recvMsgRequestHandshake version peerHandshake :: ServerStHandshake query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StHandshake m a peerHandshake = \case SendMsgHandshakeRejected versions ma -> Yield (ServerAgency TokHandshake) (MsgRejectHandshake versions) $ Done TokDone ma SendMsgHandshakeConfirmed mIdle -> Yield (ServerAgency TokHandshake) MsgConfirmHandshake $ peerIdle initialPoint mIdle peerIdle :: point -> m (ServerStIdle query point tip m a) -> Peer (ChainSeek query point tip) 'AsServer 'StIdle m a peerIdle pos = Effect . fmap (peerIdle_ pos) peerIdle_ :: point -> ServerStIdle query point tip m a -> Peer (ChainSeek query point tip) 'AsServer 'StIdle m a peerIdle_ pos ServerStIdle{..} = Await (ClientAgency TokIdle) \case MsgQueryNext query -> Effect $ fmap (peerNext pos query) $ recvMsgQueryNext query MsgDone -> Effect $ Done TokDone <$> recvMsgDone peerNext :: forall err result . point -> query err result -> ServerStNext query err result point tip m a -> Peer (ChainSeek query point tip) 'AsServer ('StNext err result) m a peerNext pos query = \case SendMsgQueryRejected err tip mIdle -> yield pos (MsgRejectQuery err tip) mIdle SendMsgRollForward result pos' tip mIdle -> yield pos' (MsgRollForward result pos' tip) mIdle SendMsgRollBackward pos' tip mIdle -> yield pos' (MsgRollBackward pos' tip) mIdle SendMsgWait mPoll -> Yield (ServerAgency (TokNext (tagFromQuery query))) MsgWait $ Effect $ peerPoll pos query <$> mPoll where yield pos' msg = Yield (ServerAgency (TokNext (tagFromQuery query))) msg . peerIdle pos' peerPoll :: forall err result . point -> query err result -> ServerStPoll query err result point tip m a -> Peer (ChainSeek query point tip) 'AsServer ('StPoll err result) m a peerPoll pos query ServerStPoll{..} = Await (ClientAgency TokPoll) \case MsgPoll -> Effect $ fmap (peerNext pos query) recvMsgPoll MsgCancel -> Effect $ fmap (peerIdle_ pos) recvMsgCancel
9f658fcece627360ab863e6c8db05e0bff67c3027508d2bd087dcd21c4973aa1
ocaml-omake/omake
lm_index.mli
* Index module based on tables . * An index is essentially a multi - level table . * Each entry has an associated data item and subtable . * * ---------------------------------------------------------------- * * Copyright ( C ) 2002 , Caltech * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation , * version 2.1 of the License . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA * * Additional permission is given to link this library with the * OpenSSL project 's " OpenSSL " library , and with the OCaml runtime , * and you may distribute the linked executables . See the file * LICENSE.libmojave for more details . * * Author : * * * ---------------------------------------------------------------- * Revision History * * 2002 Apr 20 Initial Version * 2002 Apr 25 iter , maps , folds to * _ all * added single level iters , maps , folds * 2002 Apr 26 functions for explicitly adding * subindices * 2002 May 1 Changed interface for managing * subindices * Index module based on tables. * An index is essentially a multi-level table. * Each entry has an associated data item and subtable. * * ---------------------------------------------------------------- * * Copyright (C) 2002 Michael Maire, Caltech * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Additional permission is given to link this library with the * OpenSSL project's "OpenSSL" library, and with the OCaml runtime, * and you may distribute the linked executables. See the file * LICENSE.libmojave for more details. * * Author: Michael Maire * * * ---------------------------------------------------------------- * Revision History * * 2002 Apr 20 Michael Maire Initial Version * 2002 Apr 25 Michael Maire Renamed iter, maps, folds to *_all * added single level iters, maps, folds * 2002 Apr 26 Michael Maire Added functions for explicitly adding * subindices * 2002 May 1 Michael Maire Changed interface for managing * subindices *) (* * Elements. * This type specifies the type of the keys used in the index. *) module type OrderedType = sig type t val compare : t -> t -> int end (* * These are the functions provided by the index. *) module type LmIndex = sig (* index maps key lists to elements of type 'a *) type key type 'a t (* empty index and empty test *) val empty : 'a t val is_empty : 'a t -> bool (* tests/lookups - single level*) val mem : 'a t -> key -> bool val find : 'a t -> key -> 'a t * 'a val find_index : 'a t -> key -> 'a t val find_data : 'a t -> key -> 'a (* tests/lookups - multi level*) val mem_list : 'a t -> key list -> bool val find_list : 'a t -> key list -> 'a t * 'a val find_list_index : 'a t -> key list -> 'a t val find_list_data : 'a t -> key list -> 'a (* addition and removal - single level*) val add : 'a t -> key -> 'a -> 'a t val add_i : 'a t -> key -> 'a t * 'a -> 'a t val remove : 'a t -> key -> 'a t (* addition of a chain of nested entries *) val add_list : 'a t -> key list -> 'a list -> 'a t val add_list_i : 'a t -> key list -> ('a t * 'a) list -> 'a t (* addition/removal of single entries *) val add_entry : 'a t -> key list -> 'a -> 'a t val add_entry_i : 'a t -> key list -> 'a t * 'a -> 'a t val remove_entry : 'a t -> key list -> 'a t (* filter addition/removal - single level *) val filter_add : 'a t -> key -> ('a option -> 'a) -> 'a t val filter_add_i : 'a t -> key -> (('a t * 'a) option -> ('a t * 'a)) -> 'a t val filter_remove : 'a t -> key -> ('a -> 'a option) -> 'a t val filter_remove_i : 'a t -> key -> (('a t * 'a) -> ('a t * 'a) option) -> 'a t (* filter addition of a chain of nested entries *) val filter_add_list : 'a t -> key list -> ('a option -> 'a) list -> 'a t val filter_add_list_i : 'a t -> key list -> (('a t * 'a) option -> ('a t * 'a)) list -> 'a t (* filter addition/removal of single entries *) val filter_add_entry : 'a t -> key list -> ('a option -> 'a) -> 'a t val filter_add_entry_i : 'a t -> key list -> (('a t * 'a) option -> ('a t * 'a)) -> 'a t val filter_remove_entry : 'a t -> key list -> ('a -> 'a option) -> 'a t val filter_remove_entry_i : 'a t -> key list -> (('a t * 'a) -> ('a t * 'a) option) -> 'a t (* iterators, maps, and folds - single level *) val iter : (key -> ('a t * 'a) -> unit) -> 'a t -> unit val map : (('a t * 'a) -> ('b t * 'b)) -> 'a t -> 'b t val mapi : (key -> ('a t * 'a) -> ('b t * 'b)) -> 'a t -> 'b t val fold : ('a -> key -> ('b t * 'b) -> 'a) -> 'a -> 'b t -> 'a val fold_map : ('a -> key -> ('b t * 'b) -> 'a * ('c t * 'c)) -> 'a -> 'b t -> 'a * 'c t (* iterators, maps, and folds - entire index *) val iter_all : (key list -> 'a -> unit) -> 'a t -> unit val map_all : ('a -> 'b) -> 'a t -> 'b t val mapi_all : (key list -> 'a -> 'b) -> 'a t -> 'b t val fold_all : ('a -> key list -> 'b -> 'a) -> 'a -> 'b t -> 'a val fold_map_all : ('a -> key list -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t end (* * Make the index. *) module LmMake (Ord : OrderedType) : (LmIndex with type key = Ord.t)
null
https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/libmojave/lm_index.mli
ocaml
* Elements. * This type specifies the type of the keys used in the index. * These are the functions provided by the index. index maps key lists to elements of type 'a empty index and empty test tests/lookups - single level tests/lookups - multi level addition and removal - single level addition of a chain of nested entries addition/removal of single entries filter addition/removal - single level filter addition of a chain of nested entries filter addition/removal of single entries iterators, maps, and folds - single level iterators, maps, and folds - entire index * Make the index.
* Index module based on tables . * An index is essentially a multi - level table . * Each entry has an associated data item and subtable . * * ---------------------------------------------------------------- * * Copyright ( C ) 2002 , Caltech * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation , * version 2.1 of the License . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA * * Additional permission is given to link this library with the * OpenSSL project 's " OpenSSL " library , and with the OCaml runtime , * and you may distribute the linked executables . See the file * LICENSE.libmojave for more details . * * Author : * * * ---------------------------------------------------------------- * Revision History * * 2002 Apr 20 Initial Version * 2002 Apr 25 iter , maps , folds to * _ all * added single level iters , maps , folds * 2002 Apr 26 functions for explicitly adding * subindices * 2002 May 1 Changed interface for managing * subindices * Index module based on tables. * An index is essentially a multi-level table. * Each entry has an associated data item and subtable. * * ---------------------------------------------------------------- * * Copyright (C) 2002 Michael Maire, Caltech * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Additional permission is given to link this library with the * OpenSSL project's "OpenSSL" library, and with the OCaml runtime, * and you may distribute the linked executables. See the file * LICENSE.libmojave for more details. * * Author: Michael Maire * * * ---------------------------------------------------------------- * Revision History * * 2002 Apr 20 Michael Maire Initial Version * 2002 Apr 25 Michael Maire Renamed iter, maps, folds to *_all * added single level iters, maps, folds * 2002 Apr 26 Michael Maire Added functions for explicitly adding * subindices * 2002 May 1 Michael Maire Changed interface for managing * subindices *) module type OrderedType = sig type t val compare : t -> t -> int end module type LmIndex = sig type key type 'a t val empty : 'a t val is_empty : 'a t -> bool val mem : 'a t -> key -> bool val find : 'a t -> key -> 'a t * 'a val find_index : 'a t -> key -> 'a t val find_data : 'a t -> key -> 'a val mem_list : 'a t -> key list -> bool val find_list : 'a t -> key list -> 'a t * 'a val find_list_index : 'a t -> key list -> 'a t val find_list_data : 'a t -> key list -> 'a val add : 'a t -> key -> 'a -> 'a t val add_i : 'a t -> key -> 'a t * 'a -> 'a t val remove : 'a t -> key -> 'a t val add_list : 'a t -> key list -> 'a list -> 'a t val add_list_i : 'a t -> key list -> ('a t * 'a) list -> 'a t val add_entry : 'a t -> key list -> 'a -> 'a t val add_entry_i : 'a t -> key list -> 'a t * 'a -> 'a t val remove_entry : 'a t -> key list -> 'a t val filter_add : 'a t -> key -> ('a option -> 'a) -> 'a t val filter_add_i : 'a t -> key -> (('a t * 'a) option -> ('a t * 'a)) -> 'a t val filter_remove : 'a t -> key -> ('a -> 'a option) -> 'a t val filter_remove_i : 'a t -> key -> (('a t * 'a) -> ('a t * 'a) option) -> 'a t val filter_add_list : 'a t -> key list -> ('a option -> 'a) list -> 'a t val filter_add_list_i : 'a t -> key list -> (('a t * 'a) option -> ('a t * 'a)) list -> 'a t val filter_add_entry : 'a t -> key list -> ('a option -> 'a) -> 'a t val filter_add_entry_i : 'a t -> key list -> (('a t * 'a) option -> ('a t * 'a)) -> 'a t val filter_remove_entry : 'a t -> key list -> ('a -> 'a option) -> 'a t val filter_remove_entry_i : 'a t -> key list -> (('a t * 'a) -> ('a t * 'a) option) -> 'a t val iter : (key -> ('a t * 'a) -> unit) -> 'a t -> unit val map : (('a t * 'a) -> ('b t * 'b)) -> 'a t -> 'b t val mapi : (key -> ('a t * 'a) -> ('b t * 'b)) -> 'a t -> 'b t val fold : ('a -> key -> ('b t * 'b) -> 'a) -> 'a -> 'b t -> 'a val fold_map : ('a -> key -> ('b t * 'b) -> 'a * ('c t * 'c)) -> 'a -> 'b t -> 'a * 'c t val iter_all : (key list -> 'a -> unit) -> 'a t -> unit val map_all : ('a -> 'b) -> 'a t -> 'b t val mapi_all : (key list -> 'a -> 'b) -> 'a t -> 'b t val fold_all : ('a -> key list -> 'b -> 'a) -> 'a -> 'b t -> 'a val fold_map_all : ('a -> key list -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t end module LmMake (Ord : OrderedType) : (LmIndex with type key = Ord.t)
136b2fe6923e46f5740396e229873908780b51170d85640f9b6eaf0429631ac4
ds-wizard/engine-backend
Api.hs
module Wizard.Api.Handler.DocumentTemplateDraft.File.Api where import Servant import Servant.Swagger.Tags import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_Content_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_Content_PUT import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_DELETE import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_PUT import Wizard.Api.Handler.DocumentTemplateDraft.File.List_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.List_POST import Wizard.Model.Context.BaseContext type DocumentTemplateFileAPI = Tags "Document Template Draft File" :> ( List_GET :<|> List_POST :<|> Detail_GET :<|> Detail_PUT :<|> Detail_DELETE :<|> Detail_Content_GET :<|> Detail_Content_PUT ) documentTemplateFileApi :: Proxy DocumentTemplateFileAPI documentTemplateFileApi = Proxy documentTemplateFileServer :: ServerT DocumentTemplateFileAPI BaseContextM documentTemplateFileServer = list_GET :<|> list_POST :<|> detail_GET :<|> detail_PUT :<|> detail_DELETE :<|> detail_content_GET :<|> detail_content_PUT
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Handler/DocumentTemplateDraft/File/Api.hs
haskell
module Wizard.Api.Handler.DocumentTemplateDraft.File.Api where import Servant import Servant.Swagger.Tags import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_Content_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_Content_PUT import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_DELETE import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.Detail_PUT import Wizard.Api.Handler.DocumentTemplateDraft.File.List_GET import Wizard.Api.Handler.DocumentTemplateDraft.File.List_POST import Wizard.Model.Context.BaseContext type DocumentTemplateFileAPI = Tags "Document Template Draft File" :> ( List_GET :<|> List_POST :<|> Detail_GET :<|> Detail_PUT :<|> Detail_DELETE :<|> Detail_Content_GET :<|> Detail_Content_PUT ) documentTemplateFileApi :: Proxy DocumentTemplateFileAPI documentTemplateFileApi = Proxy documentTemplateFileServer :: ServerT DocumentTemplateFileAPI BaseContextM documentTemplateFileServer = list_GET :<|> list_POST :<|> detail_GET :<|> detail_PUT :<|> detail_DELETE :<|> detail_content_GET :<|> detail_content_PUT
b54276fed2c3f990129a85ca25dcef42b2b647d62853bee240264906b4a899fc
zack-bitcoin/amoveo
block_hashes.erl
-module(block_hashes). % keep the hash of every block we attempt to verify, that way we don't waste time trying to verify the same block twice. each blockhash is about 32 bytes . We need to prepare for about 10000000 blocks . So that would be 32 megabytes of data . We can keep this all in ram . -behaviour(gen_server). -export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2, add/1,check/1,second_chance/0, test/0]). -record(d, {set, list = []}).%set is all the hashes -define(LOC, constants:block_hashes()). init(ok) -> process_flag(trap_exit, true), %io:fwrite("start block_hashes\n"), X = db:read(?LOC), K = if X == "" -> #d{set = i_new()}; true -> X end, {ok, K}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []). code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_, X) -> db:save(?LOC, X), io:format("block_hashes died!"), ok. handle_info(_, X) -> {noreply, X}. handle_cast(_, X) -> {noreply, X}. handle_call(second_chance, _, X) -> %for every hash stored in the set, check if we are storing a block. If we are not storing a block, then remove it from the set. X2 = second_chance_internal(X), {reply, ok, X2}; handle_call({add, H}, _From, X) -> N = i_insert(H, X#d.set), L2 = [H|X#d.list], Len = length(L2), {ok, ForkTolerance} = application:get_env(amoveo_core, fork_tolerance), FT = ForkTolerance + 1, FTB = ForkTolerance * 2, X2 = if Len > FTB -> {NL, T} = lists:split(FT, L2), NS = remove_many(T, N), X#d{list = NL, set = NS}; true -> X#d{list = L2, set = N} end, {reply, ok, X2}; handle_call({check, H}, _From, X) -> B = i_check(H, X#d.set), {reply, B, X} ; handle_call(_, _From, X) -> {reply, X, X}. remove_many([], N) -> N; remove_many([H|T], N) -> N2 = i_remove(H, N), remove_many(T, N2). add(X) -> true = is_binary(X), true = size(X) == constants:hash_size(), gen_server:call(?MODULE, {add, X}). check(X) -> true = size(X) == constants:hash_size(), gen_server:call(?MODULE, {check, X}). second_chance() -> gen_server:call(?MODULE, second_chance, 30000). second_chance_internal(X) -> L = X#d.list, S = X#d.set, {L2, S2} = sci2(L, [], S), X#d{set = S2, list = L2}. sci2([], L2, S2) -> {lists:reverse(L2), S2}; sci2([H|LI], LO, S) -> %check if we are storing block H. if not, then remove it from the list and the set. {ok, Version} = application:get_env(amoveo_core, db_version), case Version of 1 -> case block:get_by_hash(H) of empty -> sci2(LI, LO, i_remove(H, S)); _ -> sci2(LI, [H|LO], S) end; _ -> case block_db:exists(H) of false -> sci2(LI, LO, i_remove(H, S)); true -> sci2(LI, [H|LO], S) end end. i_new() -> %gb_sets:new(). sets:new(). i_insert(H, X) -> %gb_sets:add(H, X). sets:add_element(H, X). i_check(H, X) -> %gb_sets:is_member(H, X). sets:is_element(H, X). i_remove(H, X) -> sets:del_element(H, X). test() -> V1 = <<1:92>>, V2 = <<2:92>>, D = i_new(), D2 = i_insert(V1, D), false = i_check(V2, D2), true = i_check(V1, D2), success.
null
https://raw.githubusercontent.com/zack-bitcoin/amoveo/257f3e8cc07f1bae9df1a7252b8bc67a0dad3262/apps/amoveo_core/src/consensus/chain/block_hashes.erl
erlang
keep the hash of every block we attempt to verify, that way we don't waste time trying to verify the same block twice. set is all the hashes io:fwrite("start block_hashes\n"), for every hash stored in the set, check if we are storing a block. If we are not storing a block, then remove it from the set. check if we are storing block H. if not, then remove it from the list and the set. gb_sets:new(). gb_sets:add(H, X). gb_sets:is_member(H, X).
-module(block_hashes). each blockhash is about 32 bytes . We need to prepare for about 10000000 blocks . So that would be 32 megabytes of data . We can keep this all in ram . -behaviour(gen_server). -export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2, add/1,check/1,second_chance/0, test/0]). -define(LOC, constants:block_hashes()). init(ok) -> process_flag(trap_exit, true), X = db:read(?LOC), K = if X == "" -> #d{set = i_new()}; true -> X end, {ok, K}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []). code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_, X) -> db:save(?LOC, X), io:format("block_hashes died!"), ok. handle_info(_, X) -> {noreply, X}. handle_cast(_, X) -> {noreply, X}. handle_call(second_chance, _, X) -> X2 = second_chance_internal(X), {reply, ok, X2}; handle_call({add, H}, _From, X) -> N = i_insert(H, X#d.set), L2 = [H|X#d.list], Len = length(L2), {ok, ForkTolerance} = application:get_env(amoveo_core, fork_tolerance), FT = ForkTolerance + 1, FTB = ForkTolerance * 2, X2 = if Len > FTB -> {NL, T} = lists:split(FT, L2), NS = remove_many(T, N), X#d{list = NL, set = NS}; true -> X#d{list = L2, set = N} end, {reply, ok, X2}; handle_call({check, H}, _From, X) -> B = i_check(H, X#d.set), {reply, B, X} ; handle_call(_, _From, X) -> {reply, X, X}. remove_many([], N) -> N; remove_many([H|T], N) -> N2 = i_remove(H, N), remove_many(T, N2). add(X) -> true = is_binary(X), true = size(X) == constants:hash_size(), gen_server:call(?MODULE, {add, X}). check(X) -> true = size(X) == constants:hash_size(), gen_server:call(?MODULE, {check, X}). second_chance() -> gen_server:call(?MODULE, second_chance, 30000). second_chance_internal(X) -> L = X#d.list, S = X#d.set, {L2, S2} = sci2(L, [], S), X#d{set = S2, list = L2}. sci2([], L2, S2) -> {lists:reverse(L2), S2}; sci2([H|LI], LO, S) -> {ok, Version} = application:get_env(amoveo_core, db_version), case Version of 1 -> case block:get_by_hash(H) of empty -> sci2(LI, LO, i_remove(H, S)); _ -> sci2(LI, [H|LO], S) end; _ -> case block_db:exists(H) of false -> sci2(LI, LO, i_remove(H, S)); true -> sci2(LI, [H|LO], S) end end. i_new() -> sets:new(). i_insert(H, X) -> sets:add_element(H, X). i_check(H, X) -> sets:is_element(H, X). i_remove(H, X) -> sets:del_element(H, X). test() -> V1 = <<1:92>>, V2 = <<2:92>>, D = i_new(), D2 = i_insert(V1, D), false = i_check(V2, D2), true = i_check(V1, D2), success.
9834d29e32743a957760bf4f78236b82b91470cbb331cb76f7ae86ca072ab8f2
engineyard/vertebra-erl
test_suite.erl
Copyright 2008 , Engine Yard , Inc. % This file is part of Vertebra . % Vertebra is free software : you can redistribute it and/or modify it under the % terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any % later version. % Vertebra 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 Vertebra . If not , see < / > . -module(test_suite). -include_lib("eunit/include/eunit.hrl").
null
https://raw.githubusercontent.com/engineyard/vertebra-erl/cf6e7c84f6dfbf2e31f19c47e9db112ae292ec27/lib/eye_update/tests/test_suite.erl
erlang
terms of the GNU Lesser General Public License as published by the Free later version. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
Copyright 2008 , Engine Yard , Inc. This file is part of Vertebra . Vertebra is free software : you can redistribute it and/or modify it under the Software Foundation , either version 3 of the License , or ( at your option ) any Vertebra is distributed in the hope that it will be useful , but WITHOUT ANY You should have received a copy of the GNU Lesser General Public License along with Vertebra . If not , see < / > . -module(test_suite). -include_lib("eunit/include/eunit.hrl").
73a9d373f3d222705098ccb60bdc7a5582ff1767e6026068568cc3896f229905
ryanpbrewster/haskell
RandomHands.hs
module Main where import Poker.Data import Poker.Analysis import qualified Data.Set as S import System.Random import System.Random.Shuffle import Control.Monad import Data.Map (Map) import qualified Data.Map as M import Data.Ord (Down(..)) import Data.List (sortOn) trials = 10000 main :: IO () main = do forM_ [5..30] $ \num_cards -> do decks <- replicateM trials $ fmap (S.fromList . take num_cards) (shuffleM allCards) let hand_tally = M.fromListWith (+) $ zip (map (handType . bestHand) decks) (repeat 1) let tally_dump = unlines [ hand ++ "\t" ++ show (M.findWithDefault 0 hand hand_tally) | hand <- allTypes ] writeFile (show num_cards ++ ".log") tally_dump handType :: Hand -> String handType (HighCard r) = "HighCard" handType ( OnePair r ) = " " handType (TwoPair r1 r2) = "TwoPair" handType (Triple r) = "Triple" handType (Straight r) = "Straight" handType (Flush r) = "Flush" handType (FullHouse r1 r2) = "FullHouse" handType (Quartet r) = "Quartet" handType (StraightFlush r) = "StraightFlush" allTypes = [ "HighCard" , "OnePair" , "TwoPair" , "Triple" , "Straight" , "Flush" , "FullHouse" , "Quartet" , "StraightFlush" ]
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/poker/app/RandomHands.hs
haskell
module Main where import Poker.Data import Poker.Analysis import qualified Data.Set as S import System.Random import System.Random.Shuffle import Control.Monad import Data.Map (Map) import qualified Data.Map as M import Data.Ord (Down(..)) import Data.List (sortOn) trials = 10000 main :: IO () main = do forM_ [5..30] $ \num_cards -> do decks <- replicateM trials $ fmap (S.fromList . take num_cards) (shuffleM allCards) let hand_tally = M.fromListWith (+) $ zip (map (handType . bestHand) decks) (repeat 1) let tally_dump = unlines [ hand ++ "\t" ++ show (M.findWithDefault 0 hand hand_tally) | hand <- allTypes ] writeFile (show num_cards ++ ".log") tally_dump handType :: Hand -> String handType (HighCard r) = "HighCard" handType ( OnePair r ) = " " handType (TwoPair r1 r2) = "TwoPair" handType (Triple r) = "Triple" handType (Straight r) = "Straight" handType (Flush r) = "Flush" handType (FullHouse r1 r2) = "FullHouse" handType (Quartet r) = "Quartet" handType (StraightFlush r) = "StraightFlush" allTypes = [ "HighCard" , "OnePair" , "TwoPair" , "Triple" , "Straight" , "Flush" , "FullHouse" , "Quartet" , "StraightFlush" ]
8bfb4f93155d405fd716363e7e25a7855069886dbf2cb935ac0b5808c76813e6
gas2serra/mcclim-desktop
system-browser.lisp
(in-package :desktop-user) (register-application "system-browser" 'standard-cl-application :pretty-name "System Browser" :icon nil :menu-p nil :home-page "-open-browser" :git-repo "-open-browser.git" :system-name "trivial-open-browser")
null
https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/dot-mcclim-desktop/apps/system-browser.lisp
lisp
(in-package :desktop-user) (register-application "system-browser" 'standard-cl-application :pretty-name "System Browser" :icon nil :menu-p nil :home-page "-open-browser" :git-repo "-open-browser.git" :system-name "trivial-open-browser")
8b68367b910eeec1c2677a23afcc9e1ae6724b339ea225a686c9398e5ae0d743
rvantonder/hack_parallel
scheduler.ml
* Copyright ( c ) 2016 - present , Facebook , Inc. Modified work Copyright ( c ) 2018 - 2019 Rijnard van Tonder This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree . Modified work Copyright (c) 2018-2019 Rijnard van Tonder This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. *) open Hack_parallel_intf.Std module Daemon = Daemon type t = { workers: Worker.t list; number_of_workers: int; bucket_multiplier: int; } let entry = Worker.register_entry_point ~restore:(fun _ -> ()) let create ?(number_of_workers = 1) ?(bucket_multiplier = 10) () = let heap_handle = Memory.get_heap_handle () in let workers = Hack_parallel_intf.Std.Worker.make ~saved_state:() ~entry ~nbr_procs:number_of_workers ~heap_handle ~gc_control:Memory.worker_garbage_control in Memory.connect heap_handle; { workers; number_of_workers; bucket_multiplier } let map_reduce { workers; number_of_workers; bucket_multiplier } ?bucket_size ~init ~map ~reduce work = let number_of_workers = match bucket_size with | Some exact_size when exact_size > 0 -> (List.length work / exact_size) + 1 | _ -> let bucket_multiplier = Core_kernel.Int.min bucket_multiplier (1 + (List.length work / 400)) in number_of_workers * bucket_multiplier in MultiWorker.call (Some workers) ~job:map ~merge:reduce ~neutral:init ~next:(Bucket.make ~num_workers:number_of_workers work) let iter scheduler ~f work = map_reduce scheduler ~init:() ~map:(fun _ work -> f work) ~reduce:(fun _ _ -> ()) work let single_job { workers; _ } ~f work = let rec wait_until_ready handle = let { Worker.readys; _ } = Worker.select [handle] in match readys with | [] -> wait_until_ready handle | ready :: _ -> ready in match workers with | worker::_ -> Worker.call worker f work |> wait_until_ready |> Worker.get_result | [] -> failwith "This service contains no workers" let mock () = Memory.get_heap_handle () |> ignore; { workers = []; number_of_workers = 1; bucket_multiplier = 1 } let destroy _ = Worker.killall ()
null
https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/interface/scheduler.ml
ocaml
* Copyright ( c ) 2016 - present , Facebook , Inc. Modified work Copyright ( c ) 2018 - 2019 Rijnard van Tonder This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree . Modified work Copyright (c) 2018-2019 Rijnard van Tonder This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. *) open Hack_parallel_intf.Std module Daemon = Daemon type t = { workers: Worker.t list; number_of_workers: int; bucket_multiplier: int; } let entry = Worker.register_entry_point ~restore:(fun _ -> ()) let create ?(number_of_workers = 1) ?(bucket_multiplier = 10) () = let heap_handle = Memory.get_heap_handle () in let workers = Hack_parallel_intf.Std.Worker.make ~saved_state:() ~entry ~nbr_procs:number_of_workers ~heap_handle ~gc_control:Memory.worker_garbage_control in Memory.connect heap_handle; { workers; number_of_workers; bucket_multiplier } let map_reduce { workers; number_of_workers; bucket_multiplier } ?bucket_size ~init ~map ~reduce work = let number_of_workers = match bucket_size with | Some exact_size when exact_size > 0 -> (List.length work / exact_size) + 1 | _ -> let bucket_multiplier = Core_kernel.Int.min bucket_multiplier (1 + (List.length work / 400)) in number_of_workers * bucket_multiplier in MultiWorker.call (Some workers) ~job:map ~merge:reduce ~neutral:init ~next:(Bucket.make ~num_workers:number_of_workers work) let iter scheduler ~f work = map_reduce scheduler ~init:() ~map:(fun _ work -> f work) ~reduce:(fun _ _ -> ()) work let single_job { workers; _ } ~f work = let rec wait_until_ready handle = let { Worker.readys; _ } = Worker.select [handle] in match readys with | [] -> wait_until_ready handle | ready :: _ -> ready in match workers with | worker::_ -> Worker.call worker f work |> wait_until_ready |> Worker.get_result | [] -> failwith "This service contains no workers" let mock () = Memory.get_heap_handle () |> ignore; { workers = []; number_of_workers = 1; bucket_multiplier = 1 } let destroy _ = Worker.killall ()
f70454ad6556d99751f48d768771f1a0d12a00109e8295c9220551abc51883a8
Clozure/ccl-tests
char-compare.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Oct 5 19:36:00 2002 ;;;; Contains: Tests of character comparison functions (in-package :cl-test) ;;; The character comparisons should throw a PROGRAM-ERROR when ;;; safe-called with no arguments (deftest char-compare-no-args (loop for f in '(char= char/= char< char> char<= char>= char-lessp char-greaterp char-equal char-not-lessp char-not-greaterp char-not-equal) collect (eval `(signals-error (funcall ',f) program-error))) (t t t t t t t t t t t t)) (deftest char=.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (not (char= c1 c2)))) t) (deftest char=.2 (loop for c across +code-chars+ always (char= c c)) t) (deftest char=.3 (every #'char= +code-chars+) t) (deftest char=.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (not (char= c1 c2)))) t) (deftest char=.order.1 (let ((i 0)) (values (not (char= (progn (incf i) #\a))) i)) nil 1) (deftest char=.order.2 (let ((i 0) a b) (values (char= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b)) i a b)) nil 2 1 2) (deftest char=.order.3 (let ((i 0) a b c) (values (char= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) ;;; (deftest char/=.1 (is-ordered-by +code-chars+ #'char/=) t) (deftest char/=.2 (loop for c across +code-chars+ never (char/= c c)) t) (deftest char/=.3 (every #'char/= +code-chars+) t) (deftest char/=.4 (is-ordered-by +rev-code-chars+ #'char/=) t) (deftest char/=.order.1 (let ((i 0)) (values (not (char/= (progn (incf i) #\a))) i)) nil 1) (deftest char/=.order.2 (let ((i 0) a b) (values (not (char/= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char/=.order.3 (let ((i 0) a b c) (values (char/= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) ;;; (deftest char<=.1 (loop for c across +code-chars+ always (char<= c c)) t) (deftest char<=.2 (every #'char<= +code-chars+) t) (deftest char<=.3 (is-antisymmetrically-ordered-by +code-chars+ #'char<=) t) (deftest char<=.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char<=) t) (deftest char<=.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char<=) t) (deftest char<=.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char<=) t) (deftest char<=.7 (notnot-mv (or (char<= #\9 #\A) (char<= #\Z #\0))) t) (deftest char<=.8 (notnot-mv (or (char<= #\9 #\a) (char<= #\z #\0))) t) (deftest char<=.order.1 (let ((i 0)) (values (not (char<= (progn (incf i) #\a))) i)) nil 1) (deftest char<=.order.2 (let ((i 0) a b) (values (not (char<= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char<=.order.3 (let ((i 0) a b c) (values (char<= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; (deftest char<.1 (loop for c across +code-chars+ never (char< c c)) t) (deftest char<.2 (every #'char< +code-chars+) t) (deftest char<.3 (is-antisymmetrically-ordered-by +code-chars+ #'char<) t) (deftest char<.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char<) t) (deftest char<.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char<) t) (deftest char<.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char<) t) (deftest char<.7 (notnot-mv (or (char< #\9 #\A) (char< #\Z #\0))) t) (deftest char<.8 (notnot-mv (or (char< #\9 #\a) (char< #\z #\0))) t) (deftest char<.order.1 (let ((i 0)) (values (not (char< (progn (incf i) #\a))) i)) nil 1) (deftest char<.order.2 (let ((i 0) a b) (values (not (char< (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char<.order.3 (let ((i 0) a b c) (values (char< (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char<.order.4 (let ((i 0) a b c) (values (char< (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) ;;; (deftest char>=.1 (loop for c across +code-chars+ always (char>= c c)) t) (deftest char>=.2 (every #'char>= +code-chars+) t) (deftest char>=.3 (is-antisymmetrically-ordered-by +rev-code-chars+ #'char>=) t) (deftest char>=.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char>=) t) (deftest char>=.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char>=) t) (deftest char>=.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char>=) t) (deftest char>=.7 (notnot-mv (or (char>= #\A #\9) (char>= #\0 #\Z))) t) (deftest char>=.8 (notnot-mv (or (char>= #\a #\9) (char>= #\0 #\z))) t) (deftest char>=.order.1 (let ((i 0)) (values (not (char>= (progn (incf i) #\a))) i)) nil 1) (deftest char>=.order.2 (let ((i 0) a b) (values (not (char>= (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char>=.order.3 (let ((i 0) a b c) (values (char>= (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char>=.order.4 (let ((i 0) a b c) (values (char>= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; (deftest char>.1 (loop for c across +code-chars+ never (char> c c)) t) (deftest char>.2 (every #'char> +code-chars+) t) (deftest char>.3 (is-antisymmetrically-ordered-by +rev-code-chars+ #'char>) t) (deftest char>.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char>) t) (deftest char>.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char>) t) (deftest char>.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char>) t) (deftest char>.7 (notnot-mv (or (char> #\A #\9) (char> #\0 #\Z))) t) (deftest char>.8 (notnot-mv (or (char> #\a #\9) (char> #\0 #\z))) t) (deftest char>.order.1 (let ((i 0)) (values (not (char> (progn (incf i) #\a))) i)) nil 1) (deftest char>.order.2 (let ((i 0) a b) (values (not (char> (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char>.order.3 (let ((i 0) a b c) (values (char> (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char>.order.4 (let ((i 0) a b c) (values (char> (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; Case-insensitive comparisons (deftest char-equal.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (not (char-equal c1 c2))))) t) (deftest char-equal.2 (loop for c across +code-chars+ always (char-equal c c)) t) (deftest char-equal.3 (loop for c across +code-chars+ always (char-equal c)) t) (deftest char-equal.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (not (char-equal c1 c2))))) t) (deftest char-equal.order.1 (let ((i 0)) (values (not (char-equal (progn (incf i) #\a))) i)) nil 1) (deftest char-equal.order.2 (let ((i 0) a b) (values (char-equal (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a)) i a b)) nil 2 1 2) (deftest char-equal.order.3 (let ((i 0) a b c) (values (char-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-equal.order.4 (let ((i 0) a b c) (values (char-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; (deftest char-not-equal.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (char-not-equal c1 c2)))) t) (deftest char-not-equal.2 (loop for c across +code-chars+ never (char-not-equal c c)) t) (deftest char-not-equal.3 (every #'char-not-equal +code-chars+) t) (deftest char-not-equal.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (char-not-equal c1 c2)))) t) (deftest char-not-equal.order.1 (let ((i 0)) (values (not (char-not-equal (progn (incf i) #\a))) i)) nil 1) (deftest char-not-equal.order.2 (let ((i 0) a b) (values (not (char-not-equal (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-not-equal.order.3 (let ((i 0) a b c) (values (char-not-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-not-equal.order.4 (let ((i 0) a b c) (values (char-not-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) ;;; (deftest char-not-greaterp.1 (loop for c across +code-chars+ always (char-not-greaterp c c)) t) (deftest char-not-greaterp.2 (every #'char-not-greaterp +code-chars+) t) (deftest char-not-greaterp.3 (is-case-insensitive #'char-not-greaterp) t) (deftest char-not-greaterp.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.7 (notnot-mv (or (char-not-greaterp #\9 #\A) (char-not-greaterp #\Z #\0))) t) (deftest char-not-greaterp.8 (notnot-mv (or (char-not-greaterp #\9 #\a) (char-not-greaterp #\z #\0))) t) (deftest char-not-greaterp.order.1 (let ((i 0)) (values (not (char-not-greaterp (progn (incf i) #\a))) i)) nil 1) (deftest char-not-greaterp.order.2 (let ((i 0) a b) (values (not (char-not-greaterp (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char-not-greaterp.order.3 (let ((i 0) a b c) (values (char-not-greaterp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-not-greaterp.order.4 (let ((i 0) a b c) (values (char-not-greaterp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; (deftest char-lessp.1 (loop for c across +code-chars+ never (char-lessp c c)) t) (deftest char-lessp.2 (every #'char-lessp +code-chars+) t) (deftest char-lessp.3 (is-case-insensitive #'char-lessp) t) (deftest char-lessp.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char-lessp) t) (deftest char-lessp.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char-lessp) t) (deftest char-lessp.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char-lessp) t) (deftest char-lessp.7 (notnot-mv (or (char-lessp #\9 #\A) (char-lessp #\Z #\0))) t) (deftest char-lessp.8 (notnot-mv (or (char-lessp #\9 #\a) (char-lessp #\z #\0))) t) (deftest char-lessp.order.1 (let ((i 0)) (values (not (char-lessp (progn (incf i) #\a))) i)) nil 1) (deftest char-lessp.order.2 (let ((i 0) a b) (values (not (char-lessp (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char-lessp.order.3 (let ((i 0) a b c) (values (char-lessp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-lessp.order.4 (let ((i 0) a b c) (values (char-lessp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) ;;; (deftest char-not-lessp.1 (loop for c across +code-chars+ always (char-not-lessp c c)) t) (deftest char-not-lessp.2 (every #'char-not-lessp +code-chars+) t) (deftest char-not-lessp.3 (is-case-insensitive #'char-not-lessp) t) (deftest char-not-lessp.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char-not-lessp) t) (deftest char-not-lessp.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char-not-lessp) t) (deftest char-not-lessp.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char-not-lessp) t) (deftest char-not-lessp.7 (notnot-mv (or (char-not-lessp #\A #\9) (char-not-lessp #\0 #\Z))) t) (deftest char-not-lessp.8 (notnot-mv (or (char-not-lessp #\a #\9) (char-not-lessp #\0 #\z))) t) (deftest char-not-lessp.order.1 (let ((i 0)) (values (not (char-not-lessp (progn (incf i) #\a))) i)) nil 1) (deftest char-not-lessp.order.2 (let ((i 0) a b) (values (not (char-not-lessp (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-not-lessp.order.3 (let ((i 0) a b c) (values (char-not-lessp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-not-lessp.order.4 (let ((i 0) a b c) (values (char-not-lessp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) ;;; (deftest char-greaterp.1 (loop for c across +code-chars+ never (char-greaterp c c)) t) (deftest char-greaterp.2 (every #'char-greaterp +code-chars+) t) (deftest char-greaterp.3 (is-case-insensitive #'char-greaterp) t) (deftest char-greaterp.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char-greaterp) t) (deftest char-greaterp.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char-greaterp) t) (deftest char-greaterp.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char-greaterp) t) (deftest char-greaterp.7 (notnot-mv (or (char-greaterp #\A #\9) (char-greaterp #\0 #\Z))) t) (deftest char-greaterp.8 (notnot-mv (or (char-greaterp #\a #\9) (char-greaterp #\0 #\z))) t) (deftest char-greaterp.order.1 (let ((i 0)) (values (not (char-greaterp (progn (incf i) #\a))) i)) nil 1) (deftest char-greaterp.order.2 (let ((i 0) a b) (values (not (char-greaterp (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-greaterp.order.3 (let ((i 0) a b c) (values (char-greaterp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-greaterp.order.4 (let ((i 0) a b c) (values (char-greaterp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/char-compare.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of character comparison functions The character comparisons should throw a PROGRAM-ERROR when safe-called with no arguments Case-insensitive comparisons
Author : Created : Sat Oct 5 19:36:00 2002 (in-package :cl-test) (deftest char-compare-no-args (loop for f in '(char= char/= char< char> char<= char>= char-lessp char-greaterp char-equal char-not-lessp char-not-greaterp char-not-equal) collect (eval `(signals-error (funcall ',f) program-error))) (t t t t t t t t t t t t)) (deftest char=.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (not (char= c1 c2)))) t) (deftest char=.2 (loop for c across +code-chars+ always (char= c c)) t) (deftest char=.3 (every #'char= +code-chars+) t) (deftest char=.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (not (char= c1 c2)))) t) (deftest char=.order.1 (let ((i 0)) (values (not (char= (progn (incf i) #\a))) i)) nil 1) (deftest char=.order.2 (let ((i 0) a b) (values (char= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b)) i a b)) nil 2 1 2) (deftest char=.order.3 (let ((i 0) a b c) (values (char= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char/=.1 (is-ordered-by +code-chars+ #'char/=) t) (deftest char/=.2 (loop for c across +code-chars+ never (char/= c c)) t) (deftest char/=.3 (every #'char/= +code-chars+) t) (deftest char/=.4 (is-ordered-by +rev-code-chars+ #'char/=) t) (deftest char/=.order.1 (let ((i 0)) (values (not (char/= (progn (incf i) #\a))) i)) nil 1) (deftest char/=.order.2 (let ((i 0) a b) (values (not (char/= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char/=.order.3 (let ((i 0) a b c) (values (char/= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char<=.1 (loop for c across +code-chars+ always (char<= c c)) t) (deftest char<=.2 (every #'char<= +code-chars+) t) (deftest char<=.3 (is-antisymmetrically-ordered-by +code-chars+ #'char<=) t) (deftest char<=.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char<=) t) (deftest char<=.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char<=) t) (deftest char<=.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char<=) t) (deftest char<=.7 (notnot-mv (or (char<= #\9 #\A) (char<= #\Z #\0))) t) (deftest char<=.8 (notnot-mv (or (char<= #\9 #\a) (char<= #\z #\0))) t) (deftest char<=.order.1 (let ((i 0)) (values (not (char<= (progn (incf i) #\a))) i)) nil 1) (deftest char<=.order.2 (let ((i 0) a b) (values (not (char<= (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char<=.order.3 (let ((i 0) a b c) (values (char<= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char<.1 (loop for c across +code-chars+ never (char< c c)) t) (deftest char<.2 (every #'char< +code-chars+) t) (deftest char<.3 (is-antisymmetrically-ordered-by +code-chars+ #'char<) t) (deftest char<.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char<) t) (deftest char<.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char<) t) (deftest char<.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char<) t) (deftest char<.7 (notnot-mv (or (char< #\9 #\A) (char< #\Z #\0))) t) (deftest char<.8 (notnot-mv (or (char< #\9 #\a) (char< #\z #\0))) t) (deftest char<.order.1 (let ((i 0)) (values (not (char< (progn (incf i) #\a))) i)) nil 1) (deftest char<.order.2 (let ((i 0) a b) (values (not (char< (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char<.order.3 (let ((i 0) a b c) (values (char< (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char<.order.4 (let ((i 0) a b c) (values (char< (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char>=.1 (loop for c across +code-chars+ always (char>= c c)) t) (deftest char>=.2 (every #'char>= +code-chars+) t) (deftest char>=.3 (is-antisymmetrically-ordered-by +rev-code-chars+ #'char>=) t) (deftest char>=.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char>=) t) (deftest char>=.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char>=) t) (deftest char>=.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char>=) t) (deftest char>=.7 (notnot-mv (or (char>= #\A #\9) (char>= #\0 #\Z))) t) (deftest char>=.8 (notnot-mv (or (char>= #\a #\9) (char>= #\0 #\z))) t) (deftest char>=.order.1 (let ((i 0)) (values (not (char>= (progn (incf i) #\a))) i)) nil 1) (deftest char>=.order.2 (let ((i 0) a b) (values (not (char>= (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char>=.order.3 (let ((i 0) a b c) (values (char>= (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char>=.order.4 (let ((i 0) a b c) (values (char>= (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char>.1 (loop for c across +code-chars+ never (char> c c)) t) (deftest char>.2 (every #'char> +code-chars+) t) (deftest char>.3 (is-antisymmetrically-ordered-by +rev-code-chars+ #'char>) t) (deftest char>.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char>) t) (deftest char>.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char>) t) (deftest char>.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char>) t) (deftest char>.7 (notnot-mv (or (char> #\A #\9) (char> #\0 #\Z))) t) (deftest char>.8 (notnot-mv (or (char> #\a #\9) (char> #\0 #\z))) t) (deftest char>.order.1 (let ((i 0)) (values (not (char> (progn (incf i) #\a))) i)) nil 1) (deftest char>.order.2 (let ((i 0) a b) (values (not (char> (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char>.order.3 (let ((i 0) a b c) (values (char> (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char>.order.4 (let ((i 0) a b c) (values (char> (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-equal.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (not (char-equal c1 c2))))) t) (deftest char-equal.2 (loop for c across +code-chars+ always (char-equal c c)) t) (deftest char-equal.3 (loop for c across +code-chars+ always (char-equal c)) t) (deftest char-equal.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (not (char-equal c1 c2))))) t) (deftest char-equal.order.1 (let ((i 0)) (values (not (char-equal (progn (incf i) #\a))) i)) nil 1) (deftest char-equal.order.2 (let ((i 0) a b) (values (char-equal (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a)) i a b)) nil 2 1 2) (deftest char-equal.order.3 (let ((i 0) a b c) (values (char-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-equal.order.4 (let ((i 0) a b c) (values (char-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-not-equal.1 (is-ordered-by +code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (char-not-equal c1 c2)))) t) (deftest char-not-equal.2 (loop for c across +code-chars+ never (char-not-equal c c)) t) (deftest char-not-equal.3 (every #'char-not-equal +code-chars+) t) (deftest char-not-equal.4 (is-ordered-by +rev-code-chars+ #'(lambda (c1 c2) (or (char= (char-downcase c1) (char-downcase c2)) (char-not-equal c1 c2)))) t) (deftest char-not-equal.order.1 (let ((i 0)) (values (not (char-not-equal (progn (incf i) #\a))) i)) nil 1) (deftest char-not-equal.order.2 (let ((i 0) a b) (values (not (char-not-equal (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-not-equal.order.3 (let ((i 0) a b c) (values (char-not-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-not-equal.order.4 (let ((i 0) a b c) (values (char-not-equal (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-not-greaterp.1 (loop for c across +code-chars+ always (char-not-greaterp c c)) t) (deftest char-not-greaterp.2 (every #'char-not-greaterp +code-chars+) t) (deftest char-not-greaterp.3 (is-case-insensitive #'char-not-greaterp) t) (deftest char-not-greaterp.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char-not-greaterp) t) (deftest char-not-greaterp.7 (notnot-mv (or (char-not-greaterp #\9 #\A) (char-not-greaterp #\Z #\0))) t) (deftest char-not-greaterp.8 (notnot-mv (or (char-not-greaterp #\9 #\a) (char-not-greaterp #\z #\0))) t) (deftest char-not-greaterp.order.1 (let ((i 0)) (values (not (char-not-greaterp (progn (incf i) #\a))) i)) nil 1) (deftest char-not-greaterp.order.2 (let ((i 0) a b) (values (not (char-not-greaterp (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char-not-greaterp.order.3 (let ((i 0) a b c) (values (char-not-greaterp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-not-greaterp.order.4 (let ((i 0) a b c) (values (char-not-greaterp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-lessp.1 (loop for c across +code-chars+ never (char-lessp c c)) t) (deftest char-lessp.2 (every #'char-lessp +code-chars+) t) (deftest char-lessp.3 (is-case-insensitive #'char-lessp) t) (deftest char-lessp.4 (is-antisymmetrically-ordered-by +lower-case-chars+ #'char-lessp) t) (deftest char-lessp.5 (is-antisymmetrically-ordered-by +upper-case-chars+ #'char-lessp) t) (deftest char-lessp.6 (is-antisymmetrically-ordered-by +digit-chars+ #'char-lessp) t) (deftest char-lessp.7 (notnot-mv (or (char-lessp #\9 #\A) (char-lessp #\Z #\0))) t) (deftest char-lessp.8 (notnot-mv (or (char-lessp #\9 #\a) (char-lessp #\z #\0))) t) (deftest char-lessp.order.1 (let ((i 0)) (values (not (char-lessp (progn (incf i) #\a))) i)) nil 1) (deftest char-lessp.order.2 (let ((i 0) a b) (values (not (char-lessp (progn (setf a (incf i)) #\a) (progn (setf b (incf i)) #\b))) i a b)) nil 2 1 2) (deftest char-lessp.order.3 (let ((i 0) a b c) (values (char-lessp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-lessp.order.4 (let ((i 0) a b c) (values (char-lessp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3) (deftest char-not-lessp.1 (loop for c across +code-chars+ always (char-not-lessp c c)) t) (deftest char-not-lessp.2 (every #'char-not-lessp +code-chars+) t) (deftest char-not-lessp.3 (is-case-insensitive #'char-not-lessp) t) (deftest char-not-lessp.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char-not-lessp) t) (deftest char-not-lessp.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char-not-lessp) t) (deftest char-not-lessp.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char-not-lessp) t) (deftest char-not-lessp.7 (notnot-mv (or (char-not-lessp #\A #\9) (char-not-lessp #\0 #\Z))) t) (deftest char-not-lessp.8 (notnot-mv (or (char-not-lessp #\a #\9) (char-not-lessp #\0 #\z))) t) (deftest char-not-lessp.order.1 (let ((i 0)) (values (not (char-not-lessp (progn (incf i) #\a))) i)) nil 1) (deftest char-not-lessp.order.2 (let ((i 0) a b) (values (not (char-not-lessp (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-not-lessp.order.3 (let ((i 0) a b c) (values (char-not-lessp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-not-lessp.order.4 (let ((i 0) a b c) (values (char-not-lessp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-greaterp.1 (loop for c across +code-chars+ never (char-greaterp c c)) t) (deftest char-greaterp.2 (every #'char-greaterp +code-chars+) t) (deftest char-greaterp.3 (is-case-insensitive #'char-greaterp) t) (deftest char-greaterp.4 (is-antisymmetrically-ordered-by (reverse +lower-case-chars+) #'char-greaterp) t) (deftest char-greaterp.5 (is-antisymmetrically-ordered-by (reverse +upper-case-chars+) #'char-greaterp) t) (deftest char-greaterp.6 (is-antisymmetrically-ordered-by (reverse +digit-chars+) #'char-greaterp) t) (deftest char-greaterp.7 (notnot-mv (or (char-greaterp #\A #\9) (char-greaterp #\0 #\Z))) t) (deftest char-greaterp.8 (notnot-mv (or (char-greaterp #\a #\9) (char-greaterp #\0 #\z))) t) (deftest char-greaterp.order.1 (let ((i 0)) (values (not (char-greaterp (progn (incf i) #\a))) i)) nil 1) (deftest char-greaterp.order.2 (let ((i 0) a b) (values (not (char-greaterp (progn (setf a (incf i)) #\b) (progn (setf b (incf i)) #\a))) i a b)) nil 2 1 2) (deftest char-greaterp.order.3 (let ((i 0) a b c) (values (char-greaterp (progn (setq a (incf i)) #\b) (progn (setq b (incf i)) #\a) (progn (setq c (incf i)) #\b)) i a b c)) nil 3 1 2 3) (deftest char-greaterp.order.4 (let ((i 0) a b c) (values (char-greaterp (progn (setq a (incf i)) #\a) (progn (setq b (incf i)) #\b) (progn (setq c (incf i)) #\a)) i a b c)) nil 3 1 2 3)
132ef9507944e2ffd667c943c22825b2300b6ad8c7173b0ae443892ad67889ee
opencog/miner
surp-mozi-ai.scm
;; Script to calculate the surprisingness of a given collection of ;; patterns over a given kb. This is convenient to test if the ;; surprisingness of a given pattern holds across multiple kbs. ;; ;; Make sure you disable compiling ;; ;; guile --no-auto-compile -l surp-mozi-ai.scm ;; Parameters (define kb-filename "all-pp.scm") (define ptns-filename "test.scm") (define surp 'nisurp) (define max-cnjs 3) (define db-ratio 1) ;; Load modules & utils (use-modules (srfi srfi-1)) (use-modules (opencog logger)) (use-modules (opencog ure)) (use-modules (opencog miner)) (use-modules (opencog bioscience)) (load "mozi-ai-utils.scm") ;; Set loggers (define log-filename (string-append (rm-extension ptns-filename "scm") "-" (rm-extension kb-filename "scm") "-" (symbol->string surp) ".log")) ;; Set main logger ;; (cog-logger-set-timestamp! #f) (cog-logger-set-level! "debug") ;; (cog-logger-set-sync! #t) (cog-logger-set-filename! log-filename) Set URE logger (ure-logger-set-level! "debug") ;; (ure-logger-set-timestamp! #f) ;; (ure-logger-set-sync! #t) (ure-logger-set-filename! log-filename) ;; Function to load the patterns and calculate their ;; surprisingness. Patterns can be already wrapped with a ;; surprisingness measure. In such case such function will replace it. (define (run-surprisingness) (let* (;; db concept (db-cpt (Concept kb-filename)) ;; Load patterns (ptns-filepath (string-append "ptns/" ptns-filename)) (msg (cog-logger-debug "Loading ~a" ptns-filepath)) (ptns-lst (load-patterns ptns-filepath db-cpt)) ;; Load kb (kb-filepath (string-append "kbs/" kb-filename)) (msg (cog-logger-debug "Loading ~a" kb-filepath)) (db-lst (load-min-preprocess kb-filepath)) ;; Build db concept (dmy (fill-db-cpt db-cpt db-lst)) Surprisingness (msg (cog-logger-info "Run surprisingness over ~a with patterns ~a" kb-filename ptns-filename)) (msg (cog-logger-info (string-append "With parameters:\n" "surp = ~a\n" "max-cnjs = ~a") surp max-cnjs)) (results (cog-outgoing-set (cog-surp surp max-cnjs db-cpt db-ratio))) (msg (cog-logger-info "Results of surprisingness over ~a:\nsize = ~a\n~a" kb-filename (length results) results))) results)) ;; Run surprisingness (define results (run-surprisingness))
null
https://raw.githubusercontent.com/opencog/miner/d46a2c4e4c4df8e0d3115dafca32ac51889e0a23/examples/miner/mozi-ai/surp-mozi-ai.scm
scheme
Script to calculate the surprisingness of a given collection of patterns over a given kb. This is convenient to test if the surprisingness of a given pattern holds across multiple kbs. Make sure you disable compiling guile --no-auto-compile -l surp-mozi-ai.scm Parameters Load modules & utils Set loggers Set main logger (cog-logger-set-timestamp! #f) (cog-logger-set-sync! #t) (ure-logger-set-timestamp! #f) (ure-logger-set-sync! #t) Function to load the patterns and calculate their surprisingness. Patterns can be already wrapped with a surprisingness measure. In such case such function will replace it. db concept Load patterns Load kb Build db concept Run surprisingness
(define kb-filename "all-pp.scm") (define ptns-filename "test.scm") (define surp 'nisurp) (define max-cnjs 3) (define db-ratio 1) (use-modules (srfi srfi-1)) (use-modules (opencog logger)) (use-modules (opencog ure)) (use-modules (opencog miner)) (use-modules (opencog bioscience)) (load "mozi-ai-utils.scm") (define log-filename (string-append (rm-extension ptns-filename "scm") "-" (rm-extension kb-filename "scm") "-" (symbol->string surp) ".log")) (cog-logger-set-level! "debug") (cog-logger-set-filename! log-filename) Set URE logger (ure-logger-set-level! "debug") (ure-logger-set-filename! log-filename) (define (run-surprisingness) (db-cpt (Concept kb-filename)) (ptns-filepath (string-append "ptns/" ptns-filename)) (msg (cog-logger-debug "Loading ~a" ptns-filepath)) (ptns-lst (load-patterns ptns-filepath db-cpt)) (kb-filepath (string-append "kbs/" kb-filename)) (msg (cog-logger-debug "Loading ~a" kb-filepath)) (db-lst (load-min-preprocess kb-filepath)) (dmy (fill-db-cpt db-cpt db-lst)) Surprisingness (msg (cog-logger-info "Run surprisingness over ~a with patterns ~a" kb-filename ptns-filename)) (msg (cog-logger-info (string-append "With parameters:\n" "surp = ~a\n" "max-cnjs = ~a") surp max-cnjs)) (results (cog-outgoing-set (cog-surp surp max-cnjs db-cpt db-ratio))) (msg (cog-logger-info "Results of surprisingness over ~a:\nsize = ~a\n~a" kb-filename (length results) results))) results)) (define results (run-surprisingness))
0cdf9045cdce84468eefb64870d84fe23fa403394bd6c701b0413793d6845c67
jcclinton/wow-emulator
client_sup.erl
This is a World of Warcraft emulator written in erlang , supporting client 1.12.x %% Copyright ( C ) 2014 < jamieclinton.com > %% %% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %% %% World of Warcraft, and all World of Warcraft or Warcraft art, images, and lore ande copyrighted by Blizzard Entertainment , Inc. -module(client_sup). -behavior(supervisor). -export([start_link/1]). -export([init/1]). start_link(AccountId) -> supervisor:start_link(?MODULE, {AccountId}). init({AccountId}) -> Procs = getChildSpecs(AccountId), % this supervisor wont restart its children if one dies % the reason is that if a process containing the socket dies, % then the socket will get closed, then the client will disconnect % and then the client will have to go through authentication anyway % so there is no point in keeping these processes around {ok, {{one_for_all, 0, 1}, Procs}}. getChildSpecs(AccountId) ->[ {client_rcv, {client_rcv, start_link, [self(), AccountId]}, transient, 10000, worker, [client_rcv]} ].
null
https://raw.githubusercontent.com/jcclinton/wow-emulator/21bc67bfc9eea131c447c67f7f889ba040dcdd79/src/client_sup.erl
erlang
This program is free software; you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. World of Warcraft, and all World of Warcraft or Warcraft art, images, this supervisor wont restart its children if one dies the reason is that if a process containing the socket dies, then the socket will get closed, then the client will disconnect and then the client will have to go through authentication anyway so there is no point in keeping these processes around
This is a World of Warcraft emulator written in erlang , supporting client 1.12.x Copyright ( C ) 2014 < jamieclinton.com > it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . and lore ande copyrighted by Blizzard Entertainment , Inc. -module(client_sup). -behavior(supervisor). -export([start_link/1]). -export([init/1]). start_link(AccountId) -> supervisor:start_link(?MODULE, {AccountId}). init({AccountId}) -> Procs = getChildSpecs(AccountId), {ok, {{one_for_all, 0, 1}, Procs}}. getChildSpecs(AccountId) ->[ {client_rcv, {client_rcv, start_link, [self(), AccountId]}, transient, 10000, worker, [client_rcv]} ].
de6e2874a326666c1500c36d4494f93b5b3d37db8e69694b9cec9e94a0cef3bb
glguy/5puzzle
Nonogram.hs
module Main where import RegExp.AST import RegExp.Match (match) import Ersatz import Booleans import Control.Monad import Data.List (intercalate,transpose) import Prelude hiding ((&&),(||),all,and,any,or,not) import Data.Colour.SRGB import Diagrams.Prelude (Diagram, mkSizeSpec, scale, fc, square) import Diagrams.TwoD.Transform (translateX, translateY) import Diagrams.Backend.SVG (B, renderSVG) main :: IO () main = do Just xs <- getModel (nonoSolve nonoPuzzle2) let asChar True = '*' asChar False = ' ' putStr $ unlines $ map (map asChar) xs let sizeSpec = mkSizeSpec (pure Nothing) renderSVG "output.svg" sizeSpec (drawSolution xs) drawSolution :: [[Bool]] -> Diagram B drawSolution rows = scale 10 $ foldMap drawCell [ (r,c) | (r,row ) <- zip [0..] rows , (c,True) <- zip [0..] row ] drawCell :: (Int,Int) -> Diagram B drawCell (r,c) = translateX (fromIntegral c) $ translateY (fromIntegral (negate r)) $ fc (sRGB24 30 30 30) $ square 1 data NonoPuzzle = NonoPuzzle { nonorows, nonocols :: [[Int]] , nonoextra :: [(Int,Int)] } nonoPuzzle :: NonoPuzzle nonoPuzzle = NonoPuzzle [[2],[1,2],[1,1], [2],[1],[3],[3],[2,2],[2,1],[2,2,1],[2,3],[2,2]] [[2,1],[1,3],[2,4],[3,4],[4],[3],[3],[3],[2],[2]] [] nonoPuzzle2 :: NonoPuzzle nonoPuzzle2 = NonoPuzzle [[7],[10],[1,4,1],[1,1,2,1,1],[1,1,2,1,1], [1,1,1,2],[1,1,1,1,1,2],[1,1,5,2],[1,1,1,3],[1,1,3,4], [2,2,6,2],[1,2,2,6,3],[2,3,4,2,2],[2,2,5,2,2],[1,7,2,2], [2,5,3,2],[4,5,2],[12,2],[10,2],[7,2], [1,2,3],[15],[15],[4,10],[4,9], [3,9,1],[2,9,3],[1,7,1,1,3],[1,5,2,1,3],[1,4,2,1,1,1,2]] [[2,5],[1,2,3],[6,3,3,3],[1,1,1,2,4],[5,1,2,3,4], [1,2,3,4,5],[3,1,9,2,5],[1,3,1,6,7,1],[3,1,1,2,3,3,7,1],[2,1,6,3,6,1], [2,1,6,3,6,1],[2,2,1,6,4,6,1],[3,6,4,5,1],[5,4,4,6],[5,4,8,5,1,1], [3,2,6,3,2,1],[1,2,1,3,2,1],[1,2,2,3,3],[4,13,3],[11,2]] [] gchqPuzzle :: NonoPuzzle gchqPuzzle = NonoPuzzle [ [7,3,1,1,7] , [1,1,2,2,1,1] , [1,3,1,3,1,1,3,1] , [1,3,1,1,6,1,3,1] , [1,3,1,5,2,1,3,1] , [1,1,2,1,1] , [7,1,1,1,1,1,7] , [3,3] , [1,2,3,1,1,3,1,1,2] , [1,1,3,2,1,1] , [4,1,4,2,1,2] , [1,1,1,1,1,4,1,3] , [2,1,1,1,2,5] , [3,2,2,6,3,1] , [1,9,1,1,2,1] , [2,1,2,2,3,1] , [3,1,1,1,1,5,1] , [1,2,2,5] , [7,1,2,1,1,1,3] , [1,1,2,1,2,2,1] , [1,3,1,4,5,1] , [1,3,1,3,10,2] , [1,3,1,1,6,6] , [1,1,2,1,1,2] , [7,2,1,2,5] ] [ [7,2,1,1,7] , [1,1,2,2,1,1] , [1,3,1,3,1,3,1,3,1] , [1,3,1,1,5,1,3,1] , [1,3,1,1,4,1,3,1] , [1,1,1,2,1,1] , [7,1,1,1,1,1,7] , [1,1,3] , [2,1,2,1,8,2,1] , [2,2,1,2,1,1,1,2] , [1,7,3,2,1] , [1,2,3,1,1,1,1,1] , [4,1,1,2,6] , [3,3,1,1,1,3,1] , [1,2,5,2,2] , [2,2,1,1,1,1,1,2,1] , [1,3,3,2,1,8,1] , [6,2,1] , [7,1,4,1,1,3] , [1,1,1,1,4] , [1,3,1,3,7,1] , [1,3,1,1,1,2,1,1,4] , [1,3,1,4,3,3] , [1,1,2,2,2,6,1] , [7,1,3,2,1,1] ] [(3,3),(3,4),(3,12),(3,13),(3,21), (8,6),(8,7),(8,10),(8,14),(8,15),(8,18), (16,6),(16,11),(16,16),(16,20), (21,3),(21,4),(21,9),(21,10),(21,15),(21,20),(21,21) ] nonoSolve :: MonadSAT s m => NonoPuzzle -> m [[Bit]] nonoSolve (NonoPuzzle rows cols extras) = do cells <- replicateM (length rows) $ replicateM (length cols) exists let check = match (===) . nonoHint assert $ all2 check rows cells assert $ all2 check cols (transpose cells) assert $ all (\(r,c) -> cells !! r !! c) extras return cells nonoHint :: Boolean a => [Int] -> RegExp a nonoHint = foldr next blanks . intercalate [blank] . map hint where blank = fill false hint n = blanks : replicate n (fill true) blanks = RE (Rep blank) fill x = RE (OneOf InSet [x]) next x y = RE (Seq (acceptsEmpty x && acceptsEmpty y) x y)
null
https://raw.githubusercontent.com/glguy/5puzzle/4d86cf9fad3ec3f70c57a167417adea6a3f9f30b/Nonogram.hs
haskell
module Main where import RegExp.AST import RegExp.Match (match) import Ersatz import Booleans import Control.Monad import Data.List (intercalate,transpose) import Prelude hiding ((&&),(||),all,and,any,or,not) import Data.Colour.SRGB import Diagrams.Prelude (Diagram, mkSizeSpec, scale, fc, square) import Diagrams.TwoD.Transform (translateX, translateY) import Diagrams.Backend.SVG (B, renderSVG) main :: IO () main = do Just xs <- getModel (nonoSolve nonoPuzzle2) let asChar True = '*' asChar False = ' ' putStr $ unlines $ map (map asChar) xs let sizeSpec = mkSizeSpec (pure Nothing) renderSVG "output.svg" sizeSpec (drawSolution xs) drawSolution :: [[Bool]] -> Diagram B drawSolution rows = scale 10 $ foldMap drawCell [ (r,c) | (r,row ) <- zip [0..] rows , (c,True) <- zip [0..] row ] drawCell :: (Int,Int) -> Diagram B drawCell (r,c) = translateX (fromIntegral c) $ translateY (fromIntegral (negate r)) $ fc (sRGB24 30 30 30) $ square 1 data NonoPuzzle = NonoPuzzle { nonorows, nonocols :: [[Int]] , nonoextra :: [(Int,Int)] } nonoPuzzle :: NonoPuzzle nonoPuzzle = NonoPuzzle [[2],[1,2],[1,1], [2],[1],[3],[3],[2,2],[2,1],[2,2,1],[2,3],[2,2]] [[2,1],[1,3],[2,4],[3,4],[4],[3],[3],[3],[2],[2]] [] nonoPuzzle2 :: NonoPuzzle nonoPuzzle2 = NonoPuzzle [[7],[10],[1,4,1],[1,1,2,1,1],[1,1,2,1,1], [1,1,1,2],[1,1,1,1,1,2],[1,1,5,2],[1,1,1,3],[1,1,3,4], [2,2,6,2],[1,2,2,6,3],[2,3,4,2,2],[2,2,5,2,2],[1,7,2,2], [2,5,3,2],[4,5,2],[12,2],[10,2],[7,2], [1,2,3],[15],[15],[4,10],[4,9], [3,9,1],[2,9,3],[1,7,1,1,3],[1,5,2,1,3],[1,4,2,1,1,1,2]] [[2,5],[1,2,3],[6,3,3,3],[1,1,1,2,4],[5,1,2,3,4], [1,2,3,4,5],[3,1,9,2,5],[1,3,1,6,7,1],[3,1,1,2,3,3,7,1],[2,1,6,3,6,1], [2,1,6,3,6,1],[2,2,1,6,4,6,1],[3,6,4,5,1],[5,4,4,6],[5,4,8,5,1,1], [3,2,6,3,2,1],[1,2,1,3,2,1],[1,2,2,3,3],[4,13,3],[11,2]] [] gchqPuzzle :: NonoPuzzle gchqPuzzle = NonoPuzzle [ [7,3,1,1,7] , [1,1,2,2,1,1] , [1,3,1,3,1,1,3,1] , [1,3,1,1,6,1,3,1] , [1,3,1,5,2,1,3,1] , [1,1,2,1,1] , [7,1,1,1,1,1,7] , [3,3] , [1,2,3,1,1,3,1,1,2] , [1,1,3,2,1,1] , [4,1,4,2,1,2] , [1,1,1,1,1,4,1,3] , [2,1,1,1,2,5] , [3,2,2,6,3,1] , [1,9,1,1,2,1] , [2,1,2,2,3,1] , [3,1,1,1,1,5,1] , [1,2,2,5] , [7,1,2,1,1,1,3] , [1,1,2,1,2,2,1] , [1,3,1,4,5,1] , [1,3,1,3,10,2] , [1,3,1,1,6,6] , [1,1,2,1,1,2] , [7,2,1,2,5] ] [ [7,2,1,1,7] , [1,1,2,2,1,1] , [1,3,1,3,1,3,1,3,1] , [1,3,1,1,5,1,3,1] , [1,3,1,1,4,1,3,1] , [1,1,1,2,1,1] , [7,1,1,1,1,1,7] , [1,1,3] , [2,1,2,1,8,2,1] , [2,2,1,2,1,1,1,2] , [1,7,3,2,1] , [1,2,3,1,1,1,1,1] , [4,1,1,2,6] , [3,3,1,1,1,3,1] , [1,2,5,2,2] , [2,2,1,1,1,1,1,2,1] , [1,3,3,2,1,8,1] , [6,2,1] , [7,1,4,1,1,3] , [1,1,1,1,4] , [1,3,1,3,7,1] , [1,3,1,1,1,2,1,1,4] , [1,3,1,4,3,3] , [1,1,2,2,2,6,1] , [7,1,3,2,1,1] ] [(3,3),(3,4),(3,12),(3,13),(3,21), (8,6),(8,7),(8,10),(8,14),(8,15),(8,18), (16,6),(16,11),(16,16),(16,20), (21,3),(21,4),(21,9),(21,10),(21,15),(21,20),(21,21) ] nonoSolve :: MonadSAT s m => NonoPuzzle -> m [[Bit]] nonoSolve (NonoPuzzle rows cols extras) = do cells <- replicateM (length rows) $ replicateM (length cols) exists let check = match (===) . nonoHint assert $ all2 check rows cells assert $ all2 check cols (transpose cells) assert $ all (\(r,c) -> cells !! r !! c) extras return cells nonoHint :: Boolean a => [Int] -> RegExp a nonoHint = foldr next blanks . intercalate [blank] . map hint where blank = fill false hint n = blanks : replicate n (fill true) blanks = RE (Rep blank) fill x = RE (OneOf InSet [x]) next x y = RE (Seq (acceptsEmpty x && acceptsEmpty y) x y)
d7c2c241f77df7e697b60d012ea8278fcbec3fdf655e769a32093dd57a2ff21c
michaelnisi/feeder
feeder_entries.erl
-module(feeder_entries). -include("feeder_records.hrl"). -export([get/2]). get(author, E) -> E#entry.author; get(categories, E) -> E#entry.categories; get(duration, E) -> E#entry.duration; get(enclosure, E) -> E#entry.enclosure; get(id, E) -> E#entry.id; get(image, E) -> E#entry.image; get(link, E) -> E#entry.link; get(subtitle, E) -> E#entry.subtitle; get(summary, E) -> E#entry.summary; get(title, E) -> E#entry.title; get(updated, E) -> E#entry.updated.
null
https://raw.githubusercontent.com/michaelnisi/feeder/de2004cb954a5a70390a680e2cb0ed697dfcfd27/src/feeder_entries.erl
erlang
-module(feeder_entries). -include("feeder_records.hrl"). -export([get/2]). get(author, E) -> E#entry.author; get(categories, E) -> E#entry.categories; get(duration, E) -> E#entry.duration; get(enclosure, E) -> E#entry.enclosure; get(id, E) -> E#entry.id; get(image, E) -> E#entry.image; get(link, E) -> E#entry.link; get(subtitle, E) -> E#entry.subtitle; get(summary, E) -> E#entry.summary; get(title, E) -> E#entry.title; get(updated, E) -> E#entry.updated.
c787912b2379322e1fc5241333351a020297b42b2fed1e1ce7d0e859cba51ce3
AndrasKovacs/ELTE-func-lang
Gy04_pre.hs
# language InstanceSigs # # options_ghc -Wincomplete - patterns # module Orai.Gy04_pre where data SparseList a = Nil | Skip (SparseList a) | Cons a (SparseList a) deriving (Show) exampleList :: SparseList Char exampleList = Cons 's' (Cons 'a' (Skip (Cons 'j' (Skip (Cons 't' Nil))))) exampleList' :: SparseList Int exampleList' = Cons 1 (Skip (Cons 4 Nil)) data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show) exampleTree :: Tree String exampleTree = Node (Node (Leaf "the") (Leaf "cake")) (Node (Leaf "is") (Node (Leaf "a") (Leaf "lie"))) {- ∙ / \ / \ / \ ∙ \ / \ \ / \ \ "the" "cake" ∙ / \ / \ "is" ∙ / \ / \ "a" "lie" -} exampleTree' :: Tree Int exampleTree' = Node (Node (Leaf 2) (Leaf 3)) (Leaf 5) ∙ / \ ∙ 5 / \ 2 3 ∙ / \ ∙ 5 / \ 2 3 -} -- Foldable -------------------------------------------------------------------------------- -- class Foldable f where -- foldr :: (a -> b -> b) -> b -> f a -> b -- foldl -- foldMap -- ... instance Foldable SparseList where foldr :: (a -> b -> b) -> b -> SparseList a -> b foldr f z sl = undefined instance Foldable Tree where foldr :: (a -> b -> b) -> b -> Tree a -> b foldr f z t = undefined -- Maybe monád motiváló feladatok -------------------------------------------------------------------------------- Írd meg a . A függvény úgy működik , mint a lista " filter " , ha a kapott ( a - > Maybe ) függvény valamely elemre Nothing - ot ad , Nothing legyen a végeredmény , egyébként Just < szűrt lista > filterMaybe :: (a -> Maybe Bool) -> [a] -> Maybe [a] filterMaybe f as = undefined ( a - > Maybe b ) függvény egy Tree minden -- levelére, ha bármelyik alkalmazás Nothing-ot ad, legyen Nothing ! mapMaybeTree :: (a -> Maybe b) -> Tree a -> Maybe (Tree b) mapMaybeTree f t = undefined Alkalmazzuk páronként a kapott ( a - > b - > Maybe c ) függvényt a elemeire ! , a Nothing , egyébként Just < lista > . zipWithMaybe :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] zipWithMaybe f as bs = undefined Definiáld újra az előbbi Maybe monád instance használatával ! filterMaybe' :: (a -> Maybe Bool) -> [a] -> Maybe [a] filterMaybe' f as = undefined mapMaybeTree' :: (a -> Maybe b) -> Tree a -> Maybe (Tree b) mapMaybeTree' f t = undefined zipWithMaybe' :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] zipWithMaybe' f as bs = undefined -- IO monád -------------------------------------------------------------------------------- getLine : : IO String -- beolvas print : : Show a = > a - > IO ( ) -- -- putStrLn :: String -> IO () -- String-et nyomtat ki ( > > : IO a - > ( a - > IO b ) - > IO b -- return :: a -> IO a -- fmap :: (a -> b) -> IO a -> IO b Írj egy függvényt , sort , a sorban található ' a ' betűk számát ! io1 :: IO () io1 = undefined Írj egy függvényt , sort , majd a sort , ahány ! io2 :: IO () io2 = undefined Írj egy függvényt , be ismételten sorokat , amíg tartalmaz ' x ' karaktert . Ha a sorban ' x ' van , a program összes eddig beolvasott sort io3 :: IO () io3 = undefined A következőt : olvass be egy sort , a sorban a kisbetűk számát . A Ctrl - c - c -vel a futtatást -- ghci-ben. io4 :: IO () io4 = undefined Bónusz funktor feladatok -------------------------------------------------------------------------------- funzip :: Functor f => f (a, b) -> (f a, f b) funzip = undefined apply :: Functor f => f (a -> b) -> a -> f b apply = undefined first :: Functor f => (a -> f b) -> (a, c) -> f (b, c) first = undefined second :: Functor f => (a -> f b) -> (c, a) -> f (c, b) second = undefined data Sum f g a = Inl (f a) | Inr (g a) deriving Show data Product f g a = Product (f a) (g a) deriving Show newtype Compose f g a = Compose (f (g a)) deriving Show instance (Functor f, Functor g) => Functor (Sum f g) where fmap = undefined instance (Functor f, Functor g) => Functor (Product f g) where fmap = undefined instance (Functor f, Functor g) => Functor (Compose f g) where fmap = undefined bónusz bónusz : mire a függvény ? Tipp : a megoldáshoz rekurzió szükséges . löb :: Functor f => f (f a -> a) -> f a löb = undefined bónusz bónusz 2 : newtype Fix f = Fix (f (Fix f)) fold :: Functor f => (f a -> a) -> Fix f -> a fold = undefined
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/4379226df753916053774f95a482ce4b56c04ee0/2022-23-1/gyak3/Gy04_pre.hs
haskell
∙ / \ / \ / \ ∙ \ / \ \ / \ \ "the" "cake" ∙ / \ / \ "is" ∙ / \ / \ "a" "lie" Foldable ------------------------------------------------------------------------------ class Foldable f where foldr :: (a -> b -> b) -> b -> f a -> b foldl foldMap ... Maybe monád motiváló feladatok ------------------------------------------------------------------------------ levelére, ha bármelyik alkalmazás Nothing-ot ad, IO monád ------------------------------------------------------------------------------ beolvas putStrLn :: String -> IO () -- String-et nyomtat ki return :: a -> IO a fmap :: (a -> b) -> IO a -> IO b ghci-ben. ------------------------------------------------------------------------------
# language InstanceSigs # # options_ghc -Wincomplete - patterns # module Orai.Gy04_pre where data SparseList a = Nil | Skip (SparseList a) | Cons a (SparseList a) deriving (Show) exampleList :: SparseList Char exampleList = Cons 's' (Cons 'a' (Skip (Cons 'j' (Skip (Cons 't' Nil))))) exampleList' :: SparseList Int exampleList' = Cons 1 (Skip (Cons 4 Nil)) data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show) exampleTree :: Tree String exampleTree = Node (Node (Leaf "the") (Leaf "cake")) (Node (Leaf "is") (Node (Leaf "a") (Leaf "lie"))) exampleTree' :: Tree Int exampleTree' = Node (Node (Leaf 2) (Leaf 3)) (Leaf 5) ∙ / \ ∙ 5 / \ 2 3 ∙ / \ ∙ 5 / \ 2 3 -} instance Foldable SparseList where foldr :: (a -> b -> b) -> b -> SparseList a -> b foldr f z sl = undefined instance Foldable Tree where foldr :: (a -> b -> b) -> b -> Tree a -> b foldr f z t = undefined Írd meg a . A függvény úgy működik , mint a lista " filter " , ha a kapott ( a - > Maybe ) függvény valamely elemre Nothing - ot ad , Nothing legyen a végeredmény , egyébként Just < szűrt lista > filterMaybe :: (a -> Maybe Bool) -> [a] -> Maybe [a] filterMaybe f as = undefined ( a - > Maybe b ) függvény egy Tree minden legyen Nothing ! mapMaybeTree :: (a -> Maybe b) -> Tree a -> Maybe (Tree b) mapMaybeTree f t = undefined Alkalmazzuk páronként a kapott ( a - > b - > Maybe c ) függvényt a elemeire ! , a Nothing , egyébként Just < lista > . zipWithMaybe :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] zipWithMaybe f as bs = undefined Definiáld újra az előbbi Maybe monád instance használatával ! filterMaybe' :: (a -> Maybe Bool) -> [a] -> Maybe [a] filterMaybe' f as = undefined mapMaybeTree' :: (a -> Maybe b) -> Tree a -> Maybe (Tree b) mapMaybeTree' f t = undefined zipWithMaybe' :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] zipWithMaybe' f as bs = undefined ( > > : IO a - > ( a - > IO b ) - > IO b Írj egy függvényt , sort , a sorban található ' a ' betűk számát ! io1 :: IO () io1 = undefined Írj egy függvényt , sort , majd a sort , ahány ! io2 :: IO () io2 = undefined Írj egy függvényt , be ismételten sorokat , amíg tartalmaz ' x ' karaktert . Ha a sorban ' x ' van , a program összes eddig beolvasott sort io3 :: IO () io3 = undefined A következőt : olvass be egy sort , a sorban a kisbetűk számát . A Ctrl - c - c -vel a futtatást io4 :: IO () io4 = undefined Bónusz funktor feladatok funzip :: Functor f => f (a, b) -> (f a, f b) funzip = undefined apply :: Functor f => f (a -> b) -> a -> f b apply = undefined first :: Functor f => (a -> f b) -> (a, c) -> f (b, c) first = undefined second :: Functor f => (a -> f b) -> (c, a) -> f (c, b) second = undefined data Sum f g a = Inl (f a) | Inr (g a) deriving Show data Product f g a = Product (f a) (g a) deriving Show newtype Compose f g a = Compose (f (g a)) deriving Show instance (Functor f, Functor g) => Functor (Sum f g) where fmap = undefined instance (Functor f, Functor g) => Functor (Product f g) where fmap = undefined instance (Functor f, Functor g) => Functor (Compose f g) where fmap = undefined bónusz bónusz : mire a függvény ? Tipp : a megoldáshoz rekurzió szükséges . löb :: Functor f => f (f a -> a) -> f a löb = undefined bónusz bónusz 2 : newtype Fix f = Fix (f (Fix f)) fold :: Functor f => (f a -> a) -> Fix f -> a fold = undefined
738621fdbc102760fcc0a6a00f28b34fa76c4613c169b06760c5e1286bacdd2d
racketscript/racketscript
import-renamed.rkt
#lang racket (require "private/renamed-out.rkt") (say-hello "Hello World!")
null
https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/modules/import-renamed.rkt
racket
#lang racket (require "private/renamed-out.rkt") (say-hello "Hello World!")
4955aed2ea38611cec1cd956022c3be362d273d67568690a0dbbc565ce024f49
sockjs/sockjs-erlang
sockjs.erl
-module(sockjs). -export([send/2, close/1, close/3, info/1]). -type(conn() :: {sockjs_session, any()}). %% Send data over a connection. -spec send(iodata(), conn()) -> ok. send(Data, Conn = {sockjs_session, _}) -> sockjs_session:send(Data, Conn). %% Initiate a close of a connection. -spec close(conn()) -> ok. close(Conn) -> close(1000, "Normal closure", Conn). -spec close(non_neg_integer(), string(), conn()) -> ok. close(Code, Reason, Conn = {sockjs_session, _}) -> sockjs_session:close(Code, Reason, Conn). -spec info(conn()) -> [{atom(), any()}]. info(Conn = {sockjs_session, _}) -> sockjs_session:info(Conn).
null
https://raw.githubusercontent.com/sockjs/sockjs-erlang/66ea7f3fabac8d0f66aa88a354577b7c6be8fe9a/src/sockjs.erl
erlang
Send data over a connection. Initiate a close of a connection.
-module(sockjs). -export([send/2, close/1, close/3, info/1]). -type(conn() :: {sockjs_session, any()}). -spec send(iodata(), conn()) -> ok. send(Data, Conn = {sockjs_session, _}) -> sockjs_session:send(Data, Conn). -spec close(conn()) -> ok. close(Conn) -> close(1000, "Normal closure", Conn). -spec close(non_neg_integer(), string(), conn()) -> ok. close(Code, Reason, Conn = {sockjs_session, _}) -> sockjs_session:close(Code, Reason, Conn). -spec info(conn()) -> [{atom(), any()}]. info(Conn = {sockjs_session, _}) -> sockjs_session:info(Conn).
9c48a6ec55f5fbc642e42440ece8f385d0dadb15b0c237ca3af210912d6128e1
atzeus/FRPNow
Time.hs
# LANGUAGE TupleSections , TypeOperators , MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances # ----------------------------------------------------------------------------- -- | -- Module : Control.FRPNow.Time Copyright : ( c ) 2015 -- License : BSD-style -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Various utility functions for FRPNow related to the passing of time. -- All take a "clock" as an argument, i.e. a behavior that gives the seconds since the program started . -- -- The clock itself is created by a function specialized to the GUI library you are using FRP with such as ' Control . FRPNow . ' module Control.FRPNow.Time(localTime,timeFrac, lastInputs, bufferBehavior,delayBy, delayByN, delayTime, integrate, VectorSpace(..)) where import Control.FRPNow.Core import Control.FRPNow.Lib import Control.FRPNow.EvStream import Data.Sequence import Control.Applicative hiding (empty) import Data.Foldable import Debug.Trace -- | When sampled at time t, gives the time since time t localTime :: (Floating time, Ord time) => Behavior time -> Behavior (Behavior time) localTime t = do n <- t return ((\x -> x - n) <$> t) | Gives a behavior that linearly increases from 0 to 1 in the specified duration timeFrac :: (Floating time, Ord time) => Behavior time -> time -> Behavior (Behavior time) timeFrac t d = do t' <- localTime t e <- when $ (>= d) <$> t' let frac = (\x -> min 1.0 (x / d)) <$> t' return (frac `switch` (pure 1.0 <$ e)) -- | Tag the events in a stream with their time tagTime :: (Floating time, Ord time) => Behavior time -> EvStream a -> EvStream (time,a) tagTime c s = ((,) <$> c) <@@> s | Gives a behavior containing the values of the events in the stream that occurred in the last n seconds lastInputs :: (Floating time, Ord time) => Behavior time -- ^ The "clock" behavior, the behavior monotonically increases with time -> time -- ^ The duration of the history to be kept -> EvStream a -- ^ The input stream -> Behavior (Behavior [a]) lastInputs clock dur s = do s' <- bufferStream clock dur s bs <- fromChanges [] s' let dropIt cur s = dropWhile (\(t,_) -> t + dur < cur) s return $ (fmap snd) <$> (dropIt <$> clock <*> bs) bufferStream :: (Floating time, Ord time) => Behavior time -> time -> EvStream a -> Behavior (EvStream [(time,a)]) bufferStream clock dur s = do s' <- scanlEv addDrop empty $ tagTime clock s return $ toList <$> s' where addDrop ss s@(last,v) = dropWhileL (\(tn,_) -> tn + dur < last) (ss |> s) data TimeTag t a = TimeTag t a instance Eq t => Eq (TimeTag t a) where (TimeTag t1 _) == (TimeTag t2 _) = t1 == t2 | Gives a behavior containing the values of the behavior during the last n seconds , with time stamps bufferBehavior :: (Floating time, Ord time) => Behavior time -- ^ The "clock" behavior, the behavior monotonically increases with time -> time -- ^ The duration of the history to be kept -> Behavior a -- ^ The input behavior -> Behavior (Behavior [(time,a)]) bufferBehavior clock dur b = fmap toList <$> foldB update empty (TimeTag <$> clock <*> b) where update l (TimeTag now x) = trimList (l |> (now,x)) (now - dur) trimList l after = loop l where loop l = case viewl l of EmptyL -> empty (t1,v1) :< tail1 | after <= t1 -> l | otherwise -> case viewl tail1 of (t2,v2) :< tail2 | t2 <= after -> loop tail2 | otherwise -> l | Give a version of the behavior delayed by n seconds delayBy :: (Floating time, Ord time) => Behavior time -- ^ The "clock" behavior, the behavior monotonically increases with time -> time -- ^ The duration of the delay -> Behavior a -- ^ The input behavior -> Behavior (Behavior a) delayBy time d b = fmap (snd . head) <$> bufferBehavior time d b -- | Give n delayed versions of the behavior, each with the given duration in delay between them. delayByN :: (Floating time, Ord time) => Behavior time -- ^ The "clock" behavior, the behavior monotonically increases with time -> time -- ^ The duration _between_ delayed versions -> Integer -- ^ The number of delayed versions -> Behavior a -- ^ The input behavior -> Behavior (Behavior [a]) delayByN clock dur n b = let durN = (fromIntegral n) * dur in do samples <- bufferBehavior clock durN b return $ interpolateFromList <$> clock <*> samples where interpolateFromList now l= loop (n - 1) l where loop n l = if n < 0 then [] else let sampleTime = now - (fromIntegral n * dur) in case l of [] -> [] [(_,v)] -> v : loop (n-1) l ((t1,v1) : (t2,v2) : rest) | sampleTime >= t2 -> loop n ((t2,v2) : rest) | otherwise -> v1 : loop (n-1) l -- | Integration using rectangle rule approximation. Integration depends on when we start integrating so the result is @Behavior (Behavior v)@. integrate :: (VectorSpace v time) => Behavior time -> Behavior v -> Behavior (Behavior v) integrate time v = do t <- time vp <- delayTime time (t,zeroVector) ((,) <$> time <*> v) foldB add zeroVector $ (,) <$> vp <*> time where add total ((t1,v),t2) = total ^+^ ((t2 - t1) *^ v) | Delay a behavior by one tick of the clock . Occasionally useful to prevent immediate feedback loops . Like ' Control.FRPNow.EvStream.delay ' , but uses the changes of the clock as an event stream . delayTime :: Eq time => Behavior time -> a -> Behavior a -> Behavior (Behavior a) delayTime time i b = loop i where loop i = do e <- futuristic $ do (t,cur) <- (,) <$> time <*> b e <- when ((/= t) <$> time) return (cur <$ e) e' <- plan ( loop <$> e) return (i `step` e') infixr *^ infixl ^/ infix 7 `dot` infixl 6 ^+^, ^-^ | A type class for vector spaces . Stolen from Yampa . Thanks :) -- Minimal instance: zeroVector, (*^), (^+^), dot class (Eq a, Eq v, Ord v, Ord a, Floating a) => VectorSpace v a | v -> a where zeroVector :: v (*^) :: a -> v -> v (^/) :: v -> a -> v negateVector :: v -> v (^+^) :: v -> v -> v (^-^) :: v -> v -> v dot :: v -> v -> a norm :: v -> a normalize :: v -> v v ^/ a = (1/a) *^ v negateVector v = (-1) *^ v v1 ^-^ v2 = v1 ^+^ negateVector v2 norm v = sqrt (v `dot` v) normalize v = if nv /= 0 then v ^/ nv else error "normalize: zero vector" where nv = norm v ------------------------------------------------------------------------------ -- Vector space instances for Float and Double ------------------------------------------------------------------------------ instance VectorSpace Float Float where zeroVector = 0 a *^ x = a * x x ^/ a = x / a negateVector x = (-x) x1 ^+^ x2 = x1 + x2 x1 ^-^ x2 = x1 - x2 x1 `dot` x2 = x1 * x2 instance VectorSpace Double Double where zeroVector = 0 a *^ x = a * x x ^/ a = x / a negateVector x = (-x) x1 ^+^ x2 = x1 + x2 x1 ^-^ x2 = x1 - x2 x1 `dot` x2 = x1 * x2 ------------------------------------------------------------------------------ -- Vector space instances for small tuples of Floating ------------------------------------------------------------------------------ instance (Eq a, Floating a, Ord a) => VectorSpace (a,a) a where zeroVector = (0,0) a *^ (x,y) = (a * x, a * y) (x,y) ^/ a = (x / a, y / a) negateVector (x,y) = (-x, -y) (x1,y1) ^+^ (x2,y2) = (x1 + x2, y1 + y2) (x1,y1) ^-^ (x2,y2) = (x1 - x2, y1 - y2) (x1,y1) `dot` (x2,y2) = x1 * x2 + y1 * y2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a) a where zeroVector = (0,0,0) a *^ (x,y,z) = (a * x, a * y, a * z) (x,y,z) ^/ a = (x / a, y / a, z / a) negateVector (x,y,z) = (-x, -y, -z) (x1,y1,z1) ^+^ (x2,y2,z2) = (x1+x2, y1+y2, z1+z2) (x1,y1,z1) ^-^ (x2,y2,z2) = (x1-x2, y1-y2, z1-z2) (x1,y1,z1) `dot` (x2,y2,z2) = x1 * x2 + y1 * y2 + z1 * z2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a,a) a where zeroVector = (0,0,0,0) a *^ (x,y,z,u) = (a * x, a * y, a * z, a * u) (x,y,z,u) ^/ a = (x / a, y / a, z / a, u / a) negateVector (x,y,z,u) = (-x, -y, -z, -u) (x1,y1,z1,u1) ^+^ (x2,y2,z2,u2) = (x1+x2, y1+y2, z1+z2, u1+u2) (x1,y1,z1,u1) ^-^ (x2,y2,z2,u2) = (x1-x2, y1-y2, z1-z2, u1-u2) (x1,y1,z1,u1) `dot` (x2,y2,z2,u2) = x1 * x2 + y1 * y2 + z1 * z2 + u1 * u2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a,a,a) a where zeroVector = (0,0,0,0,0) a *^ (x,y,z,u,v) = (a * x, a * y, a * z, a * u, a * v) (x,y,z,u,v) ^/ a = (x / a, y / a, z / a, u / a, v / a) negateVector (x,y,z,u,v) = (-x, -y, -z, -u, -v) (x1,y1,z1,u1,v1) ^+^ (x2,y2,z2,u2,v2) = (x1+x2, y1+y2, z1+z2, u1+u2, v1+v2) (x1,y1,z1,u1,v1) ^-^ (x2,y2,z2,u2,v2) = (x1-x2, y1-y2, z1-z2, u1-u2, v1-v2) (x1,y1,z1,u1,v1) `dot` (x2,y2,z2,u2,v2) = x1 * x2 + y1 * y2 + z1 * z2 + u1 * u2 + v1 * v2
null
https://raw.githubusercontent.com/atzeus/FRPNow/58073b88dfd725eab6851a75b4c9f01f9d3f97d2/Control/FRPNow/Time.hs
haskell
--------------------------------------------------------------------------- | Module : Control.FRPNow.Time License : BSD-style Maintainer : Stability : provisional Portability : portable Various utility functions for FRPNow related to the passing of time. All take a "clock" as an argument, i.e. a behavior that The clock itself is created by a function specialized to the | When sampled at time t, gives the time since time t | Tag the events in a stream with their time ^ The "clock" behavior, the behavior monotonically increases with time ^ The duration of the history to be kept ^ The input stream ^ The "clock" behavior, the behavior monotonically increases with time ^ The duration of the history to be kept ^ The input behavior ^ The "clock" behavior, the behavior monotonically increases with time ^ The duration of the delay ^ The input behavior | Give n delayed versions of the behavior, each with the given duration in delay between them. ^ The "clock" behavior, the behavior monotonically increases with time ^ The duration _between_ delayed versions ^ The number of delayed versions ^ The input behavior | Integration using rectangle rule approximation. Integration depends on when we start integrating so the result is @Behavior (Behavior v)@. Minimal instance: zeroVector, (*^), (^+^), dot ---------------------------------------------------------------------------- Vector space instances for Float and Double ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Vector space instances for small tuples of Floating ----------------------------------------------------------------------------
# LANGUAGE TupleSections , TypeOperators , MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances # Copyright : ( c ) 2015 gives the seconds since the program started . GUI library you are using FRP with such as ' Control . FRPNow . ' module Control.FRPNow.Time(localTime,timeFrac, lastInputs, bufferBehavior,delayBy, delayByN, delayTime, integrate, VectorSpace(..)) where import Control.FRPNow.Core import Control.FRPNow.Lib import Control.FRPNow.EvStream import Data.Sequence import Control.Applicative hiding (empty) import Data.Foldable import Debug.Trace localTime :: (Floating time, Ord time) => Behavior time -> Behavior (Behavior time) localTime t = do n <- t return ((\x -> x - n) <$> t) | Gives a behavior that linearly increases from 0 to 1 in the specified duration timeFrac :: (Floating time, Ord time) => Behavior time -> time -> Behavior (Behavior time) timeFrac t d = do t' <- localTime t e <- when $ (>= d) <$> t' let frac = (\x -> min 1.0 (x / d)) <$> t' return (frac `switch` (pure 1.0 <$ e)) tagTime :: (Floating time, Ord time) => Behavior time -> EvStream a -> EvStream (time,a) tagTime c s = ((,) <$> c) <@@> s | Gives a behavior containing the values of the events in the stream that occurred in the last n seconds lastInputs :: (Floating time, Ord time) => -> Behavior (Behavior [a]) lastInputs clock dur s = do s' <- bufferStream clock dur s bs <- fromChanges [] s' let dropIt cur s = dropWhile (\(t,_) -> t + dur < cur) s return $ (fmap snd) <$> (dropIt <$> clock <*> bs) bufferStream :: (Floating time, Ord time) => Behavior time -> time -> EvStream a -> Behavior (EvStream [(time,a)]) bufferStream clock dur s = do s' <- scanlEv addDrop empty $ tagTime clock s return $ toList <$> s' where addDrop ss s@(last,v) = dropWhileL (\(tn,_) -> tn + dur < last) (ss |> s) data TimeTag t a = TimeTag t a instance Eq t => Eq (TimeTag t a) where (TimeTag t1 _) == (TimeTag t2 _) = t1 == t2 | Gives a behavior containing the values of the behavior during the last n seconds , with time stamps bufferBehavior :: (Floating time, Ord time) => -> Behavior (Behavior [(time,a)]) bufferBehavior clock dur b = fmap toList <$> foldB update empty (TimeTag <$> clock <*> b) where update l (TimeTag now x) = trimList (l |> (now,x)) (now - dur) trimList l after = loop l where loop l = case viewl l of EmptyL -> empty (t1,v1) :< tail1 | after <= t1 -> l | otherwise -> case viewl tail1 of (t2,v2) :< tail2 | t2 <= after -> loop tail2 | otherwise -> l | Give a version of the behavior delayed by n seconds delayBy :: (Floating time, Ord time) => -> Behavior (Behavior a) delayBy time d b = fmap (snd . head) <$> bufferBehavior time d b delayByN :: (Floating time, Ord time) => -> Behavior (Behavior [a]) delayByN clock dur n b = let durN = (fromIntegral n) * dur in do samples <- bufferBehavior clock durN b return $ interpolateFromList <$> clock <*> samples where interpolateFromList now l= loop (n - 1) l where loop n l = if n < 0 then [] else let sampleTime = now - (fromIntegral n * dur) in case l of [] -> [] [(_,v)] -> v : loop (n-1) l ((t1,v1) : (t2,v2) : rest) | sampleTime >= t2 -> loop n ((t2,v2) : rest) | otherwise -> v1 : loop (n-1) l integrate :: (VectorSpace v time) => Behavior time -> Behavior v -> Behavior (Behavior v) integrate time v = do t <- time vp <- delayTime time (t,zeroVector) ((,) <$> time <*> v) foldB add zeroVector $ (,) <$> vp <*> time where add total ((t1,v),t2) = total ^+^ ((t2 - t1) *^ v) | Delay a behavior by one tick of the clock . Occasionally useful to prevent immediate feedback loops . Like ' Control.FRPNow.EvStream.delay ' , but uses the changes of the clock as an event stream . delayTime :: Eq time => Behavior time -> a -> Behavior a -> Behavior (Behavior a) delayTime time i b = loop i where loop i = do e <- futuristic $ do (t,cur) <- (,) <$> time <*> b e <- when ((/= t) <$> time) return (cur <$ e) e' <- plan ( loop <$> e) return (i `step` e') infixr *^ infixl ^/ infix 7 `dot` infixl 6 ^+^, ^-^ | A type class for vector spaces . Stolen from Yampa . Thanks :) class (Eq a, Eq v, Ord v, Ord a, Floating a) => VectorSpace v a | v -> a where zeroVector :: v (*^) :: a -> v -> v (^/) :: v -> a -> v negateVector :: v -> v (^+^) :: v -> v -> v (^-^) :: v -> v -> v dot :: v -> v -> a norm :: v -> a normalize :: v -> v v ^/ a = (1/a) *^ v negateVector v = (-1) *^ v v1 ^-^ v2 = v1 ^+^ negateVector v2 norm v = sqrt (v `dot` v) normalize v = if nv /= 0 then v ^/ nv else error "normalize: zero vector" where nv = norm v instance VectorSpace Float Float where zeroVector = 0 a *^ x = a * x x ^/ a = x / a negateVector x = (-x) x1 ^+^ x2 = x1 + x2 x1 ^-^ x2 = x1 - x2 x1 `dot` x2 = x1 * x2 instance VectorSpace Double Double where zeroVector = 0 a *^ x = a * x x ^/ a = x / a negateVector x = (-x) x1 ^+^ x2 = x1 + x2 x1 ^-^ x2 = x1 - x2 x1 `dot` x2 = x1 * x2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a) a where zeroVector = (0,0) a *^ (x,y) = (a * x, a * y) (x,y) ^/ a = (x / a, y / a) negateVector (x,y) = (-x, -y) (x1,y1) ^+^ (x2,y2) = (x1 + x2, y1 + y2) (x1,y1) ^-^ (x2,y2) = (x1 - x2, y1 - y2) (x1,y1) `dot` (x2,y2) = x1 * x2 + y1 * y2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a) a where zeroVector = (0,0,0) a *^ (x,y,z) = (a * x, a * y, a * z) (x,y,z) ^/ a = (x / a, y / a, z / a) negateVector (x,y,z) = (-x, -y, -z) (x1,y1,z1) ^+^ (x2,y2,z2) = (x1+x2, y1+y2, z1+z2) (x1,y1,z1) ^-^ (x2,y2,z2) = (x1-x2, y1-y2, z1-z2) (x1,y1,z1) `dot` (x2,y2,z2) = x1 * x2 + y1 * y2 + z1 * z2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a,a) a where zeroVector = (0,0,0,0) a *^ (x,y,z,u) = (a * x, a * y, a * z, a * u) (x,y,z,u) ^/ a = (x / a, y / a, z / a, u / a) negateVector (x,y,z,u) = (-x, -y, -z, -u) (x1,y1,z1,u1) ^+^ (x2,y2,z2,u2) = (x1+x2, y1+y2, z1+z2, u1+u2) (x1,y1,z1,u1) ^-^ (x2,y2,z2,u2) = (x1-x2, y1-y2, z1-z2, u1-u2) (x1,y1,z1,u1) `dot` (x2,y2,z2,u2) = x1 * x2 + y1 * y2 + z1 * z2 + u1 * u2 instance (Eq a, Floating a, Ord a) => VectorSpace (a,a,a,a,a) a where zeroVector = (0,0,0,0,0) a *^ (x,y,z,u,v) = (a * x, a * y, a * z, a * u, a * v) (x,y,z,u,v) ^/ a = (x / a, y / a, z / a, u / a, v / a) negateVector (x,y,z,u,v) = (-x, -y, -z, -u, -v) (x1,y1,z1,u1,v1) ^+^ (x2,y2,z2,u2,v2) = (x1+x2, y1+y2, z1+z2, u1+u2, v1+v2) (x1,y1,z1,u1,v1) ^-^ (x2,y2,z2,u2,v2) = (x1-x2, y1-y2, z1-z2, u1-u2, v1-v2) (x1,y1,z1,u1,v1) `dot` (x2,y2,z2,u2,v2) = x1 * x2 + y1 * y2 + z1 * z2 + u1 * u2 + v1 * v2
de11bde8ffa417a69a9349e0af552cdb7839b9915e24df2ea4742c51c0470378
gsakkas/rite
2053.ml
let rec assoc (d,k,l) = let rec helper (a,b,c) = match c with | [] -> a | (n,v)::t -> if n = c then v else helper (a, b, t) in helper (d, k, l);; (* fix let rec assoc (d,k,l) = let rec helper (a,b,c) = match c with | [] -> a | (n,v)::t -> if n = b then v else helper (a, b, t) in helper (d, k, l);; *) changed spans ( 6,26)-(6,27 ) b VarG (6,26)-(6,27) b VarG *) type error slice ( 4,5)-(6,56 ) ( 4,11)-(4,12 ) ( 6,22)-(6,23 ) ( 6,22)-(6,27 ) ( 6,26)-(6,27 ) (4,5)-(6,56) (4,11)-(4,12) (6,22)-(6,23) (6,22)-(6,27) (6,26)-(6,27) *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/2053.ml
ocaml
fix let rec assoc (d,k,l) = let rec helper (a,b,c) = match c with | [] -> a | (n,v)::t -> if n = b then v else helper (a, b, t) in helper (d, k, l);;
let rec assoc (d,k,l) = let rec helper (a,b,c) = match c with | [] -> a | (n,v)::t -> if n = c then v else helper (a, b, t) in helper (d, k, l);; changed spans ( 6,26)-(6,27 ) b VarG (6,26)-(6,27) b VarG *) type error slice ( 4,5)-(6,56 ) ( 4,11)-(4,12 ) ( 6,22)-(6,23 ) ( 6,22)-(6,27 ) ( 6,26)-(6,27 ) (4,5)-(6,56) (4,11)-(4,12) (6,22)-(6,23) (6,22)-(6,27) (6,26)-(6,27) *)
b99fae37274adc3f55315a9b4dd7df54f5d1cd5d5b312d49c7a089d5e9fa41f4
HugoPeters1024/hs-sleuth
Utf8.hs
# LANGUAGE CPP , MagicHash , BangPatterns # -- | -- Module : Data.Text.Internal.Encoding.Utf8 Copyright : ( c ) 2008 , 2009 , ( c ) 2009 , 2010 , ( c ) 2009 -- -- License : BSD-style -- Maintainer : -- Stability : experimental Portability : GHC -- -- /Warning/: this is an internal module, and does not have a stable -- API or name. Functions in this module may not check or enforce -- preconditions expected by public modules. Use at your own risk! -- -- Basic UTF-8 validation and character manipulation. module Data.Text.Internal.Encoding.Utf8 ( -- Decomposition ord2 , ord3 , ord4 -- Construction , chr2 , chr3 , chr4 -- * Validation , validate1 , validate2 , validate3 , validate4 ) where #if defined(TEST_SUITE) # undef ASSERTS #endif #if defined(ASSERTS) import Control.Exception (assert) #endif import Data.Bits ((.&.)) import Data.Text.Internal.Unsafe.Char (ord) import Data.Text.Internal.Unsafe.Shift (shiftR) import GHC.Exts import GHC.Word (Word8(..)) default(Int) between :: Word8 -- ^ byte to check -> Word8 -- ^ lower bound -> Word8 -- ^ upper bound -> Bool between x y z = x >= y && x <= z # INLINE between # ord2 :: Char -> (Word8,Word8) ord2 c = #if defined(ASSERTS) assert (n >= 0x80 && n <= 0x07ff) #endif (x1,x2) where n = ord c x1 = fromIntegral $ (n `shiftR` 6) + 0xC0 x2 = fromIntegral $ (n .&. 0x3F) + 0x80 ord3 :: Char -> (Word8,Word8,Word8) ord3 c = #if defined(ASSERTS) assert (n >= 0x0800 && n <= 0xffff) #endif (x1,x2,x3) where n = ord c x1 = fromIntegral $ (n `shiftR` 12) + 0xE0 x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x3 = fromIntegral $ (n .&. 0x3F) + 0x80 ord4 :: Char -> (Word8,Word8,Word8,Word8) ord4 c = #if defined(ASSERTS) assert (n >= 0x10000) #endif (x1,x2,x3,x4) where n = ord c x1 = fromIntegral $ (n `shiftR` 18) + 0xF0 x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80 x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x4 = fromIntegral $ (n .&. 0x3F) + 0x80 chr2 :: Word8 -> Word8 -> Char chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6# !z2# = y2# -# 0x80# # INLINE chr2 # chr3 :: Word8 -> Word8 -> Word8 -> Char chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 6# !z3# = y3# -# 0x80# # INLINE chr3 # chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) = C# (chr# (z1# +# z2# +# z3# +# z4#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !y4# = word2Int# x4# !z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 12# !z3# = uncheckedIShiftL# (y3# -# 0x80#) 6# !z4# = y4# -# 0x80# # INLINE chr4 # validate1 :: Word8 -> Bool validate1 x1 = x1 <= 0x7F # INLINE validate1 # validate2 :: Word8 -> Word8 -> Bool validate2 x1 x2 = between x1 0xC2 0xDF && between x2 0x80 0xBF # INLINE validate2 # validate3 :: Word8 -> Word8 -> Word8 -> Bool # INLINE validate3 # validate3 x1 x2 x3 = validate3_1 || validate3_2 || validate3_3 || validate3_4 where validate3_1 = (x1 == 0xE0) && between x2 0xA0 0xBF && between x3 0x80 0xBF validate3_2 = between x1 0xE1 0xEC && between x2 0x80 0xBF && between x3 0x80 0xBF validate3_3 = x1 == 0xED && between x2 0x80 0x9F && between x3 0x80 0xBF validate3_4 = between x1 0xEE 0xEF && between x2 0x80 0xBF && between x3 0x80 0xBF validate4 :: Word8 -> Word8 -> Word8 -> Word8 -> Bool # INLINE validate4 # validate4 x1 x2 x3 x4 = validate4_1 || validate4_2 || validate4_3 where validate4_1 = x1 == 0xF0 && between x2 0x90 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_2 = between x1 0xF1 0xF3 && between x2 0x80 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_3 = x1 == 0xF4 && between x2 0x80 0x8F && between x3 0x80 0xBF && between x4 0x80 0xBF
null
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/385655e62031959a14a3bac5e9ccd1c42c045f0c/test-project/text-1.2.4.0/Data/Text/Internal/Encoding/Utf8.hs
haskell
| Module : Data.Text.Internal.Encoding.Utf8 License : BSD-style Maintainer : Stability : experimental /Warning/: this is an internal module, and does not have a stable API or name. Functions in this module may not check or enforce preconditions expected by public modules. Use at your own risk! Basic UTF-8 validation and character manipulation. Decomposition Construction * Validation ^ byte to check ^ lower bound ^ upper bound
# LANGUAGE CPP , MagicHash , BangPatterns # Copyright : ( c ) 2008 , 2009 , ( c ) 2009 , 2010 , ( c ) 2009 Portability : GHC module Data.Text.Internal.Encoding.Utf8 ( ord2 , ord3 , ord4 , chr2 , chr3 , chr4 , validate1 , validate2 , validate3 , validate4 ) where #if defined(TEST_SUITE) # undef ASSERTS #endif #if defined(ASSERTS) import Control.Exception (assert) #endif import Data.Bits ((.&.)) import Data.Text.Internal.Unsafe.Char (ord) import Data.Text.Internal.Unsafe.Shift (shiftR) import GHC.Exts import GHC.Word (Word8(..)) default(Int) -> Bool between x y z = x >= y && x <= z # INLINE between # ord2 :: Char -> (Word8,Word8) ord2 c = #if defined(ASSERTS) assert (n >= 0x80 && n <= 0x07ff) #endif (x1,x2) where n = ord c x1 = fromIntegral $ (n `shiftR` 6) + 0xC0 x2 = fromIntegral $ (n .&. 0x3F) + 0x80 ord3 :: Char -> (Word8,Word8,Word8) ord3 c = #if defined(ASSERTS) assert (n >= 0x0800 && n <= 0xffff) #endif (x1,x2,x3) where n = ord c x1 = fromIntegral $ (n `shiftR` 12) + 0xE0 x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x3 = fromIntegral $ (n .&. 0x3F) + 0x80 ord4 :: Char -> (Word8,Word8,Word8,Word8) ord4 c = #if defined(ASSERTS) assert (n >= 0x10000) #endif (x1,x2,x3,x4) where n = ord c x1 = fromIntegral $ (n `shiftR` 18) + 0xF0 x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80 x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x4 = fromIntegral $ (n .&. 0x3F) + 0x80 chr2 :: Word8 -> Word8 -> Char chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6# !z2# = y2# -# 0x80# # INLINE chr2 # chr3 :: Word8 -> Word8 -> Word8 -> Char chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 6# !z3# = y3# -# 0x80# # INLINE chr3 # chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) = C# (chr# (z1# +# z2# +# z3# +# z4#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !y4# = word2Int# x4# !z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 12# !z3# = uncheckedIShiftL# (y3# -# 0x80#) 6# !z4# = y4# -# 0x80# # INLINE chr4 # validate1 :: Word8 -> Bool validate1 x1 = x1 <= 0x7F # INLINE validate1 # validate2 :: Word8 -> Word8 -> Bool validate2 x1 x2 = between x1 0xC2 0xDF && between x2 0x80 0xBF # INLINE validate2 # validate3 :: Word8 -> Word8 -> Word8 -> Bool # INLINE validate3 # validate3 x1 x2 x3 = validate3_1 || validate3_2 || validate3_3 || validate3_4 where validate3_1 = (x1 == 0xE0) && between x2 0xA0 0xBF && between x3 0x80 0xBF validate3_2 = between x1 0xE1 0xEC && between x2 0x80 0xBF && between x3 0x80 0xBF validate3_3 = x1 == 0xED && between x2 0x80 0x9F && between x3 0x80 0xBF validate3_4 = between x1 0xEE 0xEF && between x2 0x80 0xBF && between x3 0x80 0xBF validate4 :: Word8 -> Word8 -> Word8 -> Word8 -> Bool # INLINE validate4 # validate4 x1 x2 x3 x4 = validate4_1 || validate4_2 || validate4_3 where validate4_1 = x1 == 0xF0 && between x2 0x90 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_2 = between x1 0xF1 0xF3 && between x2 0x80 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_3 = x1 == 0xF4 && between x2 0x80 0x8F && between x3 0x80 0xBF && between x4 0x80 0xBF
ab02ad6cbe7262b3fd9e5447cd09e8fd91a72298220efbab557b4f8861445930
tommaisey/aeon
amp-comp-a.help.scm
( amp - compA freq root rootAmp ) ;; ANSI A-weighting curve. ;; Basic psychoacoustic amplitude compensation ;; Higher frequencies are normally perceived as louder, which amp-compA compensates . Following the measurings by Fletcher and , the ;; ANSI standard describes a function for loudness vs. frequency. ;; Note that this curve is only valid for standardized amplitude. ;; For a simpler but more flexible curve, see amp-comp. ;; freq - input frequency value. For freq == root, the output is ;; rootAmp. (default freq 0 Hz) ;; root - root freq relative to which the curve is calculated (usually ;; lowest freq) (default 0 Hz) default value: C (60.midicps) ;; minAmp - amplitude at the minimum point of the curve (around 2512 ;; Hz) (default -10dB) rootAmp - amplitude at the root frequency . ( default 1 ) apart from freq , the values are not ;; compare a sine without compensation with one that uses amplitude ;; compensation (let* ((x (mouse-x kr 300 15000 1 0.1)) (y (mouse-y kr 0 1 0 0.1)) (o (mul (sin-osc ar x 0) 0.1)) (c (amp-comp-a x 300 (db-amp -10) 1))) (audition (out 0 (mce2 (mul o y) (mul3 o (sub 1 y) c))))) ;; adjust the minimum and root amp (in this way one can flatten out ;; the curve for higher amplitudes) (let* ((x (mouse-x kr 300 18000 1 0.1)) (y (mouse-y kr 0 1 0 0.1)) (o (mul (formant ar 300 x 20) 0.1)) (c (amp-comp-a x 300 0.6 0.3))) (audition (out 0 (mce2 (mul o y) (mul3 o (sub 1 y) c))))) ;; amplitude compensation in frequency modulation (using Fletscher - Munson curve ) (let* ((x (mouse-x kr 300 15000 1 0.1)) (y (mouse-y kr 3 200 1 0.1)) (m (mul x (mul-add (sin-osc ar y 0) 0.5 1))) (a (amp-comp-a m 300 (db-amp -10) 1)) (c (mul3 (sin-osc ar m 0) 0.1 a))) (audition (out 0 c)))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/filters/amp-comp-a.help.scm
scheme
ANSI A-weighting curve. Basic psychoacoustic amplitude compensation Higher frequencies are normally perceived as louder, which amp-compA ANSI standard describes a function for loudness vs. frequency. Note that this curve is only valid for standardized amplitude. For a simpler but more flexible curve, see amp-comp. freq - input frequency value. For freq == root, the output is rootAmp. (default freq 0 Hz) root - root freq relative to which the curve is calculated (usually lowest freq) (default 0 Hz) default value: C (60.midicps) minAmp - amplitude at the minimum point of the curve (around 2512 Hz) (default -10dB) compare a sine without compensation with one that uses amplitude compensation adjust the minimum and root amp (in this way one can flatten out the curve for higher amplitudes) amplitude compensation in frequency modulation (using
( amp - compA freq root rootAmp ) compensates . Following the measurings by Fletcher and , the rootAmp - amplitude at the root frequency . ( default 1 ) apart from freq , the values are not (let* ((x (mouse-x kr 300 15000 1 0.1)) (y (mouse-y kr 0 1 0 0.1)) (o (mul (sin-osc ar x 0) 0.1)) (c (amp-comp-a x 300 (db-amp -10) 1))) (audition (out 0 (mce2 (mul o y) (mul3 o (sub 1 y) c))))) (let* ((x (mouse-x kr 300 18000 1 0.1)) (y (mouse-y kr 0 1 0 0.1)) (o (mul (formant ar 300 x 20) 0.1)) (c (amp-comp-a x 300 0.6 0.3))) (audition (out 0 (mce2 (mul o y) (mul3 o (sub 1 y) c))))) Fletscher - Munson curve ) (let* ((x (mouse-x kr 300 15000 1 0.1)) (y (mouse-y kr 3 200 1 0.1)) (m (mul x (mul-add (sin-osc ar y 0) 0.5 1))) (a (amp-comp-a m 300 (db-amp -10) 1)) (c (mul3 (sin-osc ar m 0) 0.1 a))) (audition (out 0 c)))
df309501ce9a8b23adee85970c4f380a45fdce852f6b88bad1fb94d2fc6bd88c
mzp/coq-ide-for-ios
dp_why.mli
open Fol (* generation of the Why file *) val output_file : string -> query -> unit table to translate the proofs back to Coq ( used in dp_zenon ) type proof = | Immediate of Term.constr | Fun_def of string * (string * typ) list * typ * term val add_proof : proof -> string val find_proof : string -> proof
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/coq-8.2pl2/plugins/dp/dp_why.mli
ocaml
generation of the Why file
open Fol val output_file : string -> query -> unit table to translate the proofs back to Coq ( used in dp_zenon ) type proof = | Immediate of Term.constr | Fun_def of string * (string * typ) list * typ * term val add_proof : proof -> string val find_proof : string -> proof
210a4503861e4e7d18905d8c4c7f0002282192f5fcaae5545b467ce19dfa833a
theodormoroianu/SecondYearCourses
HaskellChurch_20210415163415.hs
{-# LANGUAGE RankNTypes #-} module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = "cBool " <> show (cIf b True False) The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse --The boolean negation switches the alternatives cNot :: CBool -> CBool cNot = undefined --The boolean conjunction can be built as a conditional (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: --The boolean disjunction can be built as a conditional (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: -- a pair is a way to compute something based on the values -- contained within the pair. newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = "cPair " <> show (cOn p (,)) builds a pair out of two values as an object which , when given --a function to be applied on the values, it will apply it on them. cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined -- A natural number is any way to iterate a function s a number of times -- over an initial value z newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } -- An instance to show CNats as regular natural numbers instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) --0 will iterate the function s 0 times over z, producing z c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined --Successor n either - applies s one more time in addition to what n does -- - iterates s n times over (s z) cS :: CNat -> CNat cS = undefined --Addition of m and n is done by iterating s n times over m (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: --Multiplication of m and n can be done by composing n and m (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: --Exponentiation of m and n can be done by applying n to m (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: --Testing whether a value is 0 can be done through iteration -- using a function constantly false and an initial value true cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application -- of the predeccesor function (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular -- arithmetic instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat -- m is less than (or equal to) n if when substracting n from m we get 0 (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: -- equality on naturals can be defined my means of comparisons (==:) :: CNat -> CNat -> CBool (==:) = undefined --Fun with arithmetic and pairs --Define factorial. You can iterate over a pair to contain the current index and so far factorial cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined --Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. --hint repeated substraction, iterated for at most m times. cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined -- a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where --An instance to show CLists as regular lists. instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) cNil :: CList a cNil = undefined churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415163415.hs
haskell
# LANGUAGE RankNTypes # The boolean negation switches the alternatives The boolean conjunction can be built as a conditional The boolean disjunction can be built as a conditional a pair is a way to compute something based on the values contained within the pair. a function to be applied on the values, it will apply it on them. A natural number is any way to iterate a function s a number of times over an initial value z An instance to show CNats as regular natural numbers 0 will iterate the function s 0 times over z, producing z Successor n either - iterates s n times over (s z) Addition of m and n is done by iterating s n times over m Multiplication of m and n can be done by composing n and m Exponentiation of m and n can be done by applying n to m Testing whether a value is 0 can be done through iteration using a function constantly false and an initial value true of the predeccesor function arithmetic m is less than (or equal to) n if when substracting n from m we get 0 equality on naturals can be defined my means of comparisons Fun with arithmetic and pairs Define factorial. You can iterate over a pair to contain the current index and so far factorial Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n. hint repeated substraction, iterated for at most m times. a list is a way to aggregate a sequence of elements given an aggregation function and an initial value. An instance to show CLists as regular lists.
module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = "cBool " <> show (cIf b True False) The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cBool :: Bool -> CBool cBool True = cTrue cBool False = cFalse cNot :: CBool -> CBool cNot = undefined (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = "cPair " <> show (cOn p (,)) builds a pair out of two values as an object which , when given cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined - applies s one more time in addition to what n does cS :: CNat -> CNat cS = undefined (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: (==:) :: CNat -> CNat -> CBool (==:) = undefined cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = undefined newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } make CList an instance of Foldable instance Foldable CList where instance (Show a) => Show (CList a) where show l = "cList " <> (show $ toList l) cNil :: CList a cNil = undefined churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
6208da14c7e2ef286ec92834e0ec2a9e84e14f444b9984a9106739ca2f488d8b
ranjitjhala/haddock-annot
Convert.hs
# LANGUAGE PatternGuards # ----------------------------------------------------------------------------- -- | Module : . Convert Copyright : ( c ) , -- License : BSD-like -- -- Maintainer : -- Stability : experimental -- Portability : portable -- Conversion between TyThing and HsDecl . This functionality may be moved into GHC at some point . ----------------------------------------------------------------------------- module Haddock.Convert where -- Some other functions turned out to be useful for converting instance heads , which are n't , so just export everything . import HsSyn import TcType ( tcSplitSigmaTy ) import TypeRep import Coercion ( splitKindFunTys, synTyConResKind ) import Name import Var import Class import TyCon import DataCon import TysPrim ( alphaTyVars ) import TysWiredIn ( listTyConName ) import Bag ( emptyBag ) import SrcLoc ( Located, noLoc, unLoc ) -- the main function here! yay! tyThingToLHsDecl :: TyThing -> LHsDecl Name tyThingToLHsDecl t = noLoc $ case t of ids ( functions and zero - argument a.k.a . ) get a type signature . -- Including built-in functions like seq. -- foreign-imported functions could be represented with ForD -- instead of SigD if we wanted... -- -- in a future code version we could turn idVarDetails = foreign-call into a ForD instead of a SigD if we wanted . does n't -- need to care. AnId i -> SigD (synifyIdSig ImplicitizeForAll i) -- type-constructors (e.g. Maybe) are complicated, put the definition -- later in the file (also it's used for class associated-types too.) ATyCon tc -> TyClD (synifyTyCon tc) -- a data-constructor alone just gets rendered as a function: ADataCon dc -> SigD (TypeSig (synifyName dc) (synifyType ImplicitizeForAll (dataConUserType dc))) -- classes are just a little tedious AClass cl -> TyClD $ ClassDecl (synifyCtx (classSCTheta cl)) (synifyName cl) (synifyTyVars (classTyVars cl)) (map (\ (l,r) -> noLoc (map getName l, map getName r) ) $ snd $ classTvsFds cl) (map (noLoc . synifyIdSig DeleteTopLevelQuantification) (classMethods cl)) emptyBag --ignore default method definitions, they don't affect signature (map synifyClassAT (classATs cl)) [] --we don't have any docs at this point class associated - types are a subset of -- (mainly only type/data-families) synifyClassAT :: TyCon -> LTyClDecl Name synifyClassAT = noLoc . synifyTyCon synifyTyCon :: TyCon -> TyClDecl Name synifyTyCon tc | isFunTyCon tc || isPrimTyCon tc = TyData -- arbitrary lie, they are neither algebraic data nor newtype: DataType -- no built-in type has any stupidTheta: (noLoc []) (synifyName tc) -- tyConTyVars doesn't work on fun/prim, but we can make them up: (zipWith (\fakeTyVar realKind -> noLoc $ KindedTyVar (getName fakeTyVar) realKind) alphaTyVars --a, b, c... which are unfortunately all kind * (fst . splitKindFunTys $ tyConKind tc) ) -- assume primitive types aren't members of data/newtype families: Nothing -- we have their kind accurately: (Just (tyConKind tc)) -- no algebraic constructors: [] -- "deriving" needn't be specified: Nothing | isSynFamilyTyCon tc = case synTyConRhs tc of SynFamilyTyCon -> TyFamily TypeFamily (synifyName tc) (synifyTyVars (tyConTyVars tc)) (Just (synTyConResKind tc)) _ -> error "synifyTyCon: impossible open type synonym?" | isDataFamilyTyCon tc = --(why no "isOpenAlgTyCon"?) case algTyConRhs tc of DataFamilyTyCon -> TyFamily DataFamily (synifyName tc) (synifyTyVars (tyConTyVars tc)) Nothing --always kind '*' _ -> error "synifyTyCon: impossible open data type?" | otherwise = -- (closed) type, newtype, and data let -- alg_ only applies to newtype/data -- syn_ only applies to type -- others apply to both alg_nd = if isNewTyCon tc then NewType else DataType alg_ctx = synifyCtx (tyConStupidTheta tc) name = synifyName tc tyvars = synifyTyVars (tyConTyVars tc) typats = case tyConFamInst_maybe tc of Nothing -> Nothing Just (_, indexes) -> Just (map (synifyType WithinType) indexes) alg_kindSig = Just (tyConKind tc) -- The data constructors. -- -- Any data-constructors not exported from the module that *defines* the -- type will not (cannot) be included. -- -- Very simple constructors, Haskell98 with no existentials or anything, -- probably look nicer in non-GADT syntax. In source code, all constructors must be declared with the same ( GADT vs. not ) syntax , and it probably -- is less confusing to follow that principle for the documentation as well. -- There is no sensible infix - representation for GADT - syntax constructor -- declarations. They cannot be made in source code, but we could end up -- with some here in the case where some constructors use existentials. -- That seems like an acceptable compromise (they'll just be documented -- in prefix position), since, otherwise, the logic (at best) gets much more -- complicated. (would use dataConIsInfix.) alg_use_gadt_syntax = any (not . isVanillaDataCon) (tyConDataCons tc) alg_cons = map (synifyDataCon alg_use_gadt_syntax) (tyConDataCons tc) -- "deriving" doesn't affect the signature, no need to specify any. alg_deriv = Nothing syn_type = synifyType WithinType (synTyConType tc) in if isSynTyCon tc then TySynonym name tyvars typats syn_type else TyData alg_nd alg_ctx name tyvars typats alg_kindSig alg_cons alg_deriv -- User beware: it is your responsibility to pass True (use_gadt_syntax) -- for any constructor that would be misrepresented by omitting its -- result-type. -- But you might want pass False in simple enough cases, -- if you think it looks better. synifyDataCon :: Bool -> DataCon -> LConDecl Name synifyDataCon use_gadt_syntax dc = noLoc $ let -- dataConIsInfix allegedly tells us whether it was declared with -- infix *syntax*. use_infix_syntax = dataConIsInfix dc use_named_field_syntax = not (null field_tys) name = synifyName dc con_qvars means a different thing depending on gadt - syntax qvars = if use_gadt_syntax then synifyTyVars (dataConAllTyVars dc) else synifyTyVars (dataConExTyVars dc) skip any EqTheta , use ' orig'inal syntax ctx = synifyCtx (dataConDictTheta dc) linear_tys = zipWith (\ty bang -> let tySyn = synifyType WithinType ty in case bang of HsUnpackFailed -> noLoc $ HsBangTy HsStrict tySyn HsNoBang -> tySyn -- HsNoBang never appears, it's implied instead. _ -> noLoc $ HsBangTy bang tySyn ) (dataConOrigArgTys dc) (dataConStrictMarks dc) field_tys = zipWith (\field synTy -> ConDeclField (synifyName field) synTy Nothing) (dataConFieldLabels dc) linear_tys tys = case (use_named_field_syntax, use_infix_syntax) of (True,True) -> error "synifyDataCon: contradiction!" (True,False) -> RecCon field_tys (False,False) -> PrefixCon linear_tys (False,True) -> case linear_tys of [a,b] -> InfixCon a b _ -> error "synifyDataCon: infix with non-2 args?" res_ty = if use_gadt_syntax then ResTyGADT (synifyType WithinType (dataConOrigResTy dc)) else ResTyH98 -- finally we get synifyDataCon's result! in ConDecl name Implicit{-we don't know nor care-} qvars ctx tys res_ty Nothing we do n't want any " deprecated GADT syntax " warnings ! synifyName :: NamedThing n => n -> Located Name synifyName = noLoc . getName synifyIdSig :: SynifyTypeState -> Id -> Sig Name synifyIdSig s i = TypeSig (synifyName i) (synifyType s (varType i)) synifyCtx :: [PredType] -> LHsContext Name synifyCtx = noLoc . map synifyPred synifyPred :: PredType -> LHsPred Name synifyPred (ClassP cls tys) = let sTys = map (synifyType WithinType) tys in noLoc $ HsClassP (getName cls) sTys synifyPred (IParam ip ty) = let sTy = synifyType WithinType ty IPName should be in class NamedThing ... in noLoc $ HsIParam ip sTy synifyPred (EqPred ty1 ty2) = let s1 = synifyType WithinType ty1 s2 = synifyType WithinType ty2 in noLoc $ HsEqualP s1 s2 synifyTyVars :: [TyVar] -> [LHsTyVarBndr Name] synifyTyVars = map synifyTyVar where synifyTyVar tv = noLoc $ let kind = tyVarKind tv name = getName tv in if isLiftedTypeKind kind then UserTyVar name placeHolderKind else KindedTyVar name kind --states of what to do with foralls: data SynifyTypeState = WithinType -- ^ normal situation. This is the safe one to use if you don't -- quite understand what's going on. | ImplicitizeForAll -- ^ beginning of a function definition, in which, to make it look -- less ugly, those rank-1 foralls are made implicit. | DeleteTopLevelQuantification -- ^ because in class methods the context is added to the type ( e.g. adding @forall a. Num a = > @ to @(+ ) : : a - > a - > a@ ) -- which is rather sensible, -- but we want to restore things to the source-syntax situation where -- the defining class gets to quantify all its functions for free! synifyType :: SynifyTypeState -> Type -> LHsType Name synifyType _ (PredTy{}) = --should never happen. error "synifyType: PredTys are not, in themselves, source-level types." synifyType _ (TyVarTy tv) = noLoc $ HsTyVar (getName tv) synifyType _ (TyConApp tc tys) -- Use non-prefix tuple syntax where possible, because it looks nicer. | isTupleTyCon tc, tyConArity tc == length tys = noLoc $ HsTupleTy (tupleTyConBoxity tc) (map (synifyType WithinType) tys) -- ditto for lists | getName tc == listTyConName, [ty] <- tys = noLoc $ HsListTy (synifyType WithinType ty) Most TyCons : | otherwise = foldl (\t1 t2 -> noLoc (HsAppTy t1 t2)) (noLoc $ HsTyVar (getName tc)) (map (synifyType WithinType) tys) synifyType _ (AppTy t1 t2) = let s1 = synifyType WithinType t1 s2 = synifyType WithinType t2 in noLoc $ HsAppTy s1 s2 synifyType _ (FunTy t1 t2) = let s1 = synifyType WithinType t1 s2 = synifyType WithinType t2 in noLoc $ HsFunTy s1 s2 synifyType s forallty@(ForAllTy _tv _ty) = let (tvs, ctx, tau) = tcSplitSigmaTy forallty in case s of DeleteTopLevelQuantification -> synifyType ImplicitizeForAll tau _ -> let forallPlicitness = case s of WithinType -> Explicit ImplicitizeForAll -> Implicit _ -> error "synifyType: impossible case!!!" sTvs = synifyTyVars tvs sCtx = synifyCtx ctx sTau = synifyType WithinType tau in noLoc $ HsForAllTy forallPlicitness sTvs sCtx sTau synifyInstHead :: ([TyVar], [PredType], Class, [Type]) -> ([HsPred Name], Name, [HsType Name]) synifyInstHead (_, preds, cls, ts) = ( map (unLoc . synifyPred) preds , getName cls , map (unLoc . synifyType WithinType) ts )
null
https://raw.githubusercontent.com/ranjitjhala/haddock-annot/ffaa182b17c3047887ff43dbe358c246011903f6/haddock-2.9.3/src/Haddock/Convert.hs
haskell
--------------------------------------------------------------------------- | License : BSD-like Maintainer : Stability : experimental Portability : portable --------------------------------------------------------------------------- Some other functions turned out to be useful for converting the main function here! yay! Including built-in functions like seq. foreign-imported functions could be represented with ForD instead of SigD if we wanted... in a future code version we could turn idVarDetails = foreign-call need to care. type-constructors (e.g. Maybe) are complicated, put the definition later in the file (also it's used for class associated-types too.) a data-constructor alone just gets rendered as a function: classes are just a little tedious ignore default method definitions, they don't affect signature we don't have any docs at this point (mainly only type/data-families) arbitrary lie, they are neither algebraic data nor newtype: no built-in type has any stupidTheta: tyConTyVars doesn't work on fun/prim, but we can make them up: a, b, c... which are unfortunately all kind * assume primitive types aren't members of data/newtype families: we have their kind accurately: no algebraic constructors: "deriving" needn't be specified: (why no "isOpenAlgTyCon"?) always kind '*' (closed) type, newtype, and data alg_ only applies to newtype/data syn_ only applies to type others apply to both The data constructors. Any data-constructors not exported from the module that *defines* the type will not (cannot) be included. Very simple constructors, Haskell98 with no existentials or anything, probably look nicer in non-GADT syntax. In source code, all constructors is less confusing to follow that principle for the documentation as well. declarations. They cannot be made in source code, but we could end up with some here in the case where some constructors use existentials. That seems like an acceptable compromise (they'll just be documented in prefix position), since, otherwise, the logic (at best) gets much more complicated. (would use dataConIsInfix.) "deriving" doesn't affect the signature, no need to specify any. User beware: it is your responsibility to pass True (use_gadt_syntax) for any constructor that would be misrepresented by omitting its result-type. But you might want pass False in simple enough cases, if you think it looks better. dataConIsInfix allegedly tells us whether it was declared with infix *syntax*. HsNoBang never appears, it's implied instead. finally we get synifyDataCon's result! we don't know nor care states of what to do with foralls: ^ normal situation. This is the safe one to use if you don't quite understand what's going on. ^ beginning of a function definition, in which, to make it look less ugly, those rank-1 foralls are made implicit. ^ because in class methods the context is added to the type which is rather sensible, but we want to restore things to the source-syntax situation where the defining class gets to quantify all its functions for free! should never happen. Use non-prefix tuple syntax where possible, because it looks nicer. ditto for lists
# LANGUAGE PatternGuards # Module : . Convert Copyright : ( c ) , Conversion between TyThing and HsDecl . This functionality may be moved into GHC at some point . module Haddock.Convert where instance heads , which are n't , so just export everything . import HsSyn import TcType ( tcSplitSigmaTy ) import TypeRep import Coercion ( splitKindFunTys, synTyConResKind ) import Name import Var import Class import TyCon import DataCon import TysPrim ( alphaTyVars ) import TysWiredIn ( listTyConName ) import Bag ( emptyBag ) import SrcLoc ( Located, noLoc, unLoc ) tyThingToLHsDecl :: TyThing -> LHsDecl Name tyThingToLHsDecl t = noLoc $ case t of ids ( functions and zero - argument a.k.a . ) get a type signature . into a ForD instead of a SigD if we wanted . does n't AnId i -> SigD (synifyIdSig ImplicitizeForAll i) ATyCon tc -> TyClD (synifyTyCon tc) ADataCon dc -> SigD (TypeSig (synifyName dc) (synifyType ImplicitizeForAll (dataConUserType dc))) AClass cl -> TyClD $ ClassDecl (synifyCtx (classSCTheta cl)) (synifyName cl) (synifyTyVars (classTyVars cl)) (map (\ (l,r) -> noLoc (map getName l, map getName r) ) $ snd $ classTvsFds cl) (map (noLoc . synifyIdSig DeleteTopLevelQuantification) (classMethods cl)) (map synifyClassAT (classATs cl)) class associated - types are a subset of synifyClassAT :: TyCon -> LTyClDecl Name synifyClassAT = noLoc . synifyTyCon synifyTyCon :: TyCon -> TyClDecl Name synifyTyCon tc | isFunTyCon tc || isPrimTyCon tc = TyData DataType (noLoc []) (synifyName tc) (zipWith (\fakeTyVar realKind -> noLoc $ KindedTyVar (getName fakeTyVar) realKind) (fst . splitKindFunTys $ tyConKind tc) ) Nothing (Just (tyConKind tc)) [] Nothing | isSynFamilyTyCon tc = case synTyConRhs tc of SynFamilyTyCon -> TyFamily TypeFamily (synifyName tc) (synifyTyVars (tyConTyVars tc)) (Just (synTyConResKind tc)) _ -> error "synifyTyCon: impossible open type synonym?" case algTyConRhs tc of DataFamilyTyCon -> TyFamily DataFamily (synifyName tc) (synifyTyVars (tyConTyVars tc)) _ -> error "synifyTyCon: impossible open data type?" | otherwise = let alg_nd = if isNewTyCon tc then NewType else DataType alg_ctx = synifyCtx (tyConStupidTheta tc) name = synifyName tc tyvars = synifyTyVars (tyConTyVars tc) typats = case tyConFamInst_maybe tc of Nothing -> Nothing Just (_, indexes) -> Just (map (synifyType WithinType) indexes) alg_kindSig = Just (tyConKind tc) must be declared with the same ( GADT vs. not ) syntax , and it probably There is no sensible infix - representation for GADT - syntax constructor alg_use_gadt_syntax = any (not . isVanillaDataCon) (tyConDataCons tc) alg_cons = map (synifyDataCon alg_use_gadt_syntax) (tyConDataCons tc) alg_deriv = Nothing syn_type = synifyType WithinType (synTyConType tc) in if isSynTyCon tc then TySynonym name tyvars typats syn_type else TyData alg_nd alg_ctx name tyvars typats alg_kindSig alg_cons alg_deriv synifyDataCon :: Bool -> DataCon -> LConDecl Name synifyDataCon use_gadt_syntax dc = noLoc $ let use_infix_syntax = dataConIsInfix dc use_named_field_syntax = not (null field_tys) name = synifyName dc con_qvars means a different thing depending on gadt - syntax qvars = if use_gadt_syntax then synifyTyVars (dataConAllTyVars dc) else synifyTyVars (dataConExTyVars dc) skip any EqTheta , use ' orig'inal syntax ctx = synifyCtx (dataConDictTheta dc) linear_tys = zipWith (\ty bang -> let tySyn = synifyType WithinType ty in case bang of HsUnpackFailed -> noLoc $ HsBangTy HsStrict tySyn HsNoBang -> tySyn _ -> noLoc $ HsBangTy bang tySyn ) (dataConOrigArgTys dc) (dataConStrictMarks dc) field_tys = zipWith (\field synTy -> ConDeclField (synifyName field) synTy Nothing) (dataConFieldLabels dc) linear_tys tys = case (use_named_field_syntax, use_infix_syntax) of (True,True) -> error "synifyDataCon: contradiction!" (True,False) -> RecCon field_tys (False,False) -> PrefixCon linear_tys (False,True) -> case linear_tys of [a,b] -> InfixCon a b _ -> error "synifyDataCon: infix with non-2 args?" res_ty = if use_gadt_syntax then ResTyGADT (synifyType WithinType (dataConOrigResTy dc)) else ResTyH98 qvars ctx tys res_ty Nothing we do n't want any " deprecated GADT syntax " warnings ! synifyName :: NamedThing n => n -> Located Name synifyName = noLoc . getName synifyIdSig :: SynifyTypeState -> Id -> Sig Name synifyIdSig s i = TypeSig (synifyName i) (synifyType s (varType i)) synifyCtx :: [PredType] -> LHsContext Name synifyCtx = noLoc . map synifyPred synifyPred :: PredType -> LHsPred Name synifyPred (ClassP cls tys) = let sTys = map (synifyType WithinType) tys in noLoc $ HsClassP (getName cls) sTys synifyPred (IParam ip ty) = let sTy = synifyType WithinType ty IPName should be in class NamedThing ... in noLoc $ HsIParam ip sTy synifyPred (EqPred ty1 ty2) = let s1 = synifyType WithinType ty1 s2 = synifyType WithinType ty2 in noLoc $ HsEqualP s1 s2 synifyTyVars :: [TyVar] -> [LHsTyVarBndr Name] synifyTyVars = map synifyTyVar where synifyTyVar tv = noLoc $ let kind = tyVarKind tv name = getName tv in if isLiftedTypeKind kind then UserTyVar name placeHolderKind else KindedTyVar name kind data SynifyTypeState = WithinType | ImplicitizeForAll | DeleteTopLevelQuantification ( e.g. adding @forall a. Num a = > @ to @(+ ) : : a - > a - > a@ ) synifyType :: SynifyTypeState -> Type -> LHsType Name error "synifyType: PredTys are not, in themselves, source-level types." synifyType _ (TyVarTy tv) = noLoc $ HsTyVar (getName tv) synifyType _ (TyConApp tc tys) | isTupleTyCon tc, tyConArity tc == length tys = noLoc $ HsTupleTy (tupleTyConBoxity tc) (map (synifyType WithinType) tys) | getName tc == listTyConName, [ty] <- tys = noLoc $ HsListTy (synifyType WithinType ty) Most TyCons : | otherwise = foldl (\t1 t2 -> noLoc (HsAppTy t1 t2)) (noLoc $ HsTyVar (getName tc)) (map (synifyType WithinType) tys) synifyType _ (AppTy t1 t2) = let s1 = synifyType WithinType t1 s2 = synifyType WithinType t2 in noLoc $ HsAppTy s1 s2 synifyType _ (FunTy t1 t2) = let s1 = synifyType WithinType t1 s2 = synifyType WithinType t2 in noLoc $ HsFunTy s1 s2 synifyType s forallty@(ForAllTy _tv _ty) = let (tvs, ctx, tau) = tcSplitSigmaTy forallty in case s of DeleteTopLevelQuantification -> synifyType ImplicitizeForAll tau _ -> let forallPlicitness = case s of WithinType -> Explicit ImplicitizeForAll -> Implicit _ -> error "synifyType: impossible case!!!" sTvs = synifyTyVars tvs sCtx = synifyCtx ctx sTau = synifyType WithinType tau in noLoc $ HsForAllTy forallPlicitness sTvs sCtx sTau synifyInstHead :: ([TyVar], [PredType], Class, [Type]) -> ([HsPred Name], Name, [HsType Name]) synifyInstHead (_, preds, cls, ts) = ( map (unLoc . synifyPred) preds , getName cls , map (unLoc . synifyType WithinType) ts )
c5e40fc7cce4d76dfb20e999fd2da58890cc5f16a80f8fbf8ee508a18dc873ab
vascokk/rivus_cep
rivus_cep_server_sup.erl
%%------------------------------------------------------------------------------ Copyright ( c ) 2014 %% 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(rivus_cep_server_sup). -behaviour(supervisor). -export([start_link/0, init/1, stop/1]). -export([start_socket/0]). -compile([{parse_transform, lager_transform}]). start_socket() -> supervisor:start_child(?MODULE, []). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). stop(_S) -> ok. init([]) -> lager:debug("-----> rivus_cep_server_sup, Args: ~p~n",[]), {ok, {{simple_one_for_one, 10, 10}, [{rivus_cep_server, {rivus_cep_server, start_link, []}, temporary, brutal_kill, worker, [rivus_cep_server]}]}}.
null
https://raw.githubusercontent.com/vascokk/rivus_cep/e9fe6ed79201d852065f7fb2a24a880414031d27/src/rivus_cep_server_sup.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. ------------------------------------------------------------------------------
Copyright ( c ) 2014 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(rivus_cep_server_sup). -behaviour(supervisor). -export([start_link/0, init/1, stop/1]). -export([start_socket/0]). -compile([{parse_transform, lager_transform}]). start_socket() -> supervisor:start_child(?MODULE, []). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). stop(_S) -> ok. init([]) -> lager:debug("-----> rivus_cep_server_sup, Args: ~p~n",[]), {ok, {{simple_one_for_one, 10, 10}, [{rivus_cep_server, {rivus_cep_server, start_link, []}, temporary, brutal_kill, worker, [rivus_cep_server]}]}}.
5e330b0dec41a8ead96d264126f7f01acb8ed3d7f52c678a1fd37348f90f3e10
developandplay/material-components-web-miso
Ripple.hs
{-# LANGUAGE OverloadedStrings #-} module Material.Ripple ( Config, config, setColor, setAttributes, bounded, unbounded, Color, primary, accent, ) where import qualified Data.Map as Map import qualified Data.Maybe as Maybe import qualified Miso -- | Ripple configuration data Config msg = Config { color :: Maybe Color, additionalAttributes :: [Miso.Attribute msg] } -- | Default ripple configuration config :: Config msg config = Config { color = Nothing, additionalAttributes = [] } -- | Specify a ripple effect's color setColor :: Maybe Color -> Config msg -> Config msg setColor color config_ = config_ {color = color} -- | Specify additional attributes setAttributes :: [Miso.Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} -- | Ripple effect's color data Color = Primary | Accent -- | Primary variant of a ripple effect's color primary :: Color primary = Primary -- | Accent variant of a ripple effect's color accent :: Color accent = Accent ripple :: Bool -> Config msg -> Miso.View msg ripple isUnbounded (config_@Config {additionalAttributes = additionalAttributes}) = Miso.nodeHtml "mdc-ripple" ( Maybe.mapMaybe id [ unboundedProp isUnbounded, unboundedData isUnbounded, colorCs config_, rippleSurface, Just (Miso.style_ $ Map.singleton "position" "absolute"), Just (Miso.style_ $ Map.singleton "top" "0"), Just (Miso.style_ $ Map.singleton "left" "0"), Just (Miso.style_ $ Map.singleton "right" "0"), Just (Miso.style_ $ Map.singleton "bottom" "0") ] ++ additionalAttributes ) [] -- | Bounded ripple view function bounded :: Config msg -> Miso.View msg bounded = ripple False -- | Unbounded ripple view function unbounded :: Config msg -> Miso.View msg unbounded = ripple True rippleSurface :: Maybe (Miso.Attribute msg) rippleSurface = Just (Miso.class_ "mdc-ripple-surface") colorCs :: Config msg -> Maybe (Miso.Attribute msg) colorCs (Config {color = color}) = case color of Just Primary -> Just (Miso.class_ "mdc-ripple-surface--primary") Just Accent -> Just (Miso.class_ "mdc-ripple-surface--accent") Nothing -> Nothing unboundedProp :: Bool -> Maybe (Miso.Attribute msg) unboundedProp isUnbounded = Just (Miso.boolProp "unbounded" isUnbounded) unboundedData :: Bool -> Maybe (Miso.Attribute msg) unboundedData isUnbounded = if isUnbounded then Just (Miso.textProp "data-mdc-ripple-is-unbounded" "") else Nothing
null
https://raw.githubusercontent.com/developandplay/material-components-web-miso/97a20097bf522b62743c884b66757eb895edd690/sample-app-jsaddle/Material/Ripple.hs
haskell
# LANGUAGE OverloadedStrings # | Ripple configuration | Default ripple configuration | Specify a ripple effect's color | Specify additional attributes | Ripple effect's color | Primary variant of a ripple effect's color | Accent variant of a ripple effect's color | Bounded ripple view function | Unbounded ripple view function
module Material.Ripple ( Config, config, setColor, setAttributes, bounded, unbounded, Color, primary, accent, ) where import qualified Data.Map as Map import qualified Data.Maybe as Maybe import qualified Miso data Config msg = Config { color :: Maybe Color, additionalAttributes :: [Miso.Attribute msg] } config :: Config msg config = Config { color = Nothing, additionalAttributes = [] } setColor :: Maybe Color -> Config msg -> Config msg setColor color config_ = config_ {color = color} setAttributes :: [Miso.Attribute msg] -> Config msg -> Config msg setAttributes additionalAttributes config_ = config_ {additionalAttributes = additionalAttributes} data Color = Primary | Accent primary :: Color primary = Primary accent :: Color accent = Accent ripple :: Bool -> Config msg -> Miso.View msg ripple isUnbounded (config_@Config {additionalAttributes = additionalAttributes}) = Miso.nodeHtml "mdc-ripple" ( Maybe.mapMaybe id [ unboundedProp isUnbounded, unboundedData isUnbounded, colorCs config_, rippleSurface, Just (Miso.style_ $ Map.singleton "position" "absolute"), Just (Miso.style_ $ Map.singleton "top" "0"), Just (Miso.style_ $ Map.singleton "left" "0"), Just (Miso.style_ $ Map.singleton "right" "0"), Just (Miso.style_ $ Map.singleton "bottom" "0") ] ++ additionalAttributes ) [] bounded :: Config msg -> Miso.View msg bounded = ripple False unbounded :: Config msg -> Miso.View msg unbounded = ripple True rippleSurface :: Maybe (Miso.Attribute msg) rippleSurface = Just (Miso.class_ "mdc-ripple-surface") colorCs :: Config msg -> Maybe (Miso.Attribute msg) colorCs (Config {color = color}) = case color of Just Primary -> Just (Miso.class_ "mdc-ripple-surface--primary") Just Accent -> Just (Miso.class_ "mdc-ripple-surface--accent") Nothing -> Nothing unboundedProp :: Bool -> Maybe (Miso.Attribute msg) unboundedProp isUnbounded = Just (Miso.boolProp "unbounded" isUnbounded) unboundedData :: Bool -> Maybe (Miso.Attribute msg) unboundedData isUnbounded = if isUnbounded then Just (Miso.textProp "data-mdc-ripple-is-unbounded" "") else Nothing
c3e4f4c2b49b21f5472a2528717a0d31613ae60e9ba8207a07dc742065fb093d
clojure/tools.analyzer.js
validate.clj
Copyright ( c ) , Rich Hickey & contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.analyzer.passes.js.validate (:require [clojure.tools.analyzer.ast :refer [prewalk]] [clojure.tools.analyzer.passes.cleanup :refer [cleanup]] [clojure.tools.analyzer.passes.js.infer-tag :refer [infer-tag]] [clojure.tools.analyzer.utils :refer [source-info resolve-sym resolve-ns]])) (defmulti -validate :op) (defmethod -validate :default [ast] ast) (defmethod -validate :maybe-class [{:keys [class form env] :as ast}] (when-not (:analyzer/allow-undefined (meta form)) (throw (ex-info (str "Cannot resolve: " class) (merge {:sym class :ast (prewalk ast cleanup)} (source-info env))))) ) (defmethod -validate :maybe-host-form [{:keys [form env] :as ast}] (when-not (:analyzer/allow-undefined (meta form)) (throw (ex-info (str "Cannot resolve: " form) (merge {:sym form :ast (prewalk ast cleanup)} (source-info env))))) ) (defn validate-tag [t {:keys [env] :as ast}] (let [tag (ast t)] (if (symbol? tag) (if-let [var (resolve-sym tag env)] (symbol (str (:ns var)) (str (:name var))) #_(if (or (= :type (:op var)) (:protocol (meta var))) (symbol (str (:ns var)) (str (:name var))) (throw (ex-info (str "Not type/protocol var used as a tag: " tag) (merge {:var var :ast (prewalk ast cleanup)} (source-info env))))) tag #_(if (or ('#{boolean string number clj-nil any function object array} tag) (and (namespace tag) (not (resolve-ns (symbol (namespace tag)) env)))) tag (throw (ex-info (str "Cannot resolve: " tag) (merge {:sym tag :ast (prewalk ast cleanup)} (source-info env)))))) (throw (ex-info (str "Invalid tag: " tag) (merge {:tag tag :ast (prewalk ast cleanup)} (source-info env))))))) (defn validate "Validate tags and symbols. Throws exceptions when invalid forms are encountered" {:pass-info {:walk :any :depends #{#'infer-tag}}} [ast] (merge (-validate ast) (when (:tag ast) {:tag (validate-tag :tag ast)}) (when (:return-tag ast) {:return-tag (validate-tag :return-tag ast)})))
null
https://raw.githubusercontent.com/clojure/tools.analyzer.js/f0dbadd26393b6bb0d8b64f5f0f6891384228696/src/main/clojure/clojure/tools/analyzer/passes/js/validate.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) , Rich Hickey & contributors . (ns clojure.tools.analyzer.passes.js.validate (:require [clojure.tools.analyzer.ast :refer [prewalk]] [clojure.tools.analyzer.passes.cleanup :refer [cleanup]] [clojure.tools.analyzer.passes.js.infer-tag :refer [infer-tag]] [clojure.tools.analyzer.utils :refer [source-info resolve-sym resolve-ns]])) (defmulti -validate :op) (defmethod -validate :default [ast] ast) (defmethod -validate :maybe-class [{:keys [class form env] :as ast}] (when-not (:analyzer/allow-undefined (meta form)) (throw (ex-info (str "Cannot resolve: " class) (merge {:sym class :ast (prewalk ast cleanup)} (source-info env))))) ) (defmethod -validate :maybe-host-form [{:keys [form env] :as ast}] (when-not (:analyzer/allow-undefined (meta form)) (throw (ex-info (str "Cannot resolve: " form) (merge {:sym form :ast (prewalk ast cleanup)} (source-info env))))) ) (defn validate-tag [t {:keys [env] :as ast}] (let [tag (ast t)] (if (symbol? tag) (if-let [var (resolve-sym tag env)] (symbol (str (:ns var)) (str (:name var))) #_(if (or (= :type (:op var)) (:protocol (meta var))) (symbol (str (:ns var)) (str (:name var))) (throw (ex-info (str "Not type/protocol var used as a tag: " tag) (merge {:var var :ast (prewalk ast cleanup)} (source-info env))))) tag #_(if (or ('#{boolean string number clj-nil any function object array} tag) (and (namespace tag) (not (resolve-ns (symbol (namespace tag)) env)))) tag (throw (ex-info (str "Cannot resolve: " tag) (merge {:sym tag :ast (prewalk ast cleanup)} (source-info env)))))) (throw (ex-info (str "Invalid tag: " tag) (merge {:tag tag :ast (prewalk ast cleanup)} (source-info env))))))) (defn validate "Validate tags and symbols. Throws exceptions when invalid forms are encountered" {:pass-info {:walk :any :depends #{#'infer-tag}}} [ast] (merge (-validate ast) (when (:tag ast) {:tag (validate-tag :tag ast)}) (when (:return-tag ast) {:return-tag (validate-tag :return-tag ast)})))
5de0ac3676cecf2dd37219ed1dc66169c8166d2dcaed9e1059e0b1abba072347
kitten-lang/kitten
Interact.hs
{-# LANGUAGE OverloadedStrings #-} module Interact ( run ) where import Control.Exception (catch) import Control.Monad.IO.Class (liftIO) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.List (isPrefixOf, partition, sort, stripPrefix) import Data.Maybe (fromJust) import Data.Monoid import Data.Text (Text) import Kitten (runKitten) import Kitten.Dictionary (Dictionary) import Kitten.Entry (Entry) import Kitten.Entry.Parameter (Parameter(..)) import Kitten.Infer (typecheck, typeFromSignature) import Kitten.Informer (checkpoint) import Kitten.Instantiated (Instantiated(Instantiated)) import Kitten.Interpret (Failure, interpret) import Kitten.Kind (Kind(..)) import Kitten.Name import Report import System.Console.Haskeline hiding (catch) import System.Exit (exitFailure) import System.IO (hPrint, hPutStrLn, stdin, stdout, stderr) import Text.PrettyPrint.HughesPJClass (Pretty(..)) import Text.Printf (printf) import qualified Data.Text as Text import qualified Kitten import qualified Kitten.Definition as Definition import qualified Kitten.Dictionary as Dictionary import qualified Kitten.Enter as Enter import qualified Kitten.Entry as Entry import qualified Kitten.Fragment as Fragment import qualified Kitten.IO as IO import qualified Kitten.Instantiated as Instantiated import qualified Kitten.Name as Name import qualified Kitten.Origin as Origin import qualified Kitten.Parse as Parse import qualified Kitten.Pretty as Pretty import qualified Kitten.Report as Report import qualified Kitten.Resolve as Resolve import qualified Kitten.Signature as Signature import qualified Kitten.Term as Term import qualified Kitten.TypeEnv as TypeEnv import qualified Kitten.Unify as Unify import qualified Kitten.Vocabulary as Vocabulary import qualified Text.PrettyPrint as Pretty run :: IO () run = do let commonPath = "common.ktn" commonSource <- IO.readFileUtf8 commonPath commonDictionary <- runKitten $ do fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] (Just $ Qualified Vocabulary.global "main") 1 commonPath commonSource Enter.fragment fragment Dictionary.empty dictionaryRef <- newIORef =<< case commonDictionary of Left reports -> do reportAll reports exitFailure Right result -> return result lineNumberRef <- newIORef (1 :: Int) stackRef <- newIORef [] welcome runInputT (settings dictionaryRef) $ let loop :: InputT IO () loop = do lineNumber <- liftIO $ readIORef lineNumberRef let currentOrigin = Origin.point "<interactive>" lineNumber 1 mLine <- getEntry lineNumber case mLine of Nothing -> liftIO $ putStrLn "" >> bye Just (line, lineNumber') -> case line of "//dict" -> do liftIO $ renderDictionary dictionaryRef loop "//help" -> do liftIO showHelp loop "//stack" -> do liftIO $ renderStack stackRef loop "//quit" -> liftIO bye -- Commands with arguments. _ | "//" `Text.isPrefixOf` line -> case Text.break (== ' ') $ Text.drop 2 line of ("info", name) -> nameCommand lineNumber dictionaryRef name loop $ \ _name' entry -> liftIO $ putStrLn $ Pretty.render $ pPrint entry ("list", name) -> nameCommand lineNumber dictionaryRef name loop $ \ name' entry -> case entry of Entry.Word _ _ _ _ _ (Just body) -> liftIO $ putStrLn $ Pretty.render $ pPrint body _ -> liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I can't find a word entry called" , Pretty.quote name' , "with a body to list" ] ("type", expression) -> do dictionary <- liftIO $ readIORef dictionaryRef mResults <- liftIO $ runKitten $ do fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] Nothing lineNumber "<interactive>" expression checkpoint case Fragment.definitions fragment of [main] | Definition.name main == Definition.mainName -> do resolved <- Enter.resolveAndDesugar dictionary main checkpoint (_, type_) <- typecheck dictionary Nothing $ Definition.body resolved checkpoint return (Just type_) _ -> return Nothing liftIO $ case mResults of Left reports -> reportAll reports Right (Just type_) -> putStrLn $ Pretty.render $ pPrint type_ Right Nothing -> hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "That doesn't look like an expression" ] loop (command, _) -> do liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I don't know the command" , Pretty.quotes $ Pretty.text $ Text.unpack command ] loop -- Kitten code. _ -> do dictionary <- liftIO $ readIORef dictionaryRef let entryNameUnqualified = Text.pack $ "entry" ++ show lineNumber entryName = Qualified (Qualifier Absolute ["interactive"]) $ Unqualified entryNameUnqualified mResults <- liftIO $ runKitten $ do -- Each entry gets its own definition in the dictionary, so it can -- be executed individually, and later conveniently referred to. fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] (Just entryName) lineNumber "<interactive>" line dictionary' <- Enter.fragment fragment dictionary checkpoint callFragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] Nothing lineNumber "<interactive>" -- TODO: Avoid stringly typing. (Text.pack $ Pretty.render $ pPrint entryName) dictionary'' <- Enter.fragment callFragment dictionary' checkpoint let tenv = TypeEnv.empty mainBody = case Dictionary.lookup (Instantiated Definition.mainName []) dictionary'' of Just (Entry.Word _ _ _ _ _ (Just body)) -> body _ -> error "cannot get entry point" stackScheme <- typeFromSignature tenv $ Signature.Quantified [ Parameter currentOrigin "R" Stack , Parameter currentOrigin "E" Permission ] (Signature.StackFunction (Signature.Bottom currentOrigin) [] (Signature.Variable "R" currentOrigin) [] ["E"] currentOrigin) currentOrigin -- Checking that the main definition is able to operate on an -- empty stack is the same as verifying the last entry against the -- current stack state, as long as the state was modified -- correctly by the interpreter. _ <- Unify.type_ tenv stackScheme (Term.type_ mainBody) checkpoint return (dictionary'', mainBody) case mResults of Left reports -> do liftIO $ reportAll reports loop Right (dictionary', mainBody) -> do liftIO $ do writeIORef dictionaryRef dictionary' writeIORef lineNumberRef lineNumber' -- HACK: Get the last entry from the main body so we have the -- right generic args. let lastEntry = last $ Term.decompose mainBody case lastEntry of (Term.Word _ _ _ args _) -> liftIO $ catch (do stack <- interpret dictionary' (Just entryName) args stdin stdout stderr =<< readIORef stackRef writeIORef stackRef stack renderStack stackRef) $ \ e -> hPrint stderr (e :: Failure) _ -> error $ show lastEntry loop in loop where welcome = putStrLn "Welcome to Kitten! Type //help for help or //quit to quit" bye = do putStrLn "Bye!" return () settings :: IORef Dictionary -> Settings IO settings dictionaryRef = setComplete (completer dictionaryRef) $ defaultSettings { autoAddHistory = True , historyFile = Nothing } completer :: IORef Dictionary -> CompletionFunc IO completer = completeWord Nothing "\t \"{}[]()\\" . completePrefix completePrefix :: IORef Dictionary -> String -> IO [Completion] completePrefix dictionaryRef prefix | Just rest <- Text.stripPrefix "//" (Text.pack prefix) = let -- TODO: Factor out commands to a central location. matching = filter (rest `Text.isPrefixOf`) ["dict", "help", "info", "list", "quit", "stack", "type"] hasParams = [["info"], ["list"], ["type"]] in return $ map (toCompletion (small matching && matching `elem` hasParams) . Text.unpack . ("//" <>)) matching | otherwise = do dictionary <- readIORef dictionaryRef let matching = filter (prefix `isPrefixOf`) $ map (completionFromName . fst) $ Dictionary.toList dictionary return $ map (toCompletion (small matching)) matching where completionFromName (Instantiated (Qualified (Qualifier _ parts) (Unqualified name)) _) = Text.unpack $ Text.intercalate "::" $ parts ++ [name] small :: [a] -> Bool small [] = True small [_] = True small _ = False toCompletion :: Bool -> String -> Completion toCompletion finished name = Completion { replacement = name , display = name , isFinished = finished } renderDictionary :: IORef Dictionary -> IO () renderDictionary dictionaryRef = do names <- sort . map (Name.toParts . Instantiated.name . fst) . Dictionary.toList <$> readIORef dictionaryRef let loop :: Int -> [[Text]] -> IO () loop depth acc = case foldr0 commonPrefix [] acc of [] -> mapM_ (putStrLn . prettyName depth) acc prefix -> let stripped = map (fromJust . stripPrefix prefix) acc (leaves, branches) = partition ((== 1) . length) stripped in do putStrLn $ prettyName depth prefix loop (depth + 4) branches mapM_ (putStrLn . prettyName (depth + 4)) leaves loop 0 names where -- TODO: Don't rely on name of global vocabulary. prettyName depth = Pretty.render . Pretty.nest depth . Pretty.text . Text.unpack . Text.intercalate "::" . (\x -> if x == [""] then ["_"] else x) foldr0 :: (a -> a -> a) -> a -> [a] -> a foldr0 _ x [] = x foldr0 f _ xs = foldr1 f xs commonPrefix :: (Eq a) => [a] -> [a] -> [a] commonPrefix (x : xs) (y : ys) | x == y = x : commonPrefix xs ys | otherwise = [] commonPrefix xs@[] _ = xs commonPrefix _ ys@[] = ys nameCommand :: Int -> IORef Dictionary -> Text -> InputT IO () -> (Qualified -> Entry -> InputT IO ()) -> InputT IO () nameCommand lineNumber dictionaryRef name loop action = do result <- runKitten $ Parse.generalName lineNumber "<interactive>" name let currentOrigin = Origin.point "<interactive>" lineNumber 1 case result of Right unresolved -> do dictionary <- liftIO $ readIORef dictionaryRef mResolved <- liftIO $ runKitten $ Resolve.run $ Resolve.generalName -- TODO: Use 'WordOrTypeName' or something as the category. Report.WordName (\ _ index -> return $ LocalName index) (\ name' -> Instantiated name' [] `Dictionary.member` dictionary) -- TODO: Keep a notion of current vocabulary? Vocabulary.global unresolved -- TODO: Get this from the parser. currentOrigin case mResolved of Left reports -> do liftIO $ reportAll reports loop Right (QualifiedName resolved) | Just entry <- Dictionary.lookup (Instantiated resolved []) dictionary -> do action resolved entry loop Right resolved -> do liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I can't find an entry in the dictionary for" , Pretty.quote resolved ] loop Left reports -> do liftIO $ reportAll reports loop renderStack :: (Pretty a) => IORef [a] -> IO () renderStack stackRef = do stack <- readIORef stackRef case stack of [] -> return () _ -> putStrLn $ Pretty.render $ Pretty.vcat $ map pPrint stack showHelp :: IO () showHelp = putStrLn "\ \\n\ \//help - Show this help.\n\ \//quit - Quit interactive mode.\n\ \\n\ \//dict - Show the contents of the dictionary.\n\ \//info <name> - Show information about <name>.\n\ \//list <name> - Show the desugared source of <name>.\n\ \//stack - Show the state of the stack.\n\ \//type <expr> - Show the type of some expression <expr>.\n\ \\&" data InString = Inside | Outside getEntry :: Int -> InputT IO (Maybe (Text, Int)) getEntry lineNumber0 = do mLine <- getInputLine $ printf "\n% 4d: " lineNumber0 -- FIXME: Use MaybeT? case mLine of Nothing -> return Nothing Just line -> do mLine' <- check lineNumber0 line Nothing case mLine' of Nothing -> return Nothing Just (result, lineNumber') -> return $ Just (Text.pack result, lineNumber' + 1) where check :: Int -> String -> Maybe String -> InputT IO (Maybe (String, Int)) check lineNumber line acc | matched acc' = return $ Just (acc', lineNumber) | otherwise = continue (succ lineNumber) $ Just acc' where acc' = case acc of Just previous -> concat [previous, "\n", line] Nothing -> line continue :: Int -> Maybe String -> InputT IO (Maybe (String, Int)) continue lineNumber acc = do mLine <- getInputLine $ printf "\n% 4d| " lineNumber case mLine of Nothing -> return Nothing Just line -> check lineNumber line acc matched :: String -> Bool matched = go Outside (0::Int) where go :: InString -> Int -> String -> Bool go q n ('\\':x:xs) | x `elem` ("'\"" :: String) = go q n xs | otherwise = go q n xs go q n ('"':xs) = go (case q of Inside -> Outside; Outside -> Inside) n xs go Inside n (_:xs) = go Inside n xs go Inside _ [] = True go Outside n (x:xs) | isOpen x = go Outside (succ n) xs | isClose x = n <= 0 || go Outside (pred n) xs | otherwise = go Outside n xs go Outside n [] = n == 0 isOpen = (`elem` ("([{" :: String)) isClose = (`elem` ("}])" :: String))
null
https://raw.githubusercontent.com/kitten-lang/kitten/4a760b3d144702e39214347cfd8aa3899b34c10b/src/Interact.hs
haskell
# LANGUAGE OverloadedStrings # Commands with arguments. Kitten code. Each entry gets its own definition in the dictionary, so it can be executed individually, and later conveniently referred to. TODO: Avoid stringly typing. Checking that the main definition is able to operate on an empty stack is the same as verifying the last entry against the current stack state, as long as the state was modified correctly by the interpreter. HACK: Get the last entry from the main body so we have the right generic args. TODO: Factor out commands to a central location. TODO: Don't rely on name of global vocabulary. TODO: Use 'WordOrTypeName' or something as the category. TODO: Keep a notion of current vocabulary? TODO: Get this from the parser. FIXME: Use MaybeT?
module Interact ( run ) where import Control.Exception (catch) import Control.Monad.IO.Class (liftIO) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.List (isPrefixOf, partition, sort, stripPrefix) import Data.Maybe (fromJust) import Data.Monoid import Data.Text (Text) import Kitten (runKitten) import Kitten.Dictionary (Dictionary) import Kitten.Entry (Entry) import Kitten.Entry.Parameter (Parameter(..)) import Kitten.Infer (typecheck, typeFromSignature) import Kitten.Informer (checkpoint) import Kitten.Instantiated (Instantiated(Instantiated)) import Kitten.Interpret (Failure, interpret) import Kitten.Kind (Kind(..)) import Kitten.Name import Report import System.Console.Haskeline hiding (catch) import System.Exit (exitFailure) import System.IO (hPrint, hPutStrLn, stdin, stdout, stderr) import Text.PrettyPrint.HughesPJClass (Pretty(..)) import Text.Printf (printf) import qualified Data.Text as Text import qualified Kitten import qualified Kitten.Definition as Definition import qualified Kitten.Dictionary as Dictionary import qualified Kitten.Enter as Enter import qualified Kitten.Entry as Entry import qualified Kitten.Fragment as Fragment import qualified Kitten.IO as IO import qualified Kitten.Instantiated as Instantiated import qualified Kitten.Name as Name import qualified Kitten.Origin as Origin import qualified Kitten.Parse as Parse import qualified Kitten.Pretty as Pretty import qualified Kitten.Report as Report import qualified Kitten.Resolve as Resolve import qualified Kitten.Signature as Signature import qualified Kitten.Term as Term import qualified Kitten.TypeEnv as TypeEnv import qualified Kitten.Unify as Unify import qualified Kitten.Vocabulary as Vocabulary import qualified Text.PrettyPrint as Pretty run :: IO () run = do let commonPath = "common.ktn" commonSource <- IO.readFileUtf8 commonPath commonDictionary <- runKitten $ do fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] (Just $ Qualified Vocabulary.global "main") 1 commonPath commonSource Enter.fragment fragment Dictionary.empty dictionaryRef <- newIORef =<< case commonDictionary of Left reports -> do reportAll reports exitFailure Right result -> return result lineNumberRef <- newIORef (1 :: Int) stackRef <- newIORef [] welcome runInputT (settings dictionaryRef) $ let loop :: InputT IO () loop = do lineNumber <- liftIO $ readIORef lineNumberRef let currentOrigin = Origin.point "<interactive>" lineNumber 1 mLine <- getEntry lineNumber case mLine of Nothing -> liftIO $ putStrLn "" >> bye Just (line, lineNumber') -> case line of "//dict" -> do liftIO $ renderDictionary dictionaryRef loop "//help" -> do liftIO showHelp loop "//stack" -> do liftIO $ renderStack stackRef loop "//quit" -> liftIO bye _ | "//" `Text.isPrefixOf` line -> case Text.break (== ' ') $ Text.drop 2 line of ("info", name) -> nameCommand lineNumber dictionaryRef name loop $ \ _name' entry -> liftIO $ putStrLn $ Pretty.render $ pPrint entry ("list", name) -> nameCommand lineNumber dictionaryRef name loop $ \ name' entry -> case entry of Entry.Word _ _ _ _ _ (Just body) -> liftIO $ putStrLn $ Pretty.render $ pPrint body _ -> liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I can't find a word entry called" , Pretty.quote name' , "with a body to list" ] ("type", expression) -> do dictionary <- liftIO $ readIORef dictionaryRef mResults <- liftIO $ runKitten $ do fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] Nothing lineNumber "<interactive>" expression checkpoint case Fragment.definitions fragment of [main] | Definition.name main == Definition.mainName -> do resolved <- Enter.resolveAndDesugar dictionary main checkpoint (_, type_) <- typecheck dictionary Nothing $ Definition.body resolved checkpoint return (Just type_) _ -> return Nothing liftIO $ case mResults of Left reports -> reportAll reports Right (Just type_) -> putStrLn $ Pretty.render $ pPrint type_ Right Nothing -> hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "That doesn't look like an expression" ] loop (command, _) -> do liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I don't know the command" , Pretty.quotes $ Pretty.text $ Text.unpack command ] loop _ -> do dictionary <- liftIO $ readIORef dictionaryRef let entryNameUnqualified = Text.pack $ "entry" ++ show lineNumber entryName = Qualified (Qualifier Absolute ["interactive"]) $ Unqualified entryNameUnqualified mResults <- liftIO $ runKitten $ do fragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] (Just entryName) lineNumber "<interactive>" line dictionary' <- Enter.fragment fragment dictionary checkpoint callFragment <- Kitten.fragmentFromSource [QualifiedName $ Qualified Vocabulary.global "IO"] Nothing lineNumber "<interactive>" (Text.pack $ Pretty.render $ pPrint entryName) dictionary'' <- Enter.fragment callFragment dictionary' checkpoint let tenv = TypeEnv.empty mainBody = case Dictionary.lookup (Instantiated Definition.mainName []) dictionary'' of Just (Entry.Word _ _ _ _ _ (Just body)) -> body _ -> error "cannot get entry point" stackScheme <- typeFromSignature tenv $ Signature.Quantified [ Parameter currentOrigin "R" Stack , Parameter currentOrigin "E" Permission ] (Signature.StackFunction (Signature.Bottom currentOrigin) [] (Signature.Variable "R" currentOrigin) [] ["E"] currentOrigin) currentOrigin _ <- Unify.type_ tenv stackScheme (Term.type_ mainBody) checkpoint return (dictionary'', mainBody) case mResults of Left reports -> do liftIO $ reportAll reports loop Right (dictionary', mainBody) -> do liftIO $ do writeIORef dictionaryRef dictionary' writeIORef lineNumberRef lineNumber' let lastEntry = last $ Term.decompose mainBody case lastEntry of (Term.Word _ _ _ args _) -> liftIO $ catch (do stack <- interpret dictionary' (Just entryName) args stdin stdout stderr =<< readIORef stackRef writeIORef stackRef stack renderStack stackRef) $ \ e -> hPrint stderr (e :: Failure) _ -> error $ show lastEntry loop in loop where welcome = putStrLn "Welcome to Kitten! Type //help for help or //quit to quit" bye = do putStrLn "Bye!" return () settings :: IORef Dictionary -> Settings IO settings dictionaryRef = setComplete (completer dictionaryRef) $ defaultSettings { autoAddHistory = True , historyFile = Nothing } completer :: IORef Dictionary -> CompletionFunc IO completer = completeWord Nothing "\t \"{}[]()\\" . completePrefix completePrefix :: IORef Dictionary -> String -> IO [Completion] completePrefix dictionaryRef prefix | Just rest <- Text.stripPrefix "//" (Text.pack prefix) = let matching = filter (rest `Text.isPrefixOf`) ["dict", "help", "info", "list", "quit", "stack", "type"] hasParams = [["info"], ["list"], ["type"]] in return $ map (toCompletion (small matching && matching `elem` hasParams) . Text.unpack . ("//" <>)) matching | otherwise = do dictionary <- readIORef dictionaryRef let matching = filter (prefix `isPrefixOf`) $ map (completionFromName . fst) $ Dictionary.toList dictionary return $ map (toCompletion (small matching)) matching where completionFromName (Instantiated (Qualified (Qualifier _ parts) (Unqualified name)) _) = Text.unpack $ Text.intercalate "::" $ parts ++ [name] small :: [a] -> Bool small [] = True small [_] = True small _ = False toCompletion :: Bool -> String -> Completion toCompletion finished name = Completion { replacement = name , display = name , isFinished = finished } renderDictionary :: IORef Dictionary -> IO () renderDictionary dictionaryRef = do names <- sort . map (Name.toParts . Instantiated.name . fst) . Dictionary.toList <$> readIORef dictionaryRef let loop :: Int -> [[Text]] -> IO () loop depth acc = case foldr0 commonPrefix [] acc of [] -> mapM_ (putStrLn . prettyName depth) acc prefix -> let stripped = map (fromJust . stripPrefix prefix) acc (leaves, branches) = partition ((== 1) . length) stripped in do putStrLn $ prettyName depth prefix loop (depth + 4) branches mapM_ (putStrLn . prettyName (depth + 4)) leaves loop 0 names where prettyName depth = Pretty.render . Pretty.nest depth . Pretty.text . Text.unpack . Text.intercalate "::" . (\x -> if x == [""] then ["_"] else x) foldr0 :: (a -> a -> a) -> a -> [a] -> a foldr0 _ x [] = x foldr0 f _ xs = foldr1 f xs commonPrefix :: (Eq a) => [a] -> [a] -> [a] commonPrefix (x : xs) (y : ys) | x == y = x : commonPrefix xs ys | otherwise = [] commonPrefix xs@[] _ = xs commonPrefix _ ys@[] = ys nameCommand :: Int -> IORef Dictionary -> Text -> InputT IO () -> (Qualified -> Entry -> InputT IO ()) -> InputT IO () nameCommand lineNumber dictionaryRef name loop action = do result <- runKitten $ Parse.generalName lineNumber "<interactive>" name let currentOrigin = Origin.point "<interactive>" lineNumber 1 case result of Right unresolved -> do dictionary <- liftIO $ readIORef dictionaryRef mResolved <- liftIO $ runKitten $ Resolve.run $ Resolve.generalName Report.WordName (\ _ index -> return $ LocalName index) (\ name' -> Instantiated name' [] `Dictionary.member` dictionary) Vocabulary.global unresolved currentOrigin case mResolved of Left reports -> do liftIO $ reportAll reports loop Right (QualifiedName resolved) | Just entry <- Dictionary.lookup (Instantiated resolved []) dictionary -> do action resolved entry loop Right resolved -> do liftIO $ hPutStrLn stderr $ Pretty.render $ Pretty.hsep [ "I can't find an entry in the dictionary for" , Pretty.quote resolved ] loop Left reports -> do liftIO $ reportAll reports loop renderStack :: (Pretty a) => IORef [a] -> IO () renderStack stackRef = do stack <- readIORef stackRef case stack of [] -> return () _ -> putStrLn $ Pretty.render $ Pretty.vcat $ map pPrint stack showHelp :: IO () showHelp = putStrLn "\ \\n\ \//help - Show this help.\n\ \//quit - Quit interactive mode.\n\ \\n\ \//dict - Show the contents of the dictionary.\n\ \//info <name> - Show information about <name>.\n\ \//list <name> - Show the desugared source of <name>.\n\ \//stack - Show the state of the stack.\n\ \//type <expr> - Show the type of some expression <expr>.\n\ \\&" data InString = Inside | Outside getEntry :: Int -> InputT IO (Maybe (Text, Int)) getEntry lineNumber0 = do mLine <- getInputLine $ printf "\n% 4d: " lineNumber0 case mLine of Nothing -> return Nothing Just line -> do mLine' <- check lineNumber0 line Nothing case mLine' of Nothing -> return Nothing Just (result, lineNumber') -> return $ Just (Text.pack result, lineNumber' + 1) where check :: Int -> String -> Maybe String -> InputT IO (Maybe (String, Int)) check lineNumber line acc | matched acc' = return $ Just (acc', lineNumber) | otherwise = continue (succ lineNumber) $ Just acc' where acc' = case acc of Just previous -> concat [previous, "\n", line] Nothing -> line continue :: Int -> Maybe String -> InputT IO (Maybe (String, Int)) continue lineNumber acc = do mLine <- getInputLine $ printf "\n% 4d| " lineNumber case mLine of Nothing -> return Nothing Just line -> check lineNumber line acc matched :: String -> Bool matched = go Outside (0::Int) where go :: InString -> Int -> String -> Bool go q n ('\\':x:xs) | x `elem` ("'\"" :: String) = go q n xs | otherwise = go q n xs go q n ('"':xs) = go (case q of Inside -> Outside; Outside -> Inside) n xs go Inside n (_:xs) = go Inside n xs go Inside _ [] = True go Outside n (x:xs) | isOpen x = go Outside (succ n) xs | isClose x = n <= 0 || go Outside (pred n) xs | otherwise = go Outside n xs go Outside n [] = n == 0 isOpen = (`elem` ("([{" :: String)) isClose = (`elem` ("}])" :: String))
eead4bd1f45464e9f88c4263fd28c33165d170bc923b394787074cdc2c9d3055
basho/riak_cs
riak_cs_mp_utils.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% --------------------------------------------------------------------- %% @doc -module(riak_cs_mp_utils). -include("riak_cs.hrl"). -include_lib("riak_pb/include/riak_pb_kv_codec.hrl"). -include_lib("riakc/include/riakc.hrl"). -ifdef(TEST). -compile(export_all). -ifdef(EQC). -include_lib("eqc/include/eqc.hrl"). -endif. -include_lib("eunit/include/eunit.hrl"). -endif. -define(MIN_MP_PART_SIZE, (5*1024*1024)). -define(PID(WrappedRcPid), get_riak_client_pid(WrappedRcPid)). %% export Public API -export([ abort_multipart_upload/4, abort_multipart_upload/5, calc_multipart_2i_dict/3, clean_multipart_unused_parts/2, complete_multipart_upload/5, complete_multipart_upload/6, initiate_multipart_upload/5, initiate_multipart_upload/6, list_all_multipart_uploads/3, list_multipart_uploads/3, list_multipart_uploads/4, list_parts/5, list_parts/6, make_content_types_accepted/2, make_content_types_accepted/3, upload_part/6, upload_part/7, upload_part_1blob/2, upload_part_finished/7, upload_part_finished/8, is_multipart_manifest/1 ]). -export([get_mp_manifest/1]). %%%=================================================================== %%% API %%%=================================================================== calc_multipart_2i_dict(Ms, Bucket, _Key) when is_list(Ms) -> According to API Version 2006 - 03 - 01 , page 139 - 140 , bucket %% owners have some privileges for multipart uploads performed by %% other users, i.e, see those MP uploads via list multipart uploads, and cancel multipart upload . We use two different 2I index entries to allow 2I to do the work of segregating multipart upload requests of bucket owner vs. non - bucket owner via two different 2I entries , %% one that includes the object owner and one that does not. L_2i = [ case get_mp_manifest(M) of undefined -> []; MpM when is_record(MpM, ?MULTIPART_MANIFEST_RECNAME) -> [{make_2i_key(Bucket, MpM?MULTIPART_MANIFEST.owner), <<"1">>}, {make_2i_key(Bucket), <<"1">>}] end || M <- Ms, M?MANIFEST.state == writing], {?MD_INDEX, lists:usort(lists:append(L_2i))}. abort_multipart_upload(Bucket, Key, UploadId, Caller) -> abort_multipart_upload(Bucket, Key, UploadId, Caller, nopid). abort_multipart_upload(Bucket, Key, UploadId, Caller, RcPidUnW) -> do_part_common(abort, Bucket, Key, UploadId, Caller, [], RcPidUnW). clean_multipart_unused_parts(?MANIFEST{bkey=BKey, props=Props} = Manifest, RcPid) -> case get_mp_manifest(Manifest) of undefined -> same; MpM -> case {proplists:get_value(multipart_clean, Props, false), MpM?MULTIPART_MANIFEST.cleanup_parts} of {false, []} -> same; {false, PartsToDelete} -> _ = try {Bucket, Key} = BKey, BagId = riak_cs_mb_helper:bag_id_from_manifest(Manifest), ok = move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid), UpdManifest = Manifest?MANIFEST{props=[multipart_clean|Props]}, ok = update_manifest_with_confirmation(RcPid, UpdManifest) catch X:Y -> lager:debug("clean_multipart_unused_parts: " "bkey ~p: ~p ~p @ ~p\n", [BKey, X, Y, erlang:get_stacktrace()]) end, %% Return same value to caller, regardless of ok/catch updated; {true, _} -> same end end. complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller) -> complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller, nopid). complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller, RcPidUnW) -> Extra = {PartETags}, do_part_common(complete, Bucket, Key, UploadId, Caller, [{complete, Extra}], RcPidUnW). initiate_multipart_upload(Bucket, Key, ContentType, Owner, Opts) -> initiate_multipart_upload(Bucket, Key, ContentType, Owner, Opts, nopid). initiate_multipart_upload(Bucket, Key, ContentType, {_,_,_} = Owner, Opts, RcPidUnW) -> write_new_manifest(new_manifest(Bucket, Key, ContentType, Owner, Opts), Opts, RcPidUnW). make_content_types_accepted(RD, Ctx) -> make_content_types_accepted(RD, Ctx, unused_callback). make_content_types_accepted(RD, Ctx, Callback) -> make_content_types_accepted(wrq:get_req_header("Content-Type", RD), RD, Ctx, Callback). make_content_types_accepted(CT, RD, Ctx, Callback) when CT =:= undefined; CT =:= [] -> make_content_types_accepted("application/octet-stream", RD, Ctx, Callback); make_content_types_accepted(CT, RD, Ctx=#context{local_context=LocalCtx0}, Callback) -> %% This was shamelessly ripped out of %% #L492 {Media, _Params} = mochiweb_util:parse_header(CT), case string:tokens(Media, "/") of [_Type, _Subtype] -> %% accept whatever the user says LocalCtx = LocalCtx0#key_context{putctype=Media}, {[{Media, Callback}], RD, Ctx#context{local_context=LocalCtx}}; _ -> {[], wrq:set_resp_header( "Content-Type", "text/plain", wrq:set_resp_body( ["\"", Media, "\"" " is not a valid media type" " for the Content-type header.\n"], RD)), Ctx} end. list_multipart_uploads(Bucket, Caller, Opts) -> list_multipart_uploads(Bucket, Caller, Opts, nopid). list_multipart_uploads(Bucket, {_Display, _Canon, CallerKeyId} = Caller, Opts, RcPidUnW) -> case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try BucketOwnerP = is_caller_bucket_owner(?PID(RcPid), Bucket, CallerKeyId), Key2i = case BucketOwnerP of true -> make_2i_key(Bucket); % caller = bucket owner false -> make_2i_key(Bucket, Caller) end, list_multipart_uploads_with_2ikey(Bucket, Opts, ?PID(RcPid), Key2i) catch error:{badmatch, {m_icbo, _}} -> {error, access_denied} after wrap_close_riak_client(RcPid) end; Else -> Else end. list_all_multipart_uploads(Bucket, Opts, RcPid) -> list_multipart_uploads_with_2ikey(Bucket, Opts, RcPid, make_2i_key(Bucket)). list_multipart_uploads_with_2ikey(Bucket, Opts, RcPid, Key2i) -> HashBucket = riak_cs_utils:to_bucket_name(objects, Bucket), {ok, ManifestPbc} = riak_cs_riak_client:manifest_pbc(RcPid), Timeout = riak_cs_config:get_index_list_multipart_uploads_timeout(), case riak_cs_pbc:get_index_eq(ManifestPbc, HashBucket, Key2i, <<"1">>, [{timeout, Timeout}], [riakc, get_uploads_by_index]) of {ok, ?INDEX_RESULTS{keys=Names}} -> {ok, list_multipart_uploads2(Bucket, RcPid, Names, Opts)}; Else2 -> Else2 end. list_parts(Bucket, Key, UploadId, Caller, Opts) -> list_parts(Bucket, Key, UploadId, Caller, Opts, nopid). list_parts(Bucket, Key, UploadId, Caller, Opts, RcPidUnW) -> Extra = {Opts}, do_part_common(list, Bucket, Key, UploadId, Caller, [{list, Extra}], RcPidUnW). %% @doc -spec new_manifest(binary(), binary(), binary(), acl_owner(), list()) -> lfs_manifest(). new_manifest(Bucket, Key, ContentType, {_, _, _} = Owner, Opts) -> UUID = druuid:v4(), %% TODO: add object metadata here, e.g. content-disposition et al. MetaData = case proplists:get_value(meta_data, Opts) of undefined -> []; AsIsHdrs -> AsIsHdrs end, M = riak_cs_lfs_utils:new_manifest(Bucket, Key, UUID, 0, ContentType, %% we won't know the md5 of a multipart undefined, MetaData, riak_cs_lfs_utils:block_size(), ACL : needs client pid , so we wait no_acl_yet, [], %% Cluster ID and Bag ID are added later undefined, undefined), MpM = ?MULTIPART_MANIFEST{upload_id = UUID, owner = Owner}, M?MANIFEST{props = replace_mp_manifest(MpM, M?MANIFEST.props)}. upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller) -> upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller, nopid). upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller, RcPidUnW) -> Extra = {Bucket, Key, UploadId, Caller, PartNumber, Size}, do_part_common(upload_part, Bucket, Key, UploadId, Caller, [{upload_part, Extra}], RcPidUnW). upload_part_1blob(PutPid, Blob) -> ok = riak_cs_put_fsm:augment_data(PutPid, Blob), {ok, M} = riak_cs_put_fsm:finalize(PutPid, undefined), {ok, M?MANIFEST.content_md5}. %% Once upon a time, in a naive land far away, I thought that it would be sufficient to use each part 's UUID as the ETag when the part upload was finished , and thus the client would use that UUID to %% complete the uploaded object. However, 's3cmd' want to use the ETag of each uploaded part to be the MD5(part content ) and will %% issue a warning if that checksum expectation isn't met. So, now we must thread the MD5 value through upload_part_finished and update %% the ?MULTIPART_MANIFEST in a mergeable way. {sigh} upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller) -> upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller, nopid). upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller, RcPidUnW) -> Extra = {PartUUID, MD5}, do_part_common(upload_part_finished, Bucket, Key, UploadId, Caller, [{upload_part_finished, Extra}], RcPidUnW). write_new_manifest(?MANIFEST{bkey={Bucket, Key}, uuid=UUID}=M, Opts, RcPidUnW) -> MpM = get_mp_manifest(M), Owner = MpM?MULTIPART_MANIFEST.owner, case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try Acl = case proplists:get_value(acl, Opts) of undefined -> riak_cs_acl_utils:canned_acl("private", Owner, undefined); AnAcl -> AnAcl end, BagId = riak_cs_mb_helper:choose_bag_id(block, {Bucket, Key, UUID}), M2 = riak_cs_lfs_utils:set_bag_id(BagId, M), ClusterId = riak_cs_mb_helper:cluster_id(BagId), M3 = M2?MANIFEST{acl = Acl, cluster_id=ClusterId, write_start_time=os:timestamp()}, {ok, ManiPid} = riak_cs_manifest_fsm:start_link(Bucket, Key, ?PID(RcPid)), try ok = riak_cs_manifest_fsm:add_new_manifest(ManiPid, M3), {ok, M3?MANIFEST.uuid} after ok = riak_cs_manifest_fsm:stop(ManiPid) end after wrap_close_riak_client(RcPid) end; Else -> Else end. %%%=================================================================== Internal functions %%%=================================================================== do_part_common(Op, Bucket, Key, UploadId, {_,_,CallerKeyId} = _Caller, Props, RcPidUnW) -> case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try case riak_cs_manifest:get_manifests(?PID(RcPid), Bucket, Key) of {ok, Obj, Manifests} -> case find_manifest_with_uploadid(UploadId, Manifests) of false -> {error, notfound}; M when M?MANIFEST.state == writing -> MpM = get_mp_manifest(M), {_, _, MpMOwner} = MpM?MULTIPART_MANIFEST.owner, case CallerKeyId == MpMOwner of true -> do_part_common2(Op, ?PID(RcPid), M, Obj, MpM, Props); false -> {error, access_denied} end; _ -> {error, notfound} end; Else2 -> Else2 end catch error:{badmatch, {m_icbo, _}} -> {error, access_denied}; error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable} after wrap_close_riak_client(RcPid) end; Else -> Else end. do_part_common2(abort, RcPid, M, Obj, _Mpm, _Props) -> {Bucket, Key} = M?MANIFEST.bkey, case riak_cs_gc:gc_specific_manifests( [M?MANIFEST.uuid], Obj, Bucket, Key, RcPid) of {ok, _NewObj} -> ok; Else3 -> Else3 end; do_part_common2(complete, RcPid, ?MANIFEST{uuid = _UUID, props = MProps} = Manifest, _Obj, MpM, Props) -> The content_md5 is used by WM to create the ETags header . However / fortunately / sigh - of - relief , Amazon 's S3 does n't use %% the file contents for ETag for a completeted multipart %% upload. %% %% However, if we add the hypen suffix here, e.g., "-1", then the WM will simply convert that suffix to %% extra hex digits "2d31" instead. So, hrm, what to do here. %% %% &#203436 %% BogoMD5 = iolist_to_binary([UUID, "-1"]), {PartETags} = proplists:get_value(complete, Props), try {Bucket, Key} = Manifest?MANIFEST.bkey, {ok, ManiPid} = riak_cs_manifest_fsm:start_link(Bucket, Key, RcPid), try {Bytes, OverAllMD5, PartsToKeep, PartsToDelete} = comb_parts(MpM, PartETags), true = enforce_part_size(PartsToKeep), NewMpM = MpM?MULTIPART_MANIFEST{parts = PartsToKeep, done_parts = [], cleanup_parts = PartsToDelete}, %% If [] = PartsToDelete, then we only need to update %% the manifest once. MProps2 = case PartsToDelete of [] -> [multipart_clean] ++ replace_mp_manifest(NewMpM, MProps); _ -> replace_mp_manifest(NewMpM, MProps) end, ContentMD5 = {OverAllMD5, "-" ++ integer_to_list(ordsets:size(PartsToKeep))}, NewManifest = Manifest?MANIFEST{state = active, content_length = Bytes, content_md5 = ContentMD5, props = MProps2}, ok = riak_cs_manifest_fsm:add_new_manifest(ManiPid, NewManifest), case PartsToDelete of [] -> {ok, NewManifest}; _ -> %% Create fake S3 object manifests for this part, then pass them to the GC monster for immediate %% deletion. BagId = riak_cs_mb_helper:bag_id_from_manifest(NewManifest), ok = move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid), MProps3 = [multipart_clean|MProps2], New2Manifest = NewManifest?MANIFEST{props = MProps3}, ok = riak_cs_manifest_fsm:update_manifest( ManiPid, New2Manifest), {ok, New2Manifest} end after ok = riak_cs_manifest_fsm:stop(ManiPid) end catch error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable}; throw:bad_etag -> {error, bad_etag}; throw:bad_etag_order -> {error, bad_etag_order}; throw:entity_too_small -> {error, entity_too_small} end; do_part_common2(list, _RcPid, _M, _Obj, MpM, Props) -> {_Opts} = proplists:get_value(list, Props), ?MULTIPART_MANIFEST{parts = Parts, done_parts = DoneParts0} = MpM, DoneParts = orddict:from_list(ordsets:to_list(DoneParts0)), ETagPs = lists:foldl(fun(P, Acc) -> case orddict:find(P?PART_MANIFEST.part_id, DoneParts) of error -> Acc; {ok, ETag} -> [{ETag, P}|Acc] end end, [], Parts), Ds = [?PART_DESCR{part_number = P?PART_MANIFEST.part_number, %% TODO: technically, start_time /= last_modified last_modified = riak_cs_wm_utils:iso_8601_datetime(calendar:now_to_local_time(P?PART_MANIFEST.start_time)), etag = ETag, size = P?PART_MANIFEST.content_length} || {ETag, P} <- ETagPs], {ok, Ds}; do_part_common2(upload_part, RcPid, M, _Obj, MpM, Props) -> {Bucket, Key, _UploadId, _Caller, PartNumber, Size} = proplists:get_value(upload_part, Props), BlockSize = riak_cs_lfs_utils:block_size(), BagId = riak_cs_mb_helper:bag_id_from_manifest(M), {ok, PutPid} = riak_cs_put_fsm:start_link( {Bucket, Key, Size, <<"x-riak/multipart-part">>, orddict:new(), BlockSize, M?MANIFEST.acl, infinity, self(), RcPid}, false, BagId), try ?MANIFEST{content_length = ContentLength, props = MProps} = M, ?MULTIPART_MANIFEST{parts = Parts} = MpM, PartUUID = riak_cs_put_fsm:get_uuid(PutPid), PM = ?PART_MANIFEST{bucket = Bucket, key = Key, start_time = os:timestamp(), part_number = PartNumber, part_id = PartUUID, content_length = Size, block_size = BlockSize}, NewMpM = MpM?MULTIPART_MANIFEST{parts = ordsets:add_element(PM, Parts)}, NewM = M?MANIFEST{content_length = ContentLength + Size, props = replace_mp_manifest(NewMpM, MProps)}, ok = update_manifest_with_confirmation(RcPid, NewM), {upload_part_ready, PartUUID, PutPid} catch error:{badmatch, {m_umwc, _}} -> riak_cs_put_fsm:force_stop(PutPid), {error, riak_unavailable} end; do_part_common2(upload_part_finished, RcPid, M, _Obj, MpM, Props) -> {PartUUID, MD5} = proplists:get_value(upload_part_finished, Props), try ?MULTIPART_MANIFEST{parts = Parts, done_parts = DoneParts} = MpM, DoneUUIDs = ordsets:from_list([UUID || {UUID, _ETag} <- DoneParts]), case {lists:keyfind(PartUUID, ?PART_MANIFEST.part_id, ordsets:to_list(Parts)), ordsets:is_element(PartUUID, DoneUUIDs)} of {false, _} -> {error, notfound}; {_, true} -> {error, notfound}; {PM, false} when is_record(PM, ?PART_MANIFEST_RECNAME) -> ?MANIFEST{props = MProps} = M, NewMpM = MpM?MULTIPART_MANIFEST{ done_parts = ordsets:add_element({PartUUID, MD5}, DoneParts)}, NewM = M?MANIFEST{props = replace_mp_manifest(NewMpM, MProps)}, ok = update_manifest_with_confirmation(RcPid, NewM) end catch error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable} end. update_manifest_with_confirmation(RcPid, Manifest) -> {Bucket, Key} = Manifest?MANIFEST.bkey, {m_umwc, {ok, ManiPid}} = {m_umwc, riak_cs_manifest_fsm:start_link(Bucket, Key, RcPid)}, try ok = riak_cs_manifest_fsm:update_manifest_with_confirmation(ManiPid, Manifest) after ok = riak_cs_manifest_fsm:stop(ManiPid) end. -spec make_2i_key(binary()) -> binary(). make_2i_key(Bucket) -> make_2i_key2(Bucket, ""). -spec make_2i_key(binary(), acl_owner()) -> binary(). make_2i_key(Bucket, {_, _, OwnerStr}) -> make_2i_key2(Bucket, OwnerStr). -spec make_2i_key2(binary(), string()) -> binary(). make_2i_key2(Bucket, OwnerStr) -> iolist_to_binary(["rcs@", OwnerStr, "@", Bucket, "_bin"]). list_multipart_uploads2(Bucket, RcPid, Names, Opts) -> FilterFun = fun(K, Acc) -> filter_uploads_list(Bucket, K, Opts, RcPid, Acc) end, {Manifests, Prefixes} = lists:foldl(FilterFun, {[], ordsets:new()}, Names), {lists:sort(Manifests), ordsets:to_list(Prefixes)}. filter_uploads_list(Bucket, Key, Opts, RcPid, Acc) -> multipart_manifests_for_key(Bucket, Key, Opts, Acc, RcPid). parameter_filter(M, Acc, _, _, KeyMarker, _) when M?MULTIPART_DESCR.key =< KeyMarker-> Acc; parameter_filter(M, Acc, _, _, KeyMarker, UploadIdMarker) when M?MULTIPART_DESCR.key =< KeyMarker andalso M?MULTIPART_DESCR.upload_id =< UploadIdMarker -> Acc; parameter_filter(M, {Manifests, Prefixes}, undefined, undefined, _, _) -> {[M | Manifests], Prefixes}; parameter_filter(M, Acc, undefined, Delimiter, _, _) -> Group = extract_group(M?MULTIPART_DESCR.key, Delimiter), update_keys_and_prefixes(Acc, M, <<>>, 0, Group); parameter_filter(M, {Manifests, Prefixes}, Prefix, undefined, _, _) -> PrefixLen = byte_size(Prefix), case M?MULTIPART_DESCR.key of << Prefix:PrefixLen/binary, _/binary >> -> {[M | Manifests], Prefixes}; _ -> {Manifests, Prefixes} end; parameter_filter(M, {Manifests, Prefixes}=Acc, Prefix, Delimiter, _, _) -> PrefixLen = byte_size(Prefix), case M?MULTIPART_DESCR.key of << Prefix:PrefixLen/binary, Rest/binary >> -> Group = extract_group(Rest, Delimiter), update_keys_and_prefixes(Acc, M, Prefix, PrefixLen, Group); _ -> {Manifests, Prefixes} end. extract_group(Key, Delimiter) -> case binary:match(Key, [Delimiter]) of nomatch -> nomatch; {Pos, Len} -> binary:part(Key, {0, Pos+Len}) end. update_keys_and_prefixes({Keys, Prefixes}, Key, _, _, nomatch) -> {[Key | Keys], Prefixes}; update_keys_and_prefixes({Keys, Prefixes}, _, Prefix, PrefixLen, Group) -> NewPrefix = << Prefix:PrefixLen/binary, Group/binary >>, {Keys, ordsets:add_element(NewPrefix, Prefixes)}. multipart_manifests_for_key(Bucket, Key, Opts, Acc, RcPid) -> ParameterFilter = build_parameter_filter(Opts), Manifests = handle_get_manifests_result( riak_cs_manifest:get_manifests(RcPid, Bucket, Key)), lists:foldl(ParameterFilter, Acc, Manifests). build_parameter_filter(Opts) -> Prefix = proplists:get_value(prefix, Opts), Delimiter = proplists:get_value(delimiter, Opts), KeyMarker = proplists:get_value(key_marker, Opts), UploadIdMarker = base64url:decode( proplists:get_value(upload_id_marker, Opts)), build_parameter_filter(Prefix, Delimiter, KeyMarker, UploadIdMarker). build_parameter_filter(Prefix, Delimiter, KeyMarker, UploadIdMarker) -> fun(Key, Acc) -> parameter_filter(Key, Acc, Prefix, Delimiter, KeyMarker, UploadIdMarker) end. handle_get_manifests_result({ok, _Obj, Manifests}) -> [multipart_description(M) || {_, M} <- Manifests, M?MANIFEST.state == writing, is_multipart_manifest(M)]; handle_get_manifests_result(_) -> []. -spec is_multipart_manifest(?MANIFEST{}) -> boolean(). is_multipart_manifest(?MANIFEST{props=Props}) -> case proplists:get_value(multipart, Props) of undefined -> false; _ -> true end. -spec multipart_description(?MANIFEST{}) -> ?MULTIPART_DESCR{}. multipart_description(Manifest) -> MpM = proplists:get_value(multipart, Manifest?MANIFEST.props), ?MULTIPART_DESCR{ key = element(2, Manifest?MANIFEST.bkey), upload_id = Manifest?MANIFEST.uuid, owner_key_id = element(3, MpM?MULTIPART_MANIFEST.owner), owner_display = element(1, MpM?MULTIPART_MANIFEST.owner), initiated = Manifest?MANIFEST.created}. %% @doc Will cause error:{badmatch, {m_ibco, _}} if CallerKeyId does not exist is_caller_bucket_owner(RcPid, Bucket, CallerKeyId) -> {m_icbo, {ok, {C, _}}} = {m_icbo, riak_cs_user:get_user(CallerKeyId, RcPid)}, Buckets = [iolist_to_binary(B?RCS_BUCKET.name) || B <- riak_cs_bucket:get_buckets(C)], lists:member(Bucket, Buckets). find_manifest_with_uploadid(UploadId, Manifests) -> case lists:keyfind(UploadId, 1, Manifests) of false -> false; {UploadId, M} -> M end. @doc In # 885 ( ) it happened to be revealed that ETag is generated as %% > ETag = MD5(Sum(p \in numberParts , MD5(PartBytes(p ) ) ) + " - " + numberParts %% by an Amazon support guy , . %% -spec comb_parts(multipart_manifest(), list({non_neg_integer(), binary()})) -> {KeepBytes::non_neg_integer(), OverAllMD5::binary(), PartsToKeep::list(), PartsToDelete::list()}. comb_parts(MpM, PartETags) -> Done = orddict:from_list(ordsets:to_list(MpM?MULTIPART_MANIFEST.done_parts)), %% TODO: Strictly speaking, this implementation could have %% problems with MD5 hash collisions. I'd *really* wanted to avoid using MD5 hash used as the part ETags ( see the %% "Once upon a time" comment for upload_part_finished() %% above). According to AWS S3 docs, we're supposed to take the newest part that has this { PartNum , ETag } pair . Parts0 = ordsets:to_list(MpM?MULTIPART_MANIFEST.parts), FindOrSet = fun(Key, Dict) -> case orddict:find(Key, Dict) of {ok, Value} -> Value; error -> <<>> end end, Parts = [P?PART_MANIFEST{content_md5 = FindOrSet(P?PART_MANIFEST.part_id, Done)} || P <- Parts0], All = dict:from_list( [{{PM?PART_MANIFEST.part_number, PM?PART_MANIFEST.content_md5}, PM} || PM <- Parts]), Keep0 = dict:new(), {_, _Keep, _, _, KeepBytes, KeepPMs, MD5Context} = lists:foldl(fun comb_parts_fold/2, {All, Keep0, 0, undefined, 0, [], riak_cs_utils:md5_init()}, PartETags), To extract parts to be deleted , use ? PART_MANIFEST.part_id because { PartNum , ETag } pair is NOT unique in the set of ? PART_MANIFEST 's . KeepPartIDs = [PM?PART_MANIFEST.part_id || PM <- KeepPMs], ToDelete = [PM || PM <- Parts, not lists:member(PM?PART_MANIFEST.part_id, KeepPartIDs)], lager:debug("Part count to be deleted at completion = ~p~n", [length(ToDelete)]), {KeepBytes, riak_cs_utils:md5_final(MD5Context), lists:reverse(KeepPMs), ToDelete}. comb_parts_fold({LastPartNum, LastPartETag} = _K, {_All, _Keep, LastPartNum, LastPartETag, _Bytes, _KeepPMs, _} = Acc) -> Acc; comb_parts_fold({PartNum, _ETag} = _K, {_All, _Keep, LastPartNum, _LastPartETag, _Bytes, _KeepPMs, _}) when PartNum =< LastPartNum orelse PartNum < 1 -> throw(bad_etag_order); comb_parts_fold({PartNum, ETag} = K, {All, Keep, _LastPartNum, _LastPartETag, Bytes, KeepPMs, MD5Context}) -> case {dict:find(K, All), dict:is_key(K, Keep)} of {{ok, PM}, false} -> {All, dict:store(K, true, Keep), PartNum, ETag, Bytes + PM?PART_MANIFEST.content_length, [PM|KeepPMs], riak_cs_utils:md5_update(MD5Context, ETag)}; _X -> throw(bad_etag) end. move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid) -> PartDelMs = [{P_UUID, riak_cs_lfs_utils:new_manifest( Bucket, Key, P_UUID, ContentLength, <<"x-delete/now">>, undefined, [], P_BlockSize, no_acl_yet, [], undefined, BagId)} || ?PART_MANIFEST{part_id=P_UUID, content_length=ContentLength, block_size=P_BlockSize} <- PartsToDelete], ok = riak_cs_gc:move_manifests_to_gc_bucket(PartDelMs, RcPid). enforce_part_size(PartsToKeep) -> case riak_cs_config:enforce_multipart_part_size() of true -> eval_part_sizes([P?PART_MANIFEST.content_length || P <- PartsToKeep]); false -> true end. eval_part_sizes([]) -> true; eval_part_sizes([_]) -> true; eval_part_sizes(L) -> case lists:min(lists:sublist(L, length(L)-1)) of X when X < ?MIN_MP_PART_SIZE -> throw(entity_too_small); _ -> true end. %% The intent of the wrap_* functions is to make this module's code flexible enough to support two methods of operation : %% 1 . Allocate its own Riak client pids ( as originally written ) 2 . Use a Riak client pid passed in by caller ( later to interface with WM ) %% If we 're to allocate our own Riak client pids , we use the atom ' nopid ' . wrap_riak_client(nopid) -> case riak_cs_riak_client:checkout() of {ok, RcPid} -> {ok, {local_pid, RcPid}}; Else -> Else end; wrap_riak_client(RcPid) -> {ok, {remote_pid, RcPid}}. wrap_close_riak_client({local_pid, RcPid}) -> riak_cs_riak_client:checkin(RcPid); wrap_close_riak_client({remote_pid, _RcPid}) -> ok. get_riak_client_pid({local_pid, RcPid}) -> RcPid; get_riak_client_pid({remote_pid, RcPid}) -> RcPid. -spec get_mp_manifest(lfs_manifest()) -> multipart_manifest() | 'undefined'. get_mp_manifest(?MANIFEST{props = Props}) when is_list(Props) -> %% TODO: When the version number of the multipart_manifest_v1 changes %% to version v2 and beyond, this might be a good place to add %% a record conversion function to handle older versions of %% the multipart record? proplists:get_value(multipart, Props, undefined); get_mp_manifest(_) -> undefined. replace_mp_manifest(MpM, Props) -> [{multipart, MpM}|proplists:delete(multipart, Props)]. %% =================================================================== EUnit tests %% =================================================================== -ifdef(TEST). eval_part_sizes_test() -> true = eval_part_sizes_wrapper([]), true = eval_part_sizes_wrapper([999888777]), true = eval_part_sizes_wrapper([777]), false = eval_part_sizes_wrapper([1,51048576,51048576,51048576,436276]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576,436276]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576,436276]), false = eval_part_sizes_wrapper([1,51048576,51048576,51048576]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576]), true = eval_part_sizes_wrapper([51048576,51048576,51048576,1]), ok. eval_part_sizes_wrapper(L) -> try eval_part_sizes(L) catch throw:entity_too_small -> false end. comb_parts_test() -> Num = 5, GoodETags = [{X, <<(X+$0):8>>} || X <- lists:seq(1, Num)], GoodDones = [{ETag, ETag} || {_, ETag} <- GoodETags], PMs = [?PART_MANIFEST{part_number = X, part_id = Y, content_length = X} || {X, Y} <- GoodETags], BadETags = [{X, <<(X+$0):8>>} || X <- lists:seq(Num + 1, Num + 1 + Num)], MpM1 = ?MULTIPART_MANIFEST{parts = ordsets:from_list(PMs), done_parts = ordsets:from_list(GoodDones)}, try _ = comb_parts(MpM1, GoodETags ++ BadETags), throw(test_failed) catch throw:bad_etag -> ok end, try _ = comb_parts(MpM1, [lists:last(GoodETags)|tl(GoodETags)]), throw(test_failed) catch throw:bad_etag_order -> ok end, MD51 = riak_cs_utils:md5_final(lists:foldl(fun({_, ETag}, MD5Context) -> riak_cs_utils:md5_update(MD5Context, ETag) end, riak_cs_utils:md5_init(), GoodETags)), MD52 = riak_cs_utils:md5_final(lists:foldl(fun({_, ETag}, MD5Context) -> riak_cs_utils:md5_update(MD5Context, ETag) end, riak_cs_utils:md5_init(), tl(GoodETags))), {15, MD51, Keep1, []} = comb_parts(MpM1, GoodETags), 5 = length(Keep1), Keep1 = lists:usort(Keep1), {14, MD52, Keep2, [PM2]} = comb_parts(MpM1, tl(GoodETags)), 4 = length(Keep2), Keep2 = lists:usort(Keep2), 1 = PM2?PART_MANIFEST.part_number, ok. -ifdef(EQC). eval_part_sizes_eqc_test() -> true = eqc:quickcheck(eqc:numtests(500, prop_part_sizes())). prop_part_sizes() -> Min = ?MIN_MP_PART_SIZE, Min_1 = Min - 1, MinMinus100 = Min - 100, MinPlus100 = Min + 100, ?FORALL({L, Last, Either}, {list(choose(Min, MinPlus100)), choose(0, Min_1), choose(MinMinus100, MinPlus100)}, true == eval_part_sizes_wrapper(L ++ [Last]) andalso false == eval_part_sizes_wrapper(L ++ [Min_1] ++ L ++ [Either]) ). EQC -endif.
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/src/riak_cs_mp_utils.erl
erlang
--------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------- @doc export Public API =================================================================== API =================================================================== owners have some privileges for multipart uploads performed by other users, i.e, see those MP uploads via list multipart uploads, one that includes the object owner and one that does not. Return same value to caller, regardless of ok/catch This was shamelessly ripped out of #L492 accept whatever the user says caller = bucket owner @doc TODO: add object metadata here, e.g. content-disposition et al. we won't know the md5 of a multipart Cluster ID and Bag ID are added later Once upon a time, in a naive land far away, I thought that it would complete the uploaded object. However, 's3cmd' want to use the issue a warning if that checksum expectation isn't met. So, now we the ?MULTIPART_MANIFEST in a mergeable way. {sigh} =================================================================== =================================================================== the file contents for ETag for a completeted multipart upload. However, if we add the hypen suffix here, e.g., "-1", then extra hex digits "2d31" instead. So, hrm, what to do here. &#203436 BogoMD5 = iolist_to_binary([UUID, "-1"]), If [] = PartsToDelete, then we only need to update the manifest once. Create fake S3 object manifests for this part, deletion. TODO: technically, start_time /= last_modified @doc Will cause error:{badmatch, {m_ibco, _}} if CallerKeyId does not exist TODO: Strictly speaking, this implementation could have problems with MD5 hash collisions. I'd *really* wanted "Once upon a time" comment for upload_part_finished() above). According to AWS S3 docs, we're supposed to take The intent of the wrap_* functions is to make this module's code TODO: When the version number of the multipart_manifest_v1 changes to version v2 and beyond, this might be a good place to add a record conversion function to handle older versions of the multipart record? =================================================================== ===================================================================
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_cs_mp_utils). -include("riak_cs.hrl"). -include_lib("riak_pb/include/riak_pb_kv_codec.hrl"). -include_lib("riakc/include/riakc.hrl"). -ifdef(TEST). -compile(export_all). -ifdef(EQC). -include_lib("eqc/include/eqc.hrl"). -endif. -include_lib("eunit/include/eunit.hrl"). -endif. -define(MIN_MP_PART_SIZE, (5*1024*1024)). -define(PID(WrappedRcPid), get_riak_client_pid(WrappedRcPid)). -export([ abort_multipart_upload/4, abort_multipart_upload/5, calc_multipart_2i_dict/3, clean_multipart_unused_parts/2, complete_multipart_upload/5, complete_multipart_upload/6, initiate_multipart_upload/5, initiate_multipart_upload/6, list_all_multipart_uploads/3, list_multipart_uploads/3, list_multipart_uploads/4, list_parts/5, list_parts/6, make_content_types_accepted/2, make_content_types_accepted/3, upload_part/6, upload_part/7, upload_part_1blob/2, upload_part_finished/7, upload_part_finished/8, is_multipart_manifest/1 ]). -export([get_mp_manifest/1]). calc_multipart_2i_dict(Ms, Bucket, _Key) when is_list(Ms) -> According to API Version 2006 - 03 - 01 , page 139 - 140 , bucket and cancel multipart upload . We use two different 2I index entries to allow 2I to do the work of segregating multipart upload requests of bucket owner vs. non - bucket owner via two different 2I entries , L_2i = [ case get_mp_manifest(M) of undefined -> []; MpM when is_record(MpM, ?MULTIPART_MANIFEST_RECNAME) -> [{make_2i_key(Bucket, MpM?MULTIPART_MANIFEST.owner), <<"1">>}, {make_2i_key(Bucket), <<"1">>}] end || M <- Ms, M?MANIFEST.state == writing], {?MD_INDEX, lists:usort(lists:append(L_2i))}. abort_multipart_upload(Bucket, Key, UploadId, Caller) -> abort_multipart_upload(Bucket, Key, UploadId, Caller, nopid). abort_multipart_upload(Bucket, Key, UploadId, Caller, RcPidUnW) -> do_part_common(abort, Bucket, Key, UploadId, Caller, [], RcPidUnW). clean_multipart_unused_parts(?MANIFEST{bkey=BKey, props=Props} = Manifest, RcPid) -> case get_mp_manifest(Manifest) of undefined -> same; MpM -> case {proplists:get_value(multipart_clean, Props, false), MpM?MULTIPART_MANIFEST.cleanup_parts} of {false, []} -> same; {false, PartsToDelete} -> _ = try {Bucket, Key} = BKey, BagId = riak_cs_mb_helper:bag_id_from_manifest(Manifest), ok = move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid), UpdManifest = Manifest?MANIFEST{props=[multipart_clean|Props]}, ok = update_manifest_with_confirmation(RcPid, UpdManifest) catch X:Y -> lager:debug("clean_multipart_unused_parts: " "bkey ~p: ~p ~p @ ~p\n", [BKey, X, Y, erlang:get_stacktrace()]) end, updated; {true, _} -> same end end. complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller) -> complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller, nopid). complete_multipart_upload(Bucket, Key, UploadId, PartETags, Caller, RcPidUnW) -> Extra = {PartETags}, do_part_common(complete, Bucket, Key, UploadId, Caller, [{complete, Extra}], RcPidUnW). initiate_multipart_upload(Bucket, Key, ContentType, Owner, Opts) -> initiate_multipart_upload(Bucket, Key, ContentType, Owner, Opts, nopid). initiate_multipart_upload(Bucket, Key, ContentType, {_,_,_} = Owner, Opts, RcPidUnW) -> write_new_manifest(new_manifest(Bucket, Key, ContentType, Owner, Opts), Opts, RcPidUnW). make_content_types_accepted(RD, Ctx) -> make_content_types_accepted(RD, Ctx, unused_callback). make_content_types_accepted(RD, Ctx, Callback) -> make_content_types_accepted(wrq:get_req_header("Content-Type", RD), RD, Ctx, Callback). make_content_types_accepted(CT, RD, Ctx, Callback) when CT =:= undefined; CT =:= [] -> make_content_types_accepted("application/octet-stream", RD, Ctx, Callback); make_content_types_accepted(CT, RD, Ctx=#context{local_context=LocalCtx0}, Callback) -> {Media, _Params} = mochiweb_util:parse_header(CT), case string:tokens(Media, "/") of [_Type, _Subtype] -> LocalCtx = LocalCtx0#key_context{putctype=Media}, {[{Media, Callback}], RD, Ctx#context{local_context=LocalCtx}}; _ -> {[], wrq:set_resp_header( "Content-Type", "text/plain", wrq:set_resp_body( ["\"", Media, "\"" " is not a valid media type" " for the Content-type header.\n"], RD)), Ctx} end. list_multipart_uploads(Bucket, Caller, Opts) -> list_multipart_uploads(Bucket, Caller, Opts, nopid). list_multipart_uploads(Bucket, {_Display, _Canon, CallerKeyId} = Caller, Opts, RcPidUnW) -> case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try BucketOwnerP = is_caller_bucket_owner(?PID(RcPid), Bucket, CallerKeyId), Key2i = case BucketOwnerP of true -> false -> make_2i_key(Bucket, Caller) end, list_multipart_uploads_with_2ikey(Bucket, Opts, ?PID(RcPid), Key2i) catch error:{badmatch, {m_icbo, _}} -> {error, access_denied} after wrap_close_riak_client(RcPid) end; Else -> Else end. list_all_multipart_uploads(Bucket, Opts, RcPid) -> list_multipart_uploads_with_2ikey(Bucket, Opts, RcPid, make_2i_key(Bucket)). list_multipart_uploads_with_2ikey(Bucket, Opts, RcPid, Key2i) -> HashBucket = riak_cs_utils:to_bucket_name(objects, Bucket), {ok, ManifestPbc} = riak_cs_riak_client:manifest_pbc(RcPid), Timeout = riak_cs_config:get_index_list_multipart_uploads_timeout(), case riak_cs_pbc:get_index_eq(ManifestPbc, HashBucket, Key2i, <<"1">>, [{timeout, Timeout}], [riakc, get_uploads_by_index]) of {ok, ?INDEX_RESULTS{keys=Names}} -> {ok, list_multipart_uploads2(Bucket, RcPid, Names, Opts)}; Else2 -> Else2 end. list_parts(Bucket, Key, UploadId, Caller, Opts) -> list_parts(Bucket, Key, UploadId, Caller, Opts, nopid). list_parts(Bucket, Key, UploadId, Caller, Opts, RcPidUnW) -> Extra = {Opts}, do_part_common(list, Bucket, Key, UploadId, Caller, [{list, Extra}], RcPidUnW). -spec new_manifest(binary(), binary(), binary(), acl_owner(), list()) -> lfs_manifest(). new_manifest(Bucket, Key, ContentType, {_, _, _} = Owner, Opts) -> UUID = druuid:v4(), MetaData = case proplists:get_value(meta_data, Opts) of undefined -> []; AsIsHdrs -> AsIsHdrs end, M = riak_cs_lfs_utils:new_manifest(Bucket, Key, UUID, 0, ContentType, undefined, MetaData, riak_cs_lfs_utils:block_size(), ACL : needs client pid , so we wait no_acl_yet, [], undefined, undefined), MpM = ?MULTIPART_MANIFEST{upload_id = UUID, owner = Owner}, M?MANIFEST{props = replace_mp_manifest(MpM, M?MANIFEST.props)}. upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller) -> upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller, nopid). upload_part(Bucket, Key, UploadId, PartNumber, Size, Caller, RcPidUnW) -> Extra = {Bucket, Key, UploadId, Caller, PartNumber, Size}, do_part_common(upload_part, Bucket, Key, UploadId, Caller, [{upload_part, Extra}], RcPidUnW). upload_part_1blob(PutPid, Blob) -> ok = riak_cs_put_fsm:augment_data(PutPid, Blob), {ok, M} = riak_cs_put_fsm:finalize(PutPid, undefined), {ok, M?MANIFEST.content_md5}. be sufficient to use each part 's UUID as the ETag when the part upload was finished , and thus the client would use that UUID to ETag of each uploaded part to be the MD5(part content ) and will must thread the MD5 value through upload_part_finished and update upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller) -> upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller, nopid). upload_part_finished(Bucket, Key, UploadId, _PartNumber, PartUUID, MD5, Caller, RcPidUnW) -> Extra = {PartUUID, MD5}, do_part_common(upload_part_finished, Bucket, Key, UploadId, Caller, [{upload_part_finished, Extra}], RcPidUnW). write_new_manifest(?MANIFEST{bkey={Bucket, Key}, uuid=UUID}=M, Opts, RcPidUnW) -> MpM = get_mp_manifest(M), Owner = MpM?MULTIPART_MANIFEST.owner, case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try Acl = case proplists:get_value(acl, Opts) of undefined -> riak_cs_acl_utils:canned_acl("private", Owner, undefined); AnAcl -> AnAcl end, BagId = riak_cs_mb_helper:choose_bag_id(block, {Bucket, Key, UUID}), M2 = riak_cs_lfs_utils:set_bag_id(BagId, M), ClusterId = riak_cs_mb_helper:cluster_id(BagId), M3 = M2?MANIFEST{acl = Acl, cluster_id=ClusterId, write_start_time=os:timestamp()}, {ok, ManiPid} = riak_cs_manifest_fsm:start_link(Bucket, Key, ?PID(RcPid)), try ok = riak_cs_manifest_fsm:add_new_manifest(ManiPid, M3), {ok, M3?MANIFEST.uuid} after ok = riak_cs_manifest_fsm:stop(ManiPid) end after wrap_close_riak_client(RcPid) end; Else -> Else end. Internal functions do_part_common(Op, Bucket, Key, UploadId, {_,_,CallerKeyId} = _Caller, Props, RcPidUnW) -> case wrap_riak_client(RcPidUnW) of {ok, RcPid} -> try case riak_cs_manifest:get_manifests(?PID(RcPid), Bucket, Key) of {ok, Obj, Manifests} -> case find_manifest_with_uploadid(UploadId, Manifests) of false -> {error, notfound}; M when M?MANIFEST.state == writing -> MpM = get_mp_manifest(M), {_, _, MpMOwner} = MpM?MULTIPART_MANIFEST.owner, case CallerKeyId == MpMOwner of true -> do_part_common2(Op, ?PID(RcPid), M, Obj, MpM, Props); false -> {error, access_denied} end; _ -> {error, notfound} end; Else2 -> Else2 end catch error:{badmatch, {m_icbo, _}} -> {error, access_denied}; error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable} after wrap_close_riak_client(RcPid) end; Else -> Else end. do_part_common2(abort, RcPid, M, Obj, _Mpm, _Props) -> {Bucket, Key} = M?MANIFEST.bkey, case riak_cs_gc:gc_specific_manifests( [M?MANIFEST.uuid], Obj, Bucket, Key, RcPid) of {ok, _NewObj} -> ok; Else3 -> Else3 end; do_part_common2(complete, RcPid, ?MANIFEST{uuid = _UUID, props = MProps} = Manifest, _Obj, MpM, Props) -> The content_md5 is used by WM to create the ETags header . However / fortunately / sigh - of - relief , Amazon 's S3 does n't use the WM will simply convert that suffix to {PartETags} = proplists:get_value(complete, Props), try {Bucket, Key} = Manifest?MANIFEST.bkey, {ok, ManiPid} = riak_cs_manifest_fsm:start_link(Bucket, Key, RcPid), try {Bytes, OverAllMD5, PartsToKeep, PartsToDelete} = comb_parts(MpM, PartETags), true = enforce_part_size(PartsToKeep), NewMpM = MpM?MULTIPART_MANIFEST{parts = PartsToKeep, done_parts = [], cleanup_parts = PartsToDelete}, MProps2 = case PartsToDelete of [] -> [multipart_clean] ++ replace_mp_manifest(NewMpM, MProps); _ -> replace_mp_manifest(NewMpM, MProps) end, ContentMD5 = {OverAllMD5, "-" ++ integer_to_list(ordsets:size(PartsToKeep))}, NewManifest = Manifest?MANIFEST{state = active, content_length = Bytes, content_md5 = ContentMD5, props = MProps2}, ok = riak_cs_manifest_fsm:add_new_manifest(ManiPid, NewManifest), case PartsToDelete of [] -> {ok, NewManifest}; _ -> then pass them to the GC monster for immediate BagId = riak_cs_mb_helper:bag_id_from_manifest(NewManifest), ok = move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid), MProps3 = [multipart_clean|MProps2], New2Manifest = NewManifest?MANIFEST{props = MProps3}, ok = riak_cs_manifest_fsm:update_manifest( ManiPid, New2Manifest), {ok, New2Manifest} end after ok = riak_cs_manifest_fsm:stop(ManiPid) end catch error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable}; throw:bad_etag -> {error, bad_etag}; throw:bad_etag_order -> {error, bad_etag_order}; throw:entity_too_small -> {error, entity_too_small} end; do_part_common2(list, _RcPid, _M, _Obj, MpM, Props) -> {_Opts} = proplists:get_value(list, Props), ?MULTIPART_MANIFEST{parts = Parts, done_parts = DoneParts0} = MpM, DoneParts = orddict:from_list(ordsets:to_list(DoneParts0)), ETagPs = lists:foldl(fun(P, Acc) -> case orddict:find(P?PART_MANIFEST.part_id, DoneParts) of error -> Acc; {ok, ETag} -> [{ETag, P}|Acc] end end, [], Parts), Ds = [?PART_DESCR{part_number = P?PART_MANIFEST.part_number, last_modified = riak_cs_wm_utils:iso_8601_datetime(calendar:now_to_local_time(P?PART_MANIFEST.start_time)), etag = ETag, size = P?PART_MANIFEST.content_length} || {ETag, P} <- ETagPs], {ok, Ds}; do_part_common2(upload_part, RcPid, M, _Obj, MpM, Props) -> {Bucket, Key, _UploadId, _Caller, PartNumber, Size} = proplists:get_value(upload_part, Props), BlockSize = riak_cs_lfs_utils:block_size(), BagId = riak_cs_mb_helper:bag_id_from_manifest(M), {ok, PutPid} = riak_cs_put_fsm:start_link( {Bucket, Key, Size, <<"x-riak/multipart-part">>, orddict:new(), BlockSize, M?MANIFEST.acl, infinity, self(), RcPid}, false, BagId), try ?MANIFEST{content_length = ContentLength, props = MProps} = M, ?MULTIPART_MANIFEST{parts = Parts} = MpM, PartUUID = riak_cs_put_fsm:get_uuid(PutPid), PM = ?PART_MANIFEST{bucket = Bucket, key = Key, start_time = os:timestamp(), part_number = PartNumber, part_id = PartUUID, content_length = Size, block_size = BlockSize}, NewMpM = MpM?MULTIPART_MANIFEST{parts = ordsets:add_element(PM, Parts)}, NewM = M?MANIFEST{content_length = ContentLength + Size, props = replace_mp_manifest(NewMpM, MProps)}, ok = update_manifest_with_confirmation(RcPid, NewM), {upload_part_ready, PartUUID, PutPid} catch error:{badmatch, {m_umwc, _}} -> riak_cs_put_fsm:force_stop(PutPid), {error, riak_unavailable} end; do_part_common2(upload_part_finished, RcPid, M, _Obj, MpM, Props) -> {PartUUID, MD5} = proplists:get_value(upload_part_finished, Props), try ?MULTIPART_MANIFEST{parts = Parts, done_parts = DoneParts} = MpM, DoneUUIDs = ordsets:from_list([UUID || {UUID, _ETag} <- DoneParts]), case {lists:keyfind(PartUUID, ?PART_MANIFEST.part_id, ordsets:to_list(Parts)), ordsets:is_element(PartUUID, DoneUUIDs)} of {false, _} -> {error, notfound}; {_, true} -> {error, notfound}; {PM, false} when is_record(PM, ?PART_MANIFEST_RECNAME) -> ?MANIFEST{props = MProps} = M, NewMpM = MpM?MULTIPART_MANIFEST{ done_parts = ordsets:add_element({PartUUID, MD5}, DoneParts)}, NewM = M?MANIFEST{props = replace_mp_manifest(NewMpM, MProps)}, ok = update_manifest_with_confirmation(RcPid, NewM) end catch error:{badmatch, {m_umwc, _}} -> {error, riak_unavailable} end. update_manifest_with_confirmation(RcPid, Manifest) -> {Bucket, Key} = Manifest?MANIFEST.bkey, {m_umwc, {ok, ManiPid}} = {m_umwc, riak_cs_manifest_fsm:start_link(Bucket, Key, RcPid)}, try ok = riak_cs_manifest_fsm:update_manifest_with_confirmation(ManiPid, Manifest) after ok = riak_cs_manifest_fsm:stop(ManiPid) end. -spec make_2i_key(binary()) -> binary(). make_2i_key(Bucket) -> make_2i_key2(Bucket, ""). -spec make_2i_key(binary(), acl_owner()) -> binary(). make_2i_key(Bucket, {_, _, OwnerStr}) -> make_2i_key2(Bucket, OwnerStr). -spec make_2i_key2(binary(), string()) -> binary(). make_2i_key2(Bucket, OwnerStr) -> iolist_to_binary(["rcs@", OwnerStr, "@", Bucket, "_bin"]). list_multipart_uploads2(Bucket, RcPid, Names, Opts) -> FilterFun = fun(K, Acc) -> filter_uploads_list(Bucket, K, Opts, RcPid, Acc) end, {Manifests, Prefixes} = lists:foldl(FilterFun, {[], ordsets:new()}, Names), {lists:sort(Manifests), ordsets:to_list(Prefixes)}. filter_uploads_list(Bucket, Key, Opts, RcPid, Acc) -> multipart_manifests_for_key(Bucket, Key, Opts, Acc, RcPid). parameter_filter(M, Acc, _, _, KeyMarker, _) when M?MULTIPART_DESCR.key =< KeyMarker-> Acc; parameter_filter(M, Acc, _, _, KeyMarker, UploadIdMarker) when M?MULTIPART_DESCR.key =< KeyMarker andalso M?MULTIPART_DESCR.upload_id =< UploadIdMarker -> Acc; parameter_filter(M, {Manifests, Prefixes}, undefined, undefined, _, _) -> {[M | Manifests], Prefixes}; parameter_filter(M, Acc, undefined, Delimiter, _, _) -> Group = extract_group(M?MULTIPART_DESCR.key, Delimiter), update_keys_and_prefixes(Acc, M, <<>>, 0, Group); parameter_filter(M, {Manifests, Prefixes}, Prefix, undefined, _, _) -> PrefixLen = byte_size(Prefix), case M?MULTIPART_DESCR.key of << Prefix:PrefixLen/binary, _/binary >> -> {[M | Manifests], Prefixes}; _ -> {Manifests, Prefixes} end; parameter_filter(M, {Manifests, Prefixes}=Acc, Prefix, Delimiter, _, _) -> PrefixLen = byte_size(Prefix), case M?MULTIPART_DESCR.key of << Prefix:PrefixLen/binary, Rest/binary >> -> Group = extract_group(Rest, Delimiter), update_keys_and_prefixes(Acc, M, Prefix, PrefixLen, Group); _ -> {Manifests, Prefixes} end. extract_group(Key, Delimiter) -> case binary:match(Key, [Delimiter]) of nomatch -> nomatch; {Pos, Len} -> binary:part(Key, {0, Pos+Len}) end. update_keys_and_prefixes({Keys, Prefixes}, Key, _, _, nomatch) -> {[Key | Keys], Prefixes}; update_keys_and_prefixes({Keys, Prefixes}, _, Prefix, PrefixLen, Group) -> NewPrefix = << Prefix:PrefixLen/binary, Group/binary >>, {Keys, ordsets:add_element(NewPrefix, Prefixes)}. multipart_manifests_for_key(Bucket, Key, Opts, Acc, RcPid) -> ParameterFilter = build_parameter_filter(Opts), Manifests = handle_get_manifests_result( riak_cs_manifest:get_manifests(RcPid, Bucket, Key)), lists:foldl(ParameterFilter, Acc, Manifests). build_parameter_filter(Opts) -> Prefix = proplists:get_value(prefix, Opts), Delimiter = proplists:get_value(delimiter, Opts), KeyMarker = proplists:get_value(key_marker, Opts), UploadIdMarker = base64url:decode( proplists:get_value(upload_id_marker, Opts)), build_parameter_filter(Prefix, Delimiter, KeyMarker, UploadIdMarker). build_parameter_filter(Prefix, Delimiter, KeyMarker, UploadIdMarker) -> fun(Key, Acc) -> parameter_filter(Key, Acc, Prefix, Delimiter, KeyMarker, UploadIdMarker) end. handle_get_manifests_result({ok, _Obj, Manifests}) -> [multipart_description(M) || {_, M} <- Manifests, M?MANIFEST.state == writing, is_multipart_manifest(M)]; handle_get_manifests_result(_) -> []. -spec is_multipart_manifest(?MANIFEST{}) -> boolean(). is_multipart_manifest(?MANIFEST{props=Props}) -> case proplists:get_value(multipart, Props) of undefined -> false; _ -> true end. -spec multipart_description(?MANIFEST{}) -> ?MULTIPART_DESCR{}. multipart_description(Manifest) -> MpM = proplists:get_value(multipart, Manifest?MANIFEST.props), ?MULTIPART_DESCR{ key = element(2, Manifest?MANIFEST.bkey), upload_id = Manifest?MANIFEST.uuid, owner_key_id = element(3, MpM?MULTIPART_MANIFEST.owner), owner_display = element(1, MpM?MULTIPART_MANIFEST.owner), initiated = Manifest?MANIFEST.created}. is_caller_bucket_owner(RcPid, Bucket, CallerKeyId) -> {m_icbo, {ok, {C, _}}} = {m_icbo, riak_cs_user:get_user(CallerKeyId, RcPid)}, Buckets = [iolist_to_binary(B?RCS_BUCKET.name) || B <- riak_cs_bucket:get_buckets(C)], lists:member(Bucket, Buckets). find_manifest_with_uploadid(UploadId, Manifests) -> case lists:keyfind(UploadId, 1, Manifests) of false -> false; {UploadId, M} -> M end. @doc In # 885 ( ) it happened to be revealed that ETag is generated as > ETag = MD5(Sum(p \in numberParts , MD5(PartBytes(p ) ) ) + " - " + numberParts by an Amazon support guy , . -spec comb_parts(multipart_manifest(), list({non_neg_integer(), binary()})) -> {KeepBytes::non_neg_integer(), OverAllMD5::binary(), PartsToKeep::list(), PartsToDelete::list()}. comb_parts(MpM, PartETags) -> Done = orddict:from_list(ordsets:to_list(MpM?MULTIPART_MANIFEST.done_parts)), to avoid using MD5 hash used as the part ETags ( see the the newest part that has this { PartNum , ETag } pair . Parts0 = ordsets:to_list(MpM?MULTIPART_MANIFEST.parts), FindOrSet = fun(Key, Dict) -> case orddict:find(Key, Dict) of {ok, Value} -> Value; error -> <<>> end end, Parts = [P?PART_MANIFEST{content_md5 = FindOrSet(P?PART_MANIFEST.part_id, Done)} || P <- Parts0], All = dict:from_list( [{{PM?PART_MANIFEST.part_number, PM?PART_MANIFEST.content_md5}, PM} || PM <- Parts]), Keep0 = dict:new(), {_, _Keep, _, _, KeepBytes, KeepPMs, MD5Context} = lists:foldl(fun comb_parts_fold/2, {All, Keep0, 0, undefined, 0, [], riak_cs_utils:md5_init()}, PartETags), To extract parts to be deleted , use ? PART_MANIFEST.part_id because { PartNum , ETag } pair is NOT unique in the set of ? PART_MANIFEST 's . KeepPartIDs = [PM?PART_MANIFEST.part_id || PM <- KeepPMs], ToDelete = [PM || PM <- Parts, not lists:member(PM?PART_MANIFEST.part_id, KeepPartIDs)], lager:debug("Part count to be deleted at completion = ~p~n", [length(ToDelete)]), {KeepBytes, riak_cs_utils:md5_final(MD5Context), lists:reverse(KeepPMs), ToDelete}. comb_parts_fold({LastPartNum, LastPartETag} = _K, {_All, _Keep, LastPartNum, LastPartETag, _Bytes, _KeepPMs, _} = Acc) -> Acc; comb_parts_fold({PartNum, _ETag} = _K, {_All, _Keep, LastPartNum, _LastPartETag, _Bytes, _KeepPMs, _}) when PartNum =< LastPartNum orelse PartNum < 1 -> throw(bad_etag_order); comb_parts_fold({PartNum, ETag} = K, {All, Keep, _LastPartNum, _LastPartETag, Bytes, KeepPMs, MD5Context}) -> case {dict:find(K, All), dict:is_key(K, Keep)} of {{ok, PM}, false} -> {All, dict:store(K, true, Keep), PartNum, ETag, Bytes + PM?PART_MANIFEST.content_length, [PM|KeepPMs], riak_cs_utils:md5_update(MD5Context, ETag)}; _X -> throw(bad_etag) end. move_dead_parts_to_gc(Bucket, Key, BagId, PartsToDelete, RcPid) -> PartDelMs = [{P_UUID, riak_cs_lfs_utils:new_manifest( Bucket, Key, P_UUID, ContentLength, <<"x-delete/now">>, undefined, [], P_BlockSize, no_acl_yet, [], undefined, BagId)} || ?PART_MANIFEST{part_id=P_UUID, content_length=ContentLength, block_size=P_BlockSize} <- PartsToDelete], ok = riak_cs_gc:move_manifests_to_gc_bucket(PartDelMs, RcPid). enforce_part_size(PartsToKeep) -> case riak_cs_config:enforce_multipart_part_size() of true -> eval_part_sizes([P?PART_MANIFEST.content_length || P <- PartsToKeep]); false -> true end. eval_part_sizes([]) -> true; eval_part_sizes([_]) -> true; eval_part_sizes(L) -> case lists:min(lists:sublist(L, length(L)-1)) of X when X < ?MIN_MP_PART_SIZE -> throw(entity_too_small); _ -> true end. flexible enough to support two methods of operation : 1 . Allocate its own Riak client pids ( as originally written ) 2 . Use a Riak client pid passed in by caller ( later to interface with WM ) If we 're to allocate our own Riak client pids , we use the atom ' nopid ' . wrap_riak_client(nopid) -> case riak_cs_riak_client:checkout() of {ok, RcPid} -> {ok, {local_pid, RcPid}}; Else -> Else end; wrap_riak_client(RcPid) -> {ok, {remote_pid, RcPid}}. wrap_close_riak_client({local_pid, RcPid}) -> riak_cs_riak_client:checkin(RcPid); wrap_close_riak_client({remote_pid, _RcPid}) -> ok. get_riak_client_pid({local_pid, RcPid}) -> RcPid; get_riak_client_pid({remote_pid, RcPid}) -> RcPid. -spec get_mp_manifest(lfs_manifest()) -> multipart_manifest() | 'undefined'. get_mp_manifest(?MANIFEST{props = Props}) when is_list(Props) -> proplists:get_value(multipart, Props, undefined); get_mp_manifest(_) -> undefined. replace_mp_manifest(MpM, Props) -> [{multipart, MpM}|proplists:delete(multipart, Props)]. EUnit tests -ifdef(TEST). eval_part_sizes_test() -> true = eval_part_sizes_wrapper([]), true = eval_part_sizes_wrapper([999888777]), true = eval_part_sizes_wrapper([777]), false = eval_part_sizes_wrapper([1,51048576,51048576,51048576,436276]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576,436276]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576,436276]), false = eval_part_sizes_wrapper([1,51048576,51048576,51048576]), false = eval_part_sizes_wrapper([51048576,1,51048576,51048576]), true = eval_part_sizes_wrapper([51048576,51048576,51048576,1]), ok. eval_part_sizes_wrapper(L) -> try eval_part_sizes(L) catch throw:entity_too_small -> false end. comb_parts_test() -> Num = 5, GoodETags = [{X, <<(X+$0):8>>} || X <- lists:seq(1, Num)], GoodDones = [{ETag, ETag} || {_, ETag} <- GoodETags], PMs = [?PART_MANIFEST{part_number = X, part_id = Y, content_length = X} || {X, Y} <- GoodETags], BadETags = [{X, <<(X+$0):8>>} || X <- lists:seq(Num + 1, Num + 1 + Num)], MpM1 = ?MULTIPART_MANIFEST{parts = ordsets:from_list(PMs), done_parts = ordsets:from_list(GoodDones)}, try _ = comb_parts(MpM1, GoodETags ++ BadETags), throw(test_failed) catch throw:bad_etag -> ok end, try _ = comb_parts(MpM1, [lists:last(GoodETags)|tl(GoodETags)]), throw(test_failed) catch throw:bad_etag_order -> ok end, MD51 = riak_cs_utils:md5_final(lists:foldl(fun({_, ETag}, MD5Context) -> riak_cs_utils:md5_update(MD5Context, ETag) end, riak_cs_utils:md5_init(), GoodETags)), MD52 = riak_cs_utils:md5_final(lists:foldl(fun({_, ETag}, MD5Context) -> riak_cs_utils:md5_update(MD5Context, ETag) end, riak_cs_utils:md5_init(), tl(GoodETags))), {15, MD51, Keep1, []} = comb_parts(MpM1, GoodETags), 5 = length(Keep1), Keep1 = lists:usort(Keep1), {14, MD52, Keep2, [PM2]} = comb_parts(MpM1, tl(GoodETags)), 4 = length(Keep2), Keep2 = lists:usort(Keep2), 1 = PM2?PART_MANIFEST.part_number, ok. -ifdef(EQC). eval_part_sizes_eqc_test() -> true = eqc:quickcheck(eqc:numtests(500, prop_part_sizes())). prop_part_sizes() -> Min = ?MIN_MP_PART_SIZE, Min_1 = Min - 1, MinMinus100 = Min - 100, MinPlus100 = Min + 100, ?FORALL({L, Last, Either}, {list(choose(Min, MinPlus100)), choose(0, Min_1), choose(MinMinus100, MinPlus100)}, true == eval_part_sizes_wrapper(L ++ [Last]) andalso false == eval_part_sizes_wrapper(L ++ [Min_1] ++ L ++ [Either]) ). EQC -endif.
544e4aa68259112ee56388ae1d825d9059507a1364350483b1bf8ec569d6723c
nirum-lang/nirum
PythonSpec.hs
# LANGUAGE OverloadedLists # # LANGUAGE ScopedTypeVariables # module Nirum.Targets.PythonSpec where import qualified Data.Map.Strict as M import Data.Either import System.FilePath ((</>)) import Test.Hspec.Meta import Nirum.Constructs.Annotation hiding (null) import Nirum.Constructs.Annotation.Internal import Nirum.Constructs.Module (Module (Module)) import Nirum.Constructs.TypeDeclaration hiding (Text) import qualified Nirum.Package.Metadata as M import Nirum.Targets.Python ( Source (Source) , parseModulePath ) import Nirum.Targets.Python.CodeGenSpec hiding (spec) spec :: Spec spec = do describe "compilePackage" $ do it "returns a Map of file paths and their contents to generate" $ do let (Source pkg _) = makeDummySource $ Module [] Nothing files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "foo" </> "__init__.py" , "src-py2" </> "foo" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "foo" </> "__init__.py" , "src" </> "foo" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure it "creates an emtpy Python package directory if necessary" $ do let (Source pkg _) = makeDummySource' ["test"] (Module [] Nothing) [] files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "test" </> "__init__.py" , "src-py2" </> "test" </> "foo" </> "__init__.py" , "src-py2" </> "test" </> "foo" </> "bar" </> "__init__.py" , "src-py2" </> "test" </> "qux" </> "__init__.py" , "src" </> "test" </> "__init__.py" , "src" </> "test" </> "foo" </> "__init__.py" , "src" </> "test" </> "foo" </> "bar" </> "__init__.py" , "src" </> "test" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure it "generates renamed package dirs if renames are configured" $ do let (Source pkg _) = makeDummySource' [] (Module [] Nothing) [(["foo"], ["quz"])] files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "quz" </> "__init__.py" , "src-py2" </> "quz" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "quz" </> "__init__.py" , "src" </> "quz" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure let (Source pkg' _) = makeDummySource' [] (Module [] Nothing) [(["foo", "bar"], ["bar"])] files' = M.compilePackage pkg' directoryStructure' = [ "src-py2" </> "foo" </> "__init__.py" , "src-py2" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "foo" </> "__init__.py" , "src" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files' `shouldBe` directoryStructure' specify "parseModulePath" $ do parseModulePath "" `shouldBe` Nothing parseModulePath "foo" `shouldBe` Just ["foo"] parseModulePath "foo.bar" `shouldBe` Just ["foo", "bar"] parseModulePath "foo.bar-baz" `shouldBe` Just ["foo", "bar-baz"] parseModulePath "foo." `shouldBe` Nothing parseModulePath "foo.bar." `shouldBe` Nothing parseModulePath ".foo" `shouldBe` Nothing parseModulePath ".foo.bar" `shouldBe` Nothing parseModulePath "foo..bar" `shouldBe` Nothing parseModulePath "foo.bar>" `shouldBe` Nothing parseModulePath "foo.bar-" `shouldBe` Nothing describe "@numeric-constraints" $ do it "fails if unsupported arguments are present" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("unsupported", Integer 2)] ] compareErrorMessage annots it "fails if unsupported arguments type is given" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("max", Text "2")] ] compareErrorMessage annots it "success" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("max", Integer 2)] ] let Just result = getResult annots isRight result `shouldBe` True where compareErrorMessage annots = do let Just result = getResult annots let Left errorMessage = result errorMessage `shouldBe` "Unsupported arguments on @numeric-constraints" getResult annots = let unboxed = TypeDeclaration "foo" (UnboxedType "int32") annots (Source pkg _) = makeDummySource $ Module [unboxed] Nothing files = M.compilePackage pkg in M.lookup ("src" </> "foo" </> "__init__.py") files
null
https://raw.githubusercontent.com/nirum-lang/nirum/4d4488b0524874abc6e693479a5cc70c961bad33/test/Nirum/Targets/PythonSpec.hs
haskell
# LANGUAGE OverloadedLists # # LANGUAGE ScopedTypeVariables # module Nirum.Targets.PythonSpec where import qualified Data.Map.Strict as M import Data.Either import System.FilePath ((</>)) import Test.Hspec.Meta import Nirum.Constructs.Annotation hiding (null) import Nirum.Constructs.Annotation.Internal import Nirum.Constructs.Module (Module (Module)) import Nirum.Constructs.TypeDeclaration hiding (Text) import qualified Nirum.Package.Metadata as M import Nirum.Targets.Python ( Source (Source) , parseModulePath ) import Nirum.Targets.Python.CodeGenSpec hiding (spec) spec :: Spec spec = do describe "compilePackage" $ do it "returns a Map of file paths and their contents to generate" $ do let (Source pkg _) = makeDummySource $ Module [] Nothing files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "foo" </> "__init__.py" , "src-py2" </> "foo" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "foo" </> "__init__.py" , "src" </> "foo" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure it "creates an emtpy Python package directory if necessary" $ do let (Source pkg _) = makeDummySource' ["test"] (Module [] Nothing) [] files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "test" </> "__init__.py" , "src-py2" </> "test" </> "foo" </> "__init__.py" , "src-py2" </> "test" </> "foo" </> "bar" </> "__init__.py" , "src-py2" </> "test" </> "qux" </> "__init__.py" , "src" </> "test" </> "__init__.py" , "src" </> "test" </> "foo" </> "__init__.py" , "src" </> "test" </> "foo" </> "bar" </> "__init__.py" , "src" </> "test" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure it "generates renamed package dirs if renames are configured" $ do let (Source pkg _) = makeDummySource' [] (Module [] Nothing) [(["foo"], ["quz"])] files = M.compilePackage pkg directoryStructure = [ "src-py2" </> "quz" </> "__init__.py" , "src-py2" </> "quz" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "quz" </> "__init__.py" , "src" </> "quz" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files `shouldBe` directoryStructure let (Source pkg' _) = makeDummySource' [] (Module [] Nothing) [(["foo", "bar"], ["bar"])] files' = M.compilePackage pkg' directoryStructure' = [ "src-py2" </> "foo" </> "__init__.py" , "src-py2" </> "bar" </> "__init__.py" , "src-py2" </> "qux" </> "__init__.py" , "src" </> "foo" </> "__init__.py" , "src" </> "bar" </> "__init__.py" , "src" </> "qux" </> "__init__.py" , "setup.py" , "MANIFEST.in" ] M.keysSet files' `shouldBe` directoryStructure' specify "parseModulePath" $ do parseModulePath "" `shouldBe` Nothing parseModulePath "foo" `shouldBe` Just ["foo"] parseModulePath "foo.bar" `shouldBe` Just ["foo", "bar"] parseModulePath "foo.bar-baz" `shouldBe` Just ["foo", "bar-baz"] parseModulePath "foo." `shouldBe` Nothing parseModulePath "foo.bar." `shouldBe` Nothing parseModulePath ".foo" `shouldBe` Nothing parseModulePath ".foo.bar" `shouldBe` Nothing parseModulePath "foo..bar" `shouldBe` Nothing parseModulePath "foo.bar>" `shouldBe` Nothing parseModulePath "foo.bar-" `shouldBe` Nothing describe "@numeric-constraints" $ do it "fails if unsupported arguments are present" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("unsupported", Integer 2)] ] compareErrorMessage annots it "fails if unsupported arguments type is given" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("max", Text "2")] ] compareErrorMessage annots it "success" $ do let Right annots = fromList [ Annotation "numeric-constraints" [("min", Integer 1), ("max", Integer 2)] ] let Just result = getResult annots isRight result `shouldBe` True where compareErrorMessage annots = do let Just result = getResult annots let Left errorMessage = result errorMessage `shouldBe` "Unsupported arguments on @numeric-constraints" getResult annots = let unboxed = TypeDeclaration "foo" (UnboxedType "int32") annots (Source pkg _) = makeDummySource $ Module [unboxed] Nothing files = M.compilePackage pkg in M.lookup ("src" </> "foo" </> "__init__.py") files
be90735ff824e54a9c31c0dda2b47ea85a31cfd38d49d6dd9cce520456d7aad8
haroldcarr/learn-haskell-coq-ml-etc
RLPItem.hs
module RLPItem (Item(String, List), encode, decode) where import PPrelude import Control.Error import Data.Attoparsec.ByteString as A import Data.Bits import qualified Data.ByteString as BS data Item = String ByteString | List [Item] deriving (Eq) instance Show Item where show (String str) = show str show (List list) = show list encode :: Item -> ByteString encode x = case x of String bytes -> if BS.length bytes == 1 && BS.head bytes <= 0x7f then bytes else encodeLength 0x80 bytes List children -> encodeLength 0xc0 (mconcat $ map encode children) where encodeLength :: Word8 -> ByteString -> ByteString encodeLength offset bytes | len <= 55 = prefix len <> bytes | otherwise = let lenBytes = encodeInt len lenLen = BS.length lenBytes + 55 in prefix lenLen <> lenBytes <> bytes where len = BS.length bytes prefix n = BS.singleton $ offset + fromIntegral n parseItem :: Parser (Int, Item) parseItem = do first <- anyWord8 let typeBits = 0xc0 .&. first parseString, parseList :: Int -> Parser Item parseString n = String <$> A.take n parseList 0 = return $ List [] parseList n = do (took, ret) <- parseItem List rest <- parseList (n - took) return . List $ ret : rest withSize offset parser | lenBits <= 55 = do res <- parser lenBits return (1 + lenBits, res) | otherwise = do let lenLen = lenBits - 55 bytes <- A.take lenLen len <- justZ $ decodeInt bytes ret <- parser len return (1 + lenLen + len, ret) where lenBits = fromIntegral $ first - offset case typeBits of 0x80 -> withSize 0x80 parseString 0xc0 -> withSize 0xc0 parseList _ -> return (1, String $ BS.singleton first) decode :: ByteString -> Maybe Item decode bs = hush $ parseOnly (snd <$> parser) bs where parser = do a <- parseItem A.endOfInput return a
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/playpen/blockchain/ben-kirwin-merkle/src/RLPItem.hs
haskell
module RLPItem (Item(String, List), encode, decode) where import PPrelude import Control.Error import Data.Attoparsec.ByteString as A import Data.Bits import qualified Data.ByteString as BS data Item = String ByteString | List [Item] deriving (Eq) instance Show Item where show (String str) = show str show (List list) = show list encode :: Item -> ByteString encode x = case x of String bytes -> if BS.length bytes == 1 && BS.head bytes <= 0x7f then bytes else encodeLength 0x80 bytes List children -> encodeLength 0xc0 (mconcat $ map encode children) where encodeLength :: Word8 -> ByteString -> ByteString encodeLength offset bytes | len <= 55 = prefix len <> bytes | otherwise = let lenBytes = encodeInt len lenLen = BS.length lenBytes + 55 in prefix lenLen <> lenBytes <> bytes where len = BS.length bytes prefix n = BS.singleton $ offset + fromIntegral n parseItem :: Parser (Int, Item) parseItem = do first <- anyWord8 let typeBits = 0xc0 .&. first parseString, parseList :: Int -> Parser Item parseString n = String <$> A.take n parseList 0 = return $ List [] parseList n = do (took, ret) <- parseItem List rest <- parseList (n - took) return . List $ ret : rest withSize offset parser | lenBits <= 55 = do res <- parser lenBits return (1 + lenBits, res) | otherwise = do let lenLen = lenBits - 55 bytes <- A.take lenLen len <- justZ $ decodeInt bytes ret <- parser len return (1 + lenLen + len, ret) where lenBits = fromIntegral $ first - offset case typeBits of 0x80 -> withSize 0x80 parseString 0xc0 -> withSize 0xc0 parseList _ -> return (1, String $ BS.singleton first) decode :: ByteString -> Maybe Item decode bs = hush $ parseOnly (snd <$> parser) bs where parser = do a <- parseItem A.endOfInput return a
5c4771d9c440f2aac0a6f3cb547e6428a3dbb7eb53f7f0660b1327e4f8bdfba8
zkincaid/duet
ai.ml
(** Abstract interpretation utilities, and an interface to APRON for numerical domains *) open Core open Srk open Apron type abstract_domain = Box | Octagon | Polyhedron magic is an uninhabited type that is used as a parameter to and Manager.t . We always coerce managers and abstract values to their magical counterparts so that the type stays the same even if the abstract domain changes . Manager.t. We always coerce managers and abstract values to their magical counterparts so that the type stays the same even if the abstract domain changes. *) type magic type abstract0 = magic Abstract0.t type manager = magic Manager.t (* Default abstract domain *) let domain = ref Box let is_relational_domain () = match !domain with | Box -> false | Octagon | Polyhedron -> true let man : (manager option) ref = ref None let get_man () = match !man with | Some m -> m | None -> let m = match !domain with | Box -> Box.manager_of_box (Box.manager_alloc ()) | Octagon -> Oct.manager_of_oct (Oct.manager_alloc ()) | Polyhedron -> Polka.manager_of_polka (Polka.manager_alloc_loose ()) in man := Some m; m let _ = let go s = man := None; domain := match s with | "box" -> Box | "oct" -> Octagon | "polka" -> Polyhedron | _ -> failwith ("The abstract domain `" ^ s ^ " ' is not recognized") in CmdLine.register_config ("-domain", Arg.String go, " Set abstract domain (box,oct,polka)") type absbool = Yes | No | Bottom | Top module type MinInterpretation = sig type t val join : t -> t -> t val equal : t -> t -> bool val pp : Format.formatter -> t -> unit val widen : t -> t -> t val bottom : t val name : string val transfer : def -> t -> t end module type Domain = sig type t val pp : Format.formatter -> t -> unit val project : t -> AP.Set.t -> t val inject : t -> AP.Set.t -> t val cyl : t -> AP.Set.t -> t val rename : t -> (ap * ap) list -> t val equal : t -> t -> bool val join : t -> t -> t val widen : t -> t -> t val meet : t -> t -> t val bottom : AP.Set.t -> t val top : AP.Set.t -> t val is_bottom : t -> bool end module type Interpretation = sig include Domain val transfer : def -> t -> t val assert_true : bexpr -> t -> bool val assert_memsafe : aexpr -> t -> bool val name : string end type 'a ptr_value = { ptr_val : 'a; ptr_pos : 'a; ptr_width : 'a } type 'a value = | VInt of 'a | VPointer of ('a ptr_value) | VDynamic module ApronInterpretation = struct open Dim module Env = struct include Putil.MonoMap.Make(AP)(struct type t = Dim.t value let pp formatter = function | VInt x -> Format.fprintf formatter "Int[%d]" x | VPointer p -> Format.fprintf formatter "Ptr[%d,%d,%d]" p.ptr_val p.ptr_pos p.ptr_width | VDynamic -> Format.pp_print_string formatter "Dyn" end) let delete k = let shift d = if d > k then d - 1 else d in let f = function | VInt d -> VInt (shift d) | VPointer p -> VPointer { ptr_val = shift p.ptr_val; ptr_pos = shift p.ptr_pos; ptr_width = shift p.ptr_width } | VDynamic -> VDynamic in map f end type t = { env : Env.t; value : abstract0 } (* Constants *) let infty = Scalar.of_infty 1 let neg_infty = Scalar.of_infty (-1) let havoc_int = Texpr0.Cst (Coeff.Interval Interval.top) let havoc_bool = Texpr0.Cst (Coeff.i_of_int 0 1) let havoc_positive_int = Texpr0.Cst (Coeff.i_of_scalar (Scalar.of_int 1) infty) let texpr_zero = Texpr0.Cst (Coeff.s_of_int 0) let texpr_one = Texpr0.Cst (Coeff.s_of_int 1) let is_bottom v = Abstract0.is_bottom (get_man()) v.value let is_top v = Abstract0.is_top (get_man()) v.value let get_domain av = let f k _ set = AP.Set.add k set in Env.fold f av.env AP.Set.empty let format_coeff formatter coeff = let format_scalar formatter s = Format.pp_print_string formatter (Scalar.to_string s) in match coeff with | Coeff.Scalar s -> format_scalar formatter s | Coeff.Interval ivl -> Format.fprintf formatter "[@[%a,%a@]]" format_scalar ivl.Interval.inf format_scalar ivl.Interval.sup module DimMap = Putil.PInt.Map let is_positive x = match Coeff.reduce x with | Coeff.Scalar x -> Scalar.cmp_int x 0 > 0 | Coeff.Interval _ -> true let pp formatter av = let lincons = Abstract0.to_lincons_array (get_man()) av.value in let add_to_env ap value env = match value with | VInt d -> DimMap.add d (AP.show ap) env | VPointer ptr -> DimMap.add ptr.ptr_val (AP.show ap) (DimMap.add ptr.ptr_pos ("pos@" ^ (AP.show ap)) (DimMap.add ptr.ptr_width ("width@" ^ (AP.show ap)) env)) | VDynamic -> env in let env = Env.fold add_to_env av.env DimMap.empty in let domain = Env.fold (fun ap _ -> AP.Set.add ap) av.env AP.Set.empty in let format_linexpr linexpr = Linexpr0.print (fun d -> DimMap.find d env) linexpr in let pp_elt formatter cons = format_linexpr formatter cons.Lincons0.linexpr0; Format.fprintf formatter " %s 0" (Lincons0.string_of_typ cons.Lincons0.typ) in AP.Set.pp formatter domain; Format.pp_print_string formatter ". "; if is_top av then Format.pp_print_string formatter "T" else if is_bottom av then Format.pp_print_string formatter "_|_" else SrkUtil.pp_print_enum ~pp_sep:(fun formatter () -> Format.fprintf formatter "@ && ") pp_elt formatter (BatArray.enum lincons) Create a new pointer value , where ptr_val , ptr_pos , and ptr_width are new dimension , starting with n new dimension, starting with n *) let ptr_at n = { ptr_val = n; ptr_pos = n + 1; ptr_width = n + 2 } let project av aps = let add_ap ap value (forget_dim, env) = if AP.Set.mem ap aps then (forget_dim, Env.add ap value env) else begin match value with | VInt dim -> (dim::forget_dim, env) | VPointer p -> (p.ptr_val::(p.ptr_pos::(p.ptr_width::forget_dim)), env) | VDynamic -> (forget_dim, env) end in let (forget_dim, env) = Env.fold add_ap av.env ([], Env.empty) in let forget_dim_array = Array.of_list forget_dim in let rename i = let rec go j = if j >= Array.length forget_dim_array then i else if forget_dim_array.(j) < i then go (j+1) - 1 else i in go 0 in let rename_env x value env = match value with | VInt dim -> Env.add x (VInt (rename dim)) env | VPointer p -> let p_rename = { ptr_val = rename p.ptr_val; ptr_pos = rename p.ptr_pos; ptr_width = rename p.ptr_width } in Env.add x (VPointer p_rename) env | VDynamic -> Env.add x VDynamic env in Array.sort Stdlib.compare forget_dim_array; let value = Abstract0.remove_dimensions (get_man()) av.value { dim = forget_dim_array; intdim = Array.length forget_dim_array; realdim = 0 } in { env = Env.fold rename_env env Env.empty; value = value } let get_dimension av = (Abstract0.dimension (get_man()) av.value).intd let add_dimensions num_av add = if add = 0 then num_av else let current_dim = (Abstract0.dimension (get_man()) num_av).intd in Abstract0.add_dimensions (get_man()) num_av { dim = Array.make add current_dim; intdim = add; realdim = 0 } false let inject av aps = let add_ap ap av = if Env.mem ap av.env then av else match resolve_type (AP.get_type ap) with | Core.Int _ -> { env = Env.add ap (VInt (get_dimension av)) av.env; value = add_dimensions av.value 1 } | Core.Pointer _ -> let vptr = ptr_at (get_dimension av) in { env = Env.add ap (VPointer vptr) av.env; value = add_dimensions av.value 3 } | _ -> { av with env = Env.add ap VDynamic av.env } in try AP.Set.fold add_ap aps av with Manager.Error exc -> failwith ("Inject error: " ^ exc.Manager.msg) (* Look up an access path in an abstract value *) let lookup x av = try Env.find x av.env with Not_found -> Format.printf "Missing dimension %a in %a" AP.pp x pp av; flush stdout; flush stderr; assert false let cyl av aps = let add_ap ap dimensions = match lookup ap av with | VInt dim -> dim::dimensions | VPointer p -> p.ptr_val::(p.ptr_pos::(p.ptr_width::dimensions)) | VDynamic -> dimensions in let forget_dimensions = Array.of_list (AP.Set.fold add_ap aps []) in let value = Abstract0.forget_array (get_man()) av.value forget_dimensions false in { av with value = value } let equal av0 av1 = Env.equal (=) av0.env av1.env && Abstract0.is_eq (get_man()) av0.value av1.value let rename av rename = let map = List.fold_right (fun (x,y) -> AP.Map.add x y) rename AP.Map.empty in let lookup x = try AP.Map.find x map with Not_found -> x in let add k vtyp map = Env.add (lookup k) vtyp map in { av with env = Env.fold add av.env Env.empty } let bottom aps = inject { env = Env.empty; value = Abstract0.bottom (get_man()) 0 0 } aps let top aps = inject { env = Env.empty; value = Abstract0.top (get_man()) 0 0 } aps (* Compute a common environment for the abstract values x and y, and then apply the function f to the numerical abstract values for x and y in the common environment *) let common_env f x y = let get_aps z = Env.fold (fun k _ s -> AP.Set.add k s) z.env AP.Set.empty in let aps = AP.Set.union (get_aps x) (get_aps y) in let x = inject x aps in let y = inject y aps in let x_dim = ref (get_dimension x) in let y_dim = ref (get_dimension y) in let alloc_dim z_dim num = let start = !z_dim in z_dim := start + num; start in let ptr_rename var p0 p1 (rename, env) = let rename = (p0.ptr_val,p1.ptr_val):: ((p0.ptr_pos,p1.ptr_pos):: ((p0.ptr_width,p1.ptr_width)::rename)) in (rename, Env.add var (VPointer p0) env) in let int_rename var d0 d1 (rename, env) = ((d0,d1)::rename, Env.add var (VInt d0) env) in let dyn_rename var (rename, env) = (rename, Env.add var VDynamic env) in let add var (rename, env) = match lookup var x, lookup var y with | (VInt d0, VInt d1) -> int_rename var d0 d1 (rename, env) | (VPointer p0, VPointer p1) -> ptr_rename var p0 p1 (rename, env) | (VDynamic, VDynamic) -> dyn_rename var (rename, env) | (VDynamic, VInt d1) -> int_rename var (alloc_dim x_dim 1) d1 (rename, env) | (VInt d0, VDynamic) -> int_rename var d0 (alloc_dim y_dim 1) (rename, env) | (VDynamic, VPointer p1) -> let p0 = ptr_at (alloc_dim x_dim 3) in ptr_rename var p0 p1 (rename, env) | (VPointer p0, VDynamic) -> ptr_rename var p0 (ptr_at (alloc_dim y_dim 3)) (rename, env) | (VPointer p0, VInt d1) -> let start = alloc_dim y_dim 2 in let p1 = { ptr_val = d1; ptr_pos = start; ptr_width = start + 1 } in ptr_rename var p0 p1 (rename, env) | (VInt d0, VPointer p1) -> let start = alloc_dim x_dim 2 in let p0 = { ptr_val = d0; ptr_pos = start; ptr_width = start + 1 } in ptr_rename var p0 p1 (rename, env) in let (rename, env) = AP.Set.fold add aps ([], Env.empty) in let perm = Array.of_list rename in Array.sort (fun x y -> Stdlib.compare (snd x) (snd y)) perm; let x_val = add_dimensions x.value (!x_dim - (get_dimension x)) in let y_val = add_dimensions y.value (!y_dim - (get_dimension y)) in let y_val = Abstract0.permute_dimensions (get_man()) y_val (Array.map fst perm) in { env = env; value = f x_val y_val } let join x y = try Log.time "join" (common_env (Abstract0.join (get_man())) x) y with Manager.Error exc -> failwith ("Join error: " ^ exc.Manager.msg) let meet x y = try Log.time "meet" (common_env (Abstract0.meet (get_man())) x) y with Manager.Error exc -> failwith ("Meet error: " ^ exc.Manager.msg) let widen x y = try Log.time "widen" (common_env (Abstract0.widening (get_man())) x) y with Manager.Error exc -> failwith ("Widen error: " ^ exc.Manager.msg) let assign_int lhs rhs av = let rhs = Texpr0.of_expr rhs in match lookup lhs av with | VInt dim -> { av with value = Abstract0.assign_texpr (get_man()) av.value dim rhs None } | VPointer ptr -> let dim = ptr.ptr_val in let value = Abstract0.assign_texpr (get_man()) av.value dim rhs None in let value = Abstract0.remove_dimensions (get_man()) value { dim = [| ptr.ptr_pos; ptr.ptr_width |]; intdim = 2; realdim = 0 } in let env = Env.delete ptr.ptr_width (Env.delete ptr.ptr_pos (Env.add lhs (VInt dim) av.env)) in { env = env; value = value } | VDynamic -> let dim = get_dimension av in let value = add_dimensions av.value 1 in let env = Env.add lhs (VInt dim) av.env in { env = env; value = Abstract0.assign_texpr (get_man()) value dim rhs None } let assign_ptr lhs rhs av = let (p, av) = match lookup lhs av with | VInt dim -> let pos_dim = get_dimension av in let value = add_dimensions av.value 2 in let p = { ptr_val = dim; ptr_pos = pos_dim; ptr_width = pos_dim + 1 } in let env = Env.add lhs (VPointer p) av.env in (p, {env = env; value = value }) | VPointer p -> (p, av) | VDynamic -> let p = ptr_at (get_dimension av) in let value = add_dimensions av.value 3 in let env = Env.add lhs (VPointer p) av.env in (p, {env = env; value = value }) in let value = Abstract0.assign_texpr_array (get_man()) av.value [| p.ptr_val; p.ptr_pos; p.ptr_width |] [| Texpr0.of_expr rhs.ptr_val; Texpr0.of_expr rhs.ptr_pos; Texpr0.of_expr rhs.ptr_width |] None in { av with value = value } let assign lhs rhs av = try begin match rhs with | VInt x -> assign_int lhs x av | VPointer p -> assign_ptr lhs p av | VDynamic -> cyl av (AP.Set.singleton lhs) end with Manager.Error exc -> failwith ("Assign error: " ^ exc.Manager.msg) let int_binop op left right = let normal_op op = Texpr0.Binop (op, left, right, Texpr0.Int, Texpr0.Down) in match op with | Add -> normal_op Texpr0.Add | Minus -> normal_op Texpr0.Sub | Mult -> normal_op Texpr0.Mul | Div -> normal_op Texpr0.Div | Mod -> normal_op Texpr0.Mod | ShiftL | ShiftR | BXor | BAnd | BOr -> havoc_int let vint_of_value = function | VInt x -> x | VPointer p -> p.ptr_val | VDynamic -> havoc_int let apron_binop op left right = match left, op, right with | (VInt left, op, VInt right) -> VInt (int_binop op left right) | (VPointer ptr, Add, VInt offset) | (VInt offset, Add, VPointer ptr) -> let p = { ptr_val = int_binop Add ptr.ptr_val offset; ptr_pos = int_binop Add ptr.ptr_pos offset; ptr_width = ptr.ptr_width } in VPointer p | (VPointer ptr, Minus, VInt offset) -> let p = { ptr_val = int_binop Minus ptr.ptr_val offset; ptr_pos = int_binop Minus ptr.ptr_pos offset; ptr_width = ptr.ptr_width } in VPointer p | (VInt offset, Minus, VPointer ptr) -> let p = { ptr_val = int_binop Minus offset ptr.ptr_val; ptr_pos = int_binop Minus offset ptr.ptr_pos; ptr_width = ptr.ptr_width } in VPointer p | (VPointer left, op, VInt right) -> VInt (int_binop op left.ptr_val right) | (VInt left, op, VPointer right) -> VInt (int_binop op left right.ptr_val) | (VPointer left, op, VPointer right) -> VInt (int_binop op left.ptr_val right.ptr_val) | (VInt left, op, VDynamic) -> VInt (int_binop op left havoc_int) | (VDynamic, op, VInt right) -> VInt (int_binop op havoc_int right) | (VPointer left, op, VDynamic) -> VInt (int_binop op left.ptr_val havoc_int) | (VDynamic, op, VPointer right) -> VInt (int_binop op havoc_int right.ptr_val) | (VDynamic, _, VDynamic) -> VDynamic let apron_expr av expr = let f = function | OHavoc typ -> begin match resolve_type typ with | Int _ -> VInt havoc_int | Pointer _ -> VPointer { ptr_val = havoc_int; ptr_pos = havoc_int; ptr_width = havoc_int } | Dynamic -> VDynamic | _ -> Log.fatalf "Havoc with a non-integer type: %a" pp_typ typ end | OConstant (CInt (c, _)) -> VInt (Texpr0.Cst (Coeff.s_of_int c)) | OConstant (CFloat (c, _)) -> VInt (Texpr0.Cst (Coeff.s_of_float c)) | OConstant (CChar c) -> VInt (Texpr0.Cst (Coeff.s_of_int (int_of_char c))) | OConstant (CString str) -> let width = Texpr0.Cst (Coeff.s_of_int (String.length str)) in VPointer { ptr_val = havoc_positive_int; ptr_pos = texpr_zero; ptr_width = width } | OAccessPath ap -> begin match lookup ap av with | VInt d -> VInt (Texpr0.Dim d) | VPointer p -> VPointer { ptr_val = Texpr0.Dim p.ptr_val; ptr_pos = Texpr0.Dim p.ptr_pos; ptr_width = Texpr0.Dim p.ptr_width } | VDynamic -> VDynamic end | OCast (_, x) -> x (* todo *) | OBinaryOp (left, op, right, _) -> apron_binop op left right | OUnaryOp (Neg, VInt expr, _) -> VInt (Texpr0.Unop (Texpr0.Neg, expr, Texpr0.Int, Texpr0.Down)) | OUnaryOp (Neg, VPointer expr, _) -> VInt (Texpr0.Unop (Texpr0.Neg, expr.ptr_val, Texpr0.Int, Texpr0.Down)) | OUnaryOp (BNot, _, _) -> VInt havoc_int | OBoolExpr _ -> VInt havoc_bool (* todo *) | OAddrOf (Variable (v, offset)) -> let pos = match offset with | OffsetFixed x -> Texpr0.Cst (Coeff.s_of_int x) | OffsetUnknown -> havoc_int | OffsetNone -> Texpr0.Cst (Coeff.s_of_int 0) in let width = typ_width (Varinfo.get_type v) in let p = { ptr_val = havoc_positive_int; ptr_pos = pos; ptr_width = Texpr0.Cst (Coeff.s_of_int width)} in VPointer p | OAddrOf _ -> (* todo *) let p = { ptr_val = havoc_int; ptr_pos = havoc_int; ptr_width = havoc_int } in VPointer p | _ -> VDynamic in Aexpr.fold f expr Translate an atom to APRON 's representation : an ( expression , constraint type ) pair type) pair *) let apron_atom pred a b = let sub = apron_binop Minus in let one = VInt (Texpr0.Cst (Coeff.s_of_int 1)) in let texpr x = Texpr0.of_expr (vint_of_value x) in match pred with | Eq -> (texpr (sub a b), Tcons0.EQ) | Ne -> (texpr (sub a b), Tcons0.DISEQ) | Le -> (texpr (sub b a), Tcons0.SUPEQ) | Lt -> (texpr (sub (sub b a) one), Tcons0.SUPEQ) let assert_memsafe expr av = match apron_expr av expr with | VDynamic | VInt _ -> false | VPointer p -> let sub a b = int_binop Minus a b in let one = Texpr0.Cst (Coeff.s_of_int 1) in let texpr = Texpr0.of_expr in let lt a b = Tcons0.make (texpr (sub (sub b a) one)) Tcons0.SUPEQ in let sat cons = Abstract0.sat_tcons (get_man()) av.value cons in sat (lt (Texpr0.Cst (Coeff.s_of_int 0)) p.ptr_val) && sat (lt p.ptr_pos p.ptr_width) && sat (Tcons0.make (texpr p.ptr_pos) Tcons0.SUPEQ) * Return true iff expr is definitely true in av . let rec assert_true bexpr av = match bexpr with | And (a, b) -> (assert_true a av) && (assert_true b av) | Or (a, b) -> (assert_true a av) || (assert_true b (interp_bool (Bexpr.negate a) av)) | Atom (Ne, a, b) -> (assert_true (Atom (Lt, a, b)) av) || (assert_true (Bexpr.gt a b) av) | Atom (pred, a, b) -> let (expr, typ) = apron_atom pred (apron_expr av a) (apron_expr av b) in Abstract0.sat_tcons (get_man()) av.value (Tcons0.make expr typ) Given an arbitrary Boolean constraint and an abstract value , compute the meet of the constraint and the value meet of the constraint and the value *) and interp_bool expr av = match expr with | And (a, b) -> interp_bool b (interp_bool a av) | Or (a, b) -> join (interp_bool a av) (interp_bool b av) Apron handles disequality inaccurately . This seems to be a reasonable replacement replacement *) | Atom (Ne, a, b) -> join (interp_bool (Atom (Lt, a, b)) av) (interp_bool (Atom (Lt, b, a)) av) | Atom (pred, a, b) -> if Bexpr.equal expr Bexpr.ktrue then av else begin let (expr, typ) = apron_atom pred (apron_expr av a) (apron_expr av b) in let value = Abstract0.meet_tcons_array (get_man()) av.value [| Tcons0.make expr typ |] in { av with value = value } end (** Widen, but preserve variable strict inequalities (i.e., if a < b in x and y, then a < b in (widen_preserve_leq x y). *) let widen_preserve_leq x y = let w = widen x y in let f a b value = let texpr = (* a - b - 1 *) Texpr0.of_expr (int_binop Minus (int_binop Minus (Texpr0.Dim a) (Texpr0.Dim b)) (Texpr0.Cst (Coeff.s_of_int 1))) in let tcons = Tcons0.make texpr Tcons0.SUPEQ in if (Abstract0.sat_tcons (get_man()) x.value tcons && Abstract0.sat_tcons (get_man()) y.value tcons && not (Abstract0.sat_tcons (get_man()) value tcons)) then Abstract0.meet_tcons_array (get_man()) value [| tcons |] else value in let value = let g _ d1 value = let h _ d2 value = match d1,d2 with | VInt a, VInt b -> f a b value | _,_ -> value in Env.fold h w.env value in Env.fold g w.env w.value in { w with value = value } let widen_thresholds thresholds x y = let w = widen_preserve_leq x y in let f a thresh value = let texpr = (* a - thresh *) Texpr0.of_expr (int_binop Minus (Texpr0.Cst (Coeff.s_of_int thresh)) (Texpr0.Dim a)) in let tcons = Tcons0.make texpr Tcons0.SUPEQ in if (Abstract0.sat_tcons (get_man()) x.value tcons && Abstract0.sat_tcons (get_man()) y.value tcons && not (Abstract0.sat_tcons (get_man()) value tcons)) then Abstract0.meet_tcons_array (get_man()) value [| tcons |] else value in let value = let g _ d value = match d with | VInt a -> List.fold_left (fun value thresh -> f a thresh value) value thresholds | _ -> value in Env.fold g w.env w.value in { w with value = value } let assert_true bexpr av = assert_true (Bexpr.dnf bexpr) av let interp_bool bexpr av = interp_bool bexpr av Assign pointer a freshly allocated chunk of memory of the given size within the given abstract value . If ! CmdLine.fail_malloc is set , then alloc then the value that alloc assigns to ptr includes null . within the given abstract value. If !CmdLine.fail_malloc is set, then alloc then the value that alloc assigns to ptr includes null. *) let alloc ptr size av = let lower = Scalar.of_int (if !CmdLine.fail_malloc then 0 else 1) in let rhs = { ptr_val = Texpr0.Cst (Coeff.i_of_scalar lower infty); ptr_pos = texpr_zero; ptr_width = vint_of_value size } in assign_ptr ptr rhs av (* Same as alloc, except alloc_safe never assigns null *) let alloc_safe ptr size av = let rhs = { ptr_val = havoc_positive_int; ptr_pos = texpr_zero; ptr_width = vint_of_value size } in assign_ptr ptr rhs av (* This is only safe for library calls - ie. no globals are modified *) let approx_call apset av = let f ap = assign_int ap havoc_int in AP.Set.fold f apset av (** Defines the abstract semantics of def as an abstract value transformer. *) let transfer def av = let av = inject av (AP.Set.union (Def.get_defs def) (Def.get_uses def)) in match def.dkind with | Assign (var, expr) -> assign (Variable var) (apron_expr av expr) av | Store (ap, expr) -> assign ap (apron_expr av expr) av | Assume expr -> interp_bool expr av (* Don't propagate erroneous values *) | Assert (expr, _) -> interp_bool expr av | AssertMemSafe (expr, _) -> begin match apron_expr av expr with | VDynamic | VInt _ -> av (* todo *) | VPointer p -> (* val > 0 && 0 <= pos < width *) let sub a b = int_binop Minus a b in let one = Texpr0.Cst (Coeff.s_of_int 1) in let texpr = Texpr0.of_expr in let lt a b = Tcons0.make (texpr (sub (sub b a) one)) Tcons0.SUPEQ in let constrain = [| lt (Texpr0.Cst (Coeff.s_of_int 0)) p.ptr_val; lt p.ptr_pos p.ptr_width; Tcons0.make (texpr p.ptr_pos) Tcons0.SUPEQ |] in let value = Abstract0.meet_tcons_array (get_man()) av.value constrain in { av with value = value } end | Initial -> let set_init ap _ av = match AP.get_ctype ap with | Array (_, Some (_, size)) -> alloc_safe ap (VInt (Texpr0.Cst (Coeff.s_of_int size))) av | _ -> av in Env.fold set_init av.env av | Call _ -> approx_call (Def.get_defs def) av | Return _ -> av | Builtin (Alloc (ptr, size, AllocHeap)) -> alloc (Variable ptr) (apron_expr av size) av | Builtin (Alloc (ptr, size, AllocStack)) -> alloc_safe (Variable ptr) (apron_expr av size) av | Builtin (Free _) -> av (* todo *) | Builtin (Fork _) -> av | Builtin (Acquire _) | Builtin (Release _) -> av | Builtin AtomicBegin | Builtin AtomicEnd -> av | Builtin Exit -> bottom (get_domain av) module REnv = Putil.PInt.Map let build_renv env = let f v value renv = match value with | VInt dim -> REnv.add dim (AccessPath v) renv | VPointer _ | VDynamic -> renv in let renv = Env.fold f env REnv.empty in fun x -> try Some (REnv.find x renv) with Not_found -> None let int_of_scalar = function | Scalar.Mpqf qq -> let (num,den) = Mpqf.to_mpzf2 qq in let (num,den) = (Mpz.get_int num, Mpz.get_int den) in assert (den == 1); Some num | _ -> None let apron_expr renv texpr = let open Texpr0 in let open Coeff in let rec go = function | Cst (Scalar s) -> begin match int_of_scalar s with | Some k -> Some (Aexpr.const_int k) | None -> None end | Cst (Interval _) -> None | Dim d -> renv d | Unop (op, expr, _, _) -> begin match go expr with | None -> None | Some expr -> begin match op with | Neg -> Some (Aexpr.neg expr) | Cast -> None | Sqrt -> None end end | Binop (op, left, right, _, _) -> begin match go left, go right with | (None, _) | (_, None) -> None | (Some left, Some right) -> Some begin match op with | Add -> Aexpr.add left right | Sub -> Aexpr.sub left right | Mul -> Aexpr.mul left right | Div -> Aexpr.div left right | Mod -> Aexpr.modulo left right | Pow -> assert false end end in go (to_expr texpr) let tcons_bexpr renv tcons = let open Tcons0 in let zero = Aexpr.zero in match apron_expr renv tcons.texpr0 with | None -> None | Some expr -> match tcons.typ with | EQ -> Some (Atom (Eq, expr, zero)) | SUPEQ -> Some (Bexpr.ge expr zero) | SUP -> Some (Bexpr.gt expr zero) | DISEQ -> Some (Atom (Ne, expr, zero)) | EQMOD s -> begin match int_of_scalar s with | Some k -> Some (Atom (Eq, Aexpr.modulo expr (Aexpr.const_int k), zero)) | None -> None end let bexpr_of_av av = let renv = build_renv av.env in let tcons = BatArray.enum (Abstract0.to_tcons_array (get_man()) av.value) in let conjuncts = BatEnum.filter_map (tcons_bexpr renv) tcons in BatEnum.fold (fun x y -> And (x, y)) Bexpr.ktrue conjuncts let name = "APRON" end (** Derived operations on interpretations *) module IExtra (I : Interpretation) = struct include I (** Evaluate a predicate in an abstract environment. *) let eval_pred pred value = if I.is_bottom value then Bottom else if I.assert_true pred value then Yes else if I.assert_true (Bexpr.negate pred) value then No else Top end
null
https://raw.githubusercontent.com/zkincaid/duet/eb3dbfe6c51d5e1a11cb39ab8f70584aaaa309f9/duet/ai.ml
ocaml
* Abstract interpretation utilities, and an interface to APRON for numerical domains Default abstract domain Constants Look up an access path in an abstract value Compute a common environment for the abstract values x and y, and then apply the function f to the numerical abstract values for x and y in the common environment todo todo todo * Widen, but preserve variable strict inequalities (i.e., if a < b in x and y, then a < b in (widen_preserve_leq x y). a - b - 1 a - thresh Same as alloc, except alloc_safe never assigns null This is only safe for library calls - ie. no globals are modified * Defines the abstract semantics of def as an abstract value transformer. Don't propagate erroneous values todo val > 0 && 0 <= pos < width todo * Derived operations on interpretations * Evaluate a predicate in an abstract environment.
open Core open Srk open Apron type abstract_domain = Box | Octagon | Polyhedron magic is an uninhabited type that is used as a parameter to and Manager.t . We always coerce managers and abstract values to their magical counterparts so that the type stays the same even if the abstract domain changes . Manager.t. We always coerce managers and abstract values to their magical counterparts so that the type stays the same even if the abstract domain changes. *) type magic type abstract0 = magic Abstract0.t type manager = magic Manager.t let domain = ref Box let is_relational_domain () = match !domain with | Box -> false | Octagon | Polyhedron -> true let man : (manager option) ref = ref None let get_man () = match !man with | Some m -> m | None -> let m = match !domain with | Box -> Box.manager_of_box (Box.manager_alloc ()) | Octagon -> Oct.manager_of_oct (Oct.manager_alloc ()) | Polyhedron -> Polka.manager_of_polka (Polka.manager_alloc_loose ()) in man := Some m; m let _ = let go s = man := None; domain := match s with | "box" -> Box | "oct" -> Octagon | "polka" -> Polyhedron | _ -> failwith ("The abstract domain `" ^ s ^ " ' is not recognized") in CmdLine.register_config ("-domain", Arg.String go, " Set abstract domain (box,oct,polka)") type absbool = Yes | No | Bottom | Top module type MinInterpretation = sig type t val join : t -> t -> t val equal : t -> t -> bool val pp : Format.formatter -> t -> unit val widen : t -> t -> t val bottom : t val name : string val transfer : def -> t -> t end module type Domain = sig type t val pp : Format.formatter -> t -> unit val project : t -> AP.Set.t -> t val inject : t -> AP.Set.t -> t val cyl : t -> AP.Set.t -> t val rename : t -> (ap * ap) list -> t val equal : t -> t -> bool val join : t -> t -> t val widen : t -> t -> t val meet : t -> t -> t val bottom : AP.Set.t -> t val top : AP.Set.t -> t val is_bottom : t -> bool end module type Interpretation = sig include Domain val transfer : def -> t -> t val assert_true : bexpr -> t -> bool val assert_memsafe : aexpr -> t -> bool val name : string end type 'a ptr_value = { ptr_val : 'a; ptr_pos : 'a; ptr_width : 'a } type 'a value = | VInt of 'a | VPointer of ('a ptr_value) | VDynamic module ApronInterpretation = struct open Dim module Env = struct include Putil.MonoMap.Make(AP)(struct type t = Dim.t value let pp formatter = function | VInt x -> Format.fprintf formatter "Int[%d]" x | VPointer p -> Format.fprintf formatter "Ptr[%d,%d,%d]" p.ptr_val p.ptr_pos p.ptr_width | VDynamic -> Format.pp_print_string formatter "Dyn" end) let delete k = let shift d = if d > k then d - 1 else d in let f = function | VInt d -> VInt (shift d) | VPointer p -> VPointer { ptr_val = shift p.ptr_val; ptr_pos = shift p.ptr_pos; ptr_width = shift p.ptr_width } | VDynamic -> VDynamic in map f end type t = { env : Env.t; value : abstract0 } let infty = Scalar.of_infty 1 let neg_infty = Scalar.of_infty (-1) let havoc_int = Texpr0.Cst (Coeff.Interval Interval.top) let havoc_bool = Texpr0.Cst (Coeff.i_of_int 0 1) let havoc_positive_int = Texpr0.Cst (Coeff.i_of_scalar (Scalar.of_int 1) infty) let texpr_zero = Texpr0.Cst (Coeff.s_of_int 0) let texpr_one = Texpr0.Cst (Coeff.s_of_int 1) let is_bottom v = Abstract0.is_bottom (get_man()) v.value let is_top v = Abstract0.is_top (get_man()) v.value let get_domain av = let f k _ set = AP.Set.add k set in Env.fold f av.env AP.Set.empty let format_coeff formatter coeff = let format_scalar formatter s = Format.pp_print_string formatter (Scalar.to_string s) in match coeff with | Coeff.Scalar s -> format_scalar formatter s | Coeff.Interval ivl -> Format.fprintf formatter "[@[%a,%a@]]" format_scalar ivl.Interval.inf format_scalar ivl.Interval.sup module DimMap = Putil.PInt.Map let is_positive x = match Coeff.reduce x with | Coeff.Scalar x -> Scalar.cmp_int x 0 > 0 | Coeff.Interval _ -> true let pp formatter av = let lincons = Abstract0.to_lincons_array (get_man()) av.value in let add_to_env ap value env = match value with | VInt d -> DimMap.add d (AP.show ap) env | VPointer ptr -> DimMap.add ptr.ptr_val (AP.show ap) (DimMap.add ptr.ptr_pos ("pos@" ^ (AP.show ap)) (DimMap.add ptr.ptr_width ("width@" ^ (AP.show ap)) env)) | VDynamic -> env in let env = Env.fold add_to_env av.env DimMap.empty in let domain = Env.fold (fun ap _ -> AP.Set.add ap) av.env AP.Set.empty in let format_linexpr linexpr = Linexpr0.print (fun d -> DimMap.find d env) linexpr in let pp_elt formatter cons = format_linexpr formatter cons.Lincons0.linexpr0; Format.fprintf formatter " %s 0" (Lincons0.string_of_typ cons.Lincons0.typ) in AP.Set.pp formatter domain; Format.pp_print_string formatter ". "; if is_top av then Format.pp_print_string formatter "T" else if is_bottom av then Format.pp_print_string formatter "_|_" else SrkUtil.pp_print_enum ~pp_sep:(fun formatter () -> Format.fprintf formatter "@ && ") pp_elt formatter (BatArray.enum lincons) Create a new pointer value , where ptr_val , ptr_pos , and ptr_width are new dimension , starting with n new dimension, starting with n *) let ptr_at n = { ptr_val = n; ptr_pos = n + 1; ptr_width = n + 2 } let project av aps = let add_ap ap value (forget_dim, env) = if AP.Set.mem ap aps then (forget_dim, Env.add ap value env) else begin match value with | VInt dim -> (dim::forget_dim, env) | VPointer p -> (p.ptr_val::(p.ptr_pos::(p.ptr_width::forget_dim)), env) | VDynamic -> (forget_dim, env) end in let (forget_dim, env) = Env.fold add_ap av.env ([], Env.empty) in let forget_dim_array = Array.of_list forget_dim in let rename i = let rec go j = if j >= Array.length forget_dim_array then i else if forget_dim_array.(j) < i then go (j+1) - 1 else i in go 0 in let rename_env x value env = match value with | VInt dim -> Env.add x (VInt (rename dim)) env | VPointer p -> let p_rename = { ptr_val = rename p.ptr_val; ptr_pos = rename p.ptr_pos; ptr_width = rename p.ptr_width } in Env.add x (VPointer p_rename) env | VDynamic -> Env.add x VDynamic env in Array.sort Stdlib.compare forget_dim_array; let value = Abstract0.remove_dimensions (get_man()) av.value { dim = forget_dim_array; intdim = Array.length forget_dim_array; realdim = 0 } in { env = Env.fold rename_env env Env.empty; value = value } let get_dimension av = (Abstract0.dimension (get_man()) av.value).intd let add_dimensions num_av add = if add = 0 then num_av else let current_dim = (Abstract0.dimension (get_man()) num_av).intd in Abstract0.add_dimensions (get_man()) num_av { dim = Array.make add current_dim; intdim = add; realdim = 0 } false let inject av aps = let add_ap ap av = if Env.mem ap av.env then av else match resolve_type (AP.get_type ap) with | Core.Int _ -> { env = Env.add ap (VInt (get_dimension av)) av.env; value = add_dimensions av.value 1 } | Core.Pointer _ -> let vptr = ptr_at (get_dimension av) in { env = Env.add ap (VPointer vptr) av.env; value = add_dimensions av.value 3 } | _ -> { av with env = Env.add ap VDynamic av.env } in try AP.Set.fold add_ap aps av with Manager.Error exc -> failwith ("Inject error: " ^ exc.Manager.msg) let lookup x av = try Env.find x av.env with Not_found -> Format.printf "Missing dimension %a in %a" AP.pp x pp av; flush stdout; flush stderr; assert false let cyl av aps = let add_ap ap dimensions = match lookup ap av with | VInt dim -> dim::dimensions | VPointer p -> p.ptr_val::(p.ptr_pos::(p.ptr_width::dimensions)) | VDynamic -> dimensions in let forget_dimensions = Array.of_list (AP.Set.fold add_ap aps []) in let value = Abstract0.forget_array (get_man()) av.value forget_dimensions false in { av with value = value } let equal av0 av1 = Env.equal (=) av0.env av1.env && Abstract0.is_eq (get_man()) av0.value av1.value let rename av rename = let map = List.fold_right (fun (x,y) -> AP.Map.add x y) rename AP.Map.empty in let lookup x = try AP.Map.find x map with Not_found -> x in let add k vtyp map = Env.add (lookup k) vtyp map in { av with env = Env.fold add av.env Env.empty } let bottom aps = inject { env = Env.empty; value = Abstract0.bottom (get_man()) 0 0 } aps let top aps = inject { env = Env.empty; value = Abstract0.top (get_man()) 0 0 } aps let common_env f x y = let get_aps z = Env.fold (fun k _ s -> AP.Set.add k s) z.env AP.Set.empty in let aps = AP.Set.union (get_aps x) (get_aps y) in let x = inject x aps in let y = inject y aps in let x_dim = ref (get_dimension x) in let y_dim = ref (get_dimension y) in let alloc_dim z_dim num = let start = !z_dim in z_dim := start + num; start in let ptr_rename var p0 p1 (rename, env) = let rename = (p0.ptr_val,p1.ptr_val):: ((p0.ptr_pos,p1.ptr_pos):: ((p0.ptr_width,p1.ptr_width)::rename)) in (rename, Env.add var (VPointer p0) env) in let int_rename var d0 d1 (rename, env) = ((d0,d1)::rename, Env.add var (VInt d0) env) in let dyn_rename var (rename, env) = (rename, Env.add var VDynamic env) in let add var (rename, env) = match lookup var x, lookup var y with | (VInt d0, VInt d1) -> int_rename var d0 d1 (rename, env) | (VPointer p0, VPointer p1) -> ptr_rename var p0 p1 (rename, env) | (VDynamic, VDynamic) -> dyn_rename var (rename, env) | (VDynamic, VInt d1) -> int_rename var (alloc_dim x_dim 1) d1 (rename, env) | (VInt d0, VDynamic) -> int_rename var d0 (alloc_dim y_dim 1) (rename, env) | (VDynamic, VPointer p1) -> let p0 = ptr_at (alloc_dim x_dim 3) in ptr_rename var p0 p1 (rename, env) | (VPointer p0, VDynamic) -> ptr_rename var p0 (ptr_at (alloc_dim y_dim 3)) (rename, env) | (VPointer p0, VInt d1) -> let start = alloc_dim y_dim 2 in let p1 = { ptr_val = d1; ptr_pos = start; ptr_width = start + 1 } in ptr_rename var p0 p1 (rename, env) | (VInt d0, VPointer p1) -> let start = alloc_dim x_dim 2 in let p0 = { ptr_val = d0; ptr_pos = start; ptr_width = start + 1 } in ptr_rename var p0 p1 (rename, env) in let (rename, env) = AP.Set.fold add aps ([], Env.empty) in let perm = Array.of_list rename in Array.sort (fun x y -> Stdlib.compare (snd x) (snd y)) perm; let x_val = add_dimensions x.value (!x_dim - (get_dimension x)) in let y_val = add_dimensions y.value (!y_dim - (get_dimension y)) in let y_val = Abstract0.permute_dimensions (get_man()) y_val (Array.map fst perm) in { env = env; value = f x_val y_val } let join x y = try Log.time "join" (common_env (Abstract0.join (get_man())) x) y with Manager.Error exc -> failwith ("Join error: " ^ exc.Manager.msg) let meet x y = try Log.time "meet" (common_env (Abstract0.meet (get_man())) x) y with Manager.Error exc -> failwith ("Meet error: " ^ exc.Manager.msg) let widen x y = try Log.time "widen" (common_env (Abstract0.widening (get_man())) x) y with Manager.Error exc -> failwith ("Widen error: " ^ exc.Manager.msg) let assign_int lhs rhs av = let rhs = Texpr0.of_expr rhs in match lookup lhs av with | VInt dim -> { av with value = Abstract0.assign_texpr (get_man()) av.value dim rhs None } | VPointer ptr -> let dim = ptr.ptr_val in let value = Abstract0.assign_texpr (get_man()) av.value dim rhs None in let value = Abstract0.remove_dimensions (get_man()) value { dim = [| ptr.ptr_pos; ptr.ptr_width |]; intdim = 2; realdim = 0 } in let env = Env.delete ptr.ptr_width (Env.delete ptr.ptr_pos (Env.add lhs (VInt dim) av.env)) in { env = env; value = value } | VDynamic -> let dim = get_dimension av in let value = add_dimensions av.value 1 in let env = Env.add lhs (VInt dim) av.env in { env = env; value = Abstract0.assign_texpr (get_man()) value dim rhs None } let assign_ptr lhs rhs av = let (p, av) = match lookup lhs av with | VInt dim -> let pos_dim = get_dimension av in let value = add_dimensions av.value 2 in let p = { ptr_val = dim; ptr_pos = pos_dim; ptr_width = pos_dim + 1 } in let env = Env.add lhs (VPointer p) av.env in (p, {env = env; value = value }) | VPointer p -> (p, av) | VDynamic -> let p = ptr_at (get_dimension av) in let value = add_dimensions av.value 3 in let env = Env.add lhs (VPointer p) av.env in (p, {env = env; value = value }) in let value = Abstract0.assign_texpr_array (get_man()) av.value [| p.ptr_val; p.ptr_pos; p.ptr_width |] [| Texpr0.of_expr rhs.ptr_val; Texpr0.of_expr rhs.ptr_pos; Texpr0.of_expr rhs.ptr_width |] None in { av with value = value } let assign lhs rhs av = try begin match rhs with | VInt x -> assign_int lhs x av | VPointer p -> assign_ptr lhs p av | VDynamic -> cyl av (AP.Set.singleton lhs) end with Manager.Error exc -> failwith ("Assign error: " ^ exc.Manager.msg) let int_binop op left right = let normal_op op = Texpr0.Binop (op, left, right, Texpr0.Int, Texpr0.Down) in match op with | Add -> normal_op Texpr0.Add | Minus -> normal_op Texpr0.Sub | Mult -> normal_op Texpr0.Mul | Div -> normal_op Texpr0.Div | Mod -> normal_op Texpr0.Mod | ShiftL | ShiftR | BXor | BAnd | BOr -> havoc_int let vint_of_value = function | VInt x -> x | VPointer p -> p.ptr_val | VDynamic -> havoc_int let apron_binop op left right = match left, op, right with | (VInt left, op, VInt right) -> VInt (int_binop op left right) | (VPointer ptr, Add, VInt offset) | (VInt offset, Add, VPointer ptr) -> let p = { ptr_val = int_binop Add ptr.ptr_val offset; ptr_pos = int_binop Add ptr.ptr_pos offset; ptr_width = ptr.ptr_width } in VPointer p | (VPointer ptr, Minus, VInt offset) -> let p = { ptr_val = int_binop Minus ptr.ptr_val offset; ptr_pos = int_binop Minus ptr.ptr_pos offset; ptr_width = ptr.ptr_width } in VPointer p | (VInt offset, Minus, VPointer ptr) -> let p = { ptr_val = int_binop Minus offset ptr.ptr_val; ptr_pos = int_binop Minus offset ptr.ptr_pos; ptr_width = ptr.ptr_width } in VPointer p | (VPointer left, op, VInt right) -> VInt (int_binop op left.ptr_val right) | (VInt left, op, VPointer right) -> VInt (int_binop op left right.ptr_val) | (VPointer left, op, VPointer right) -> VInt (int_binop op left.ptr_val right.ptr_val) | (VInt left, op, VDynamic) -> VInt (int_binop op left havoc_int) | (VDynamic, op, VInt right) -> VInt (int_binop op havoc_int right) | (VPointer left, op, VDynamic) -> VInt (int_binop op left.ptr_val havoc_int) | (VDynamic, op, VPointer right) -> VInt (int_binop op havoc_int right.ptr_val) | (VDynamic, _, VDynamic) -> VDynamic let apron_expr av expr = let f = function | OHavoc typ -> begin match resolve_type typ with | Int _ -> VInt havoc_int | Pointer _ -> VPointer { ptr_val = havoc_int; ptr_pos = havoc_int; ptr_width = havoc_int } | Dynamic -> VDynamic | _ -> Log.fatalf "Havoc with a non-integer type: %a" pp_typ typ end | OConstant (CInt (c, _)) -> VInt (Texpr0.Cst (Coeff.s_of_int c)) | OConstant (CFloat (c, _)) -> VInt (Texpr0.Cst (Coeff.s_of_float c)) | OConstant (CChar c) -> VInt (Texpr0.Cst (Coeff.s_of_int (int_of_char c))) | OConstant (CString str) -> let width = Texpr0.Cst (Coeff.s_of_int (String.length str)) in VPointer { ptr_val = havoc_positive_int; ptr_pos = texpr_zero; ptr_width = width } | OAccessPath ap -> begin match lookup ap av with | VInt d -> VInt (Texpr0.Dim d) | VPointer p -> VPointer { ptr_val = Texpr0.Dim p.ptr_val; ptr_pos = Texpr0.Dim p.ptr_pos; ptr_width = Texpr0.Dim p.ptr_width } | VDynamic -> VDynamic end | OBinaryOp (left, op, right, _) -> apron_binop op left right | OUnaryOp (Neg, VInt expr, _) -> VInt (Texpr0.Unop (Texpr0.Neg, expr, Texpr0.Int, Texpr0.Down)) | OUnaryOp (Neg, VPointer expr, _) -> VInt (Texpr0.Unop (Texpr0.Neg, expr.ptr_val, Texpr0.Int, Texpr0.Down)) | OUnaryOp (BNot, _, _) -> VInt havoc_int | OAddrOf (Variable (v, offset)) -> let pos = match offset with | OffsetFixed x -> Texpr0.Cst (Coeff.s_of_int x) | OffsetUnknown -> havoc_int | OffsetNone -> Texpr0.Cst (Coeff.s_of_int 0) in let width = typ_width (Varinfo.get_type v) in let p = { ptr_val = havoc_positive_int; ptr_pos = pos; ptr_width = Texpr0.Cst (Coeff.s_of_int width)} in VPointer p let p = { ptr_val = havoc_int; ptr_pos = havoc_int; ptr_width = havoc_int } in VPointer p | _ -> VDynamic in Aexpr.fold f expr Translate an atom to APRON 's representation : an ( expression , constraint type ) pair type) pair *) let apron_atom pred a b = let sub = apron_binop Minus in let one = VInt (Texpr0.Cst (Coeff.s_of_int 1)) in let texpr x = Texpr0.of_expr (vint_of_value x) in match pred with | Eq -> (texpr (sub a b), Tcons0.EQ) | Ne -> (texpr (sub a b), Tcons0.DISEQ) | Le -> (texpr (sub b a), Tcons0.SUPEQ) | Lt -> (texpr (sub (sub b a) one), Tcons0.SUPEQ) let assert_memsafe expr av = match apron_expr av expr with | VDynamic | VInt _ -> false | VPointer p -> let sub a b = int_binop Minus a b in let one = Texpr0.Cst (Coeff.s_of_int 1) in let texpr = Texpr0.of_expr in let lt a b = Tcons0.make (texpr (sub (sub b a) one)) Tcons0.SUPEQ in let sat cons = Abstract0.sat_tcons (get_man()) av.value cons in sat (lt (Texpr0.Cst (Coeff.s_of_int 0)) p.ptr_val) && sat (lt p.ptr_pos p.ptr_width) && sat (Tcons0.make (texpr p.ptr_pos) Tcons0.SUPEQ) * Return true iff expr is definitely true in av . let rec assert_true bexpr av = match bexpr with | And (a, b) -> (assert_true a av) && (assert_true b av) | Or (a, b) -> (assert_true a av) || (assert_true b (interp_bool (Bexpr.negate a) av)) | Atom (Ne, a, b) -> (assert_true (Atom (Lt, a, b)) av) || (assert_true (Bexpr.gt a b) av) | Atom (pred, a, b) -> let (expr, typ) = apron_atom pred (apron_expr av a) (apron_expr av b) in Abstract0.sat_tcons (get_man()) av.value (Tcons0.make expr typ) Given an arbitrary Boolean constraint and an abstract value , compute the meet of the constraint and the value meet of the constraint and the value *) and interp_bool expr av = match expr with | And (a, b) -> interp_bool b (interp_bool a av) | Or (a, b) -> join (interp_bool a av) (interp_bool b av) Apron handles disequality inaccurately . This seems to be a reasonable replacement replacement *) | Atom (Ne, a, b) -> join (interp_bool (Atom (Lt, a, b)) av) (interp_bool (Atom (Lt, b, a)) av) | Atom (pred, a, b) -> if Bexpr.equal expr Bexpr.ktrue then av else begin let (expr, typ) = apron_atom pred (apron_expr av a) (apron_expr av b) in let value = Abstract0.meet_tcons_array (get_man()) av.value [| Tcons0.make expr typ |] in { av with value = value } end let widen_preserve_leq x y = let w = widen x y in let f a b value = Texpr0.of_expr (int_binop Minus (int_binop Minus (Texpr0.Dim a) (Texpr0.Dim b)) (Texpr0.Cst (Coeff.s_of_int 1))) in let tcons = Tcons0.make texpr Tcons0.SUPEQ in if (Abstract0.sat_tcons (get_man()) x.value tcons && Abstract0.sat_tcons (get_man()) y.value tcons && not (Abstract0.sat_tcons (get_man()) value tcons)) then Abstract0.meet_tcons_array (get_man()) value [| tcons |] else value in let value = let g _ d1 value = let h _ d2 value = match d1,d2 with | VInt a, VInt b -> f a b value | _,_ -> value in Env.fold h w.env value in Env.fold g w.env w.value in { w with value = value } let widen_thresholds thresholds x y = let w = widen_preserve_leq x y in let f a thresh value = Texpr0.of_expr (int_binop Minus (Texpr0.Cst (Coeff.s_of_int thresh)) (Texpr0.Dim a)) in let tcons = Tcons0.make texpr Tcons0.SUPEQ in if (Abstract0.sat_tcons (get_man()) x.value tcons && Abstract0.sat_tcons (get_man()) y.value tcons && not (Abstract0.sat_tcons (get_man()) value tcons)) then Abstract0.meet_tcons_array (get_man()) value [| tcons |] else value in let value = let g _ d value = match d with | VInt a -> List.fold_left (fun value thresh -> f a thresh value) value thresholds | _ -> value in Env.fold g w.env w.value in { w with value = value } let assert_true bexpr av = assert_true (Bexpr.dnf bexpr) av let interp_bool bexpr av = interp_bool bexpr av Assign pointer a freshly allocated chunk of memory of the given size within the given abstract value . If ! CmdLine.fail_malloc is set , then alloc then the value that alloc assigns to ptr includes null . within the given abstract value. If !CmdLine.fail_malloc is set, then alloc then the value that alloc assigns to ptr includes null. *) let alloc ptr size av = let lower = Scalar.of_int (if !CmdLine.fail_malloc then 0 else 1) in let rhs = { ptr_val = Texpr0.Cst (Coeff.i_of_scalar lower infty); ptr_pos = texpr_zero; ptr_width = vint_of_value size } in assign_ptr ptr rhs av let alloc_safe ptr size av = let rhs = { ptr_val = havoc_positive_int; ptr_pos = texpr_zero; ptr_width = vint_of_value size } in assign_ptr ptr rhs av let approx_call apset av = let f ap = assign_int ap havoc_int in AP.Set.fold f apset av let transfer def av = let av = inject av (AP.Set.union (Def.get_defs def) (Def.get_uses def)) in match def.dkind with | Assign (var, expr) -> assign (Variable var) (apron_expr av expr) av | Store (ap, expr) -> assign ap (apron_expr av expr) av | Assume expr -> interp_bool expr av | Assert (expr, _) -> interp_bool expr av | AssertMemSafe (expr, _) -> begin match apron_expr av expr with | VPointer p -> let sub a b = int_binop Minus a b in let one = Texpr0.Cst (Coeff.s_of_int 1) in let texpr = Texpr0.of_expr in let lt a b = Tcons0.make (texpr (sub (sub b a) one)) Tcons0.SUPEQ in let constrain = [| lt (Texpr0.Cst (Coeff.s_of_int 0)) p.ptr_val; lt p.ptr_pos p.ptr_width; Tcons0.make (texpr p.ptr_pos) Tcons0.SUPEQ |] in let value = Abstract0.meet_tcons_array (get_man()) av.value constrain in { av with value = value } end | Initial -> let set_init ap _ av = match AP.get_ctype ap with | Array (_, Some (_, size)) -> alloc_safe ap (VInt (Texpr0.Cst (Coeff.s_of_int size))) av | _ -> av in Env.fold set_init av.env av | Call _ -> approx_call (Def.get_defs def) av | Return _ -> av | Builtin (Alloc (ptr, size, AllocHeap)) -> alloc (Variable ptr) (apron_expr av size) av | Builtin (Alloc (ptr, size, AllocStack)) -> alloc_safe (Variable ptr) (apron_expr av size) av | Builtin (Fork _) -> av | Builtin (Acquire _) | Builtin (Release _) -> av | Builtin AtomicBegin | Builtin AtomicEnd -> av | Builtin Exit -> bottom (get_domain av) module REnv = Putil.PInt.Map let build_renv env = let f v value renv = match value with | VInt dim -> REnv.add dim (AccessPath v) renv | VPointer _ | VDynamic -> renv in let renv = Env.fold f env REnv.empty in fun x -> try Some (REnv.find x renv) with Not_found -> None let int_of_scalar = function | Scalar.Mpqf qq -> let (num,den) = Mpqf.to_mpzf2 qq in let (num,den) = (Mpz.get_int num, Mpz.get_int den) in assert (den == 1); Some num | _ -> None let apron_expr renv texpr = let open Texpr0 in let open Coeff in let rec go = function | Cst (Scalar s) -> begin match int_of_scalar s with | Some k -> Some (Aexpr.const_int k) | None -> None end | Cst (Interval _) -> None | Dim d -> renv d | Unop (op, expr, _, _) -> begin match go expr with | None -> None | Some expr -> begin match op with | Neg -> Some (Aexpr.neg expr) | Cast -> None | Sqrt -> None end end | Binop (op, left, right, _, _) -> begin match go left, go right with | (None, _) | (_, None) -> None | (Some left, Some right) -> Some begin match op with | Add -> Aexpr.add left right | Sub -> Aexpr.sub left right | Mul -> Aexpr.mul left right | Div -> Aexpr.div left right | Mod -> Aexpr.modulo left right | Pow -> assert false end end in go (to_expr texpr) let tcons_bexpr renv tcons = let open Tcons0 in let zero = Aexpr.zero in match apron_expr renv tcons.texpr0 with | None -> None | Some expr -> match tcons.typ with | EQ -> Some (Atom (Eq, expr, zero)) | SUPEQ -> Some (Bexpr.ge expr zero) | SUP -> Some (Bexpr.gt expr zero) | DISEQ -> Some (Atom (Ne, expr, zero)) | EQMOD s -> begin match int_of_scalar s with | Some k -> Some (Atom (Eq, Aexpr.modulo expr (Aexpr.const_int k), zero)) | None -> None end let bexpr_of_av av = let renv = build_renv av.env in let tcons = BatArray.enum (Abstract0.to_tcons_array (get_man()) av.value) in let conjuncts = BatEnum.filter_map (tcons_bexpr renv) tcons in BatEnum.fold (fun x y -> And (x, y)) Bexpr.ktrue conjuncts let name = "APRON" end module IExtra (I : Interpretation) = struct include I let eval_pred pred value = if I.is_bottom value then Bottom else if I.assert_true pred value then Yes else if I.assert_true (Bexpr.negate pred) value then No else Top end
f512e9650b86be4e67afd1371cfb615ddea6f9eaaf0253b3ffc82eaeb8d4c8c0
haskus/haskus-system
Main.hs
# LANGUAGE TemplateHaskell # {-# LANGUAGE BangPatterns #-} # LANGUAGE NoMonomorphismRestriction # # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE DataKinds # # LANGUAGE BlockArguments # import Haskus.System import Haskus.System.Linux.FileSystem.Directory import Haskus.System.Linux.FileSystem import qualified Haskus.Binary.Buffer as B import Haskus.Binary.Endianness import qualified Haskus.Binary.BitSet as BitSet import Haskus.System.Linux.Graphics.State import Haskus.System.Linux.Graphics.Mode import Haskus.System.Linux.Graphics.PixelFormat import Haskus.System.Linux.Graphics.Helper import Haskus.System.Linux.Graphics.KIO import Haskus.System.Linux.ErrorCode import Haskus.System.Graphics.Drawing import qualified Haskus.System.Graphics.Diagrams as D import Haskus.System.Graphics.Diagrams ((#),fc,lw,rasterizeDiagram,mkWidth,none) import Haskus.Utils.Embed.ByteString import Haskus.Utils.STM import qualified Haskus.Utils.Map as Map import Data.Colour.Names (blue) import Data.List (intersperse) import Data.ByteString (ByteString) import Codec.Picture.Types rawlogo :: ByteString rawlogo = $(embedBSFile "src/image/logo.png") main :: IO () main = runSys' <| do let logo = loadPng (B.Buffer rawlogo) term <- defaultTerminal writeStrLn term "Initializing the system..." sys <- defaultSystemInit let dm = systemDeviceManager sys listDir term "/system/sys/class/sound" wait for mouse driver to be loaded ( FIXME : use plug - and - play detection ) threadDelaySec 2 quitKey <- atomically <| newTVar False mousePos <- newTVarIO (250.0,250.0) let wf = 1024 / 0x7FFF :: Float hf = 768 / 0x7FFF :: Float updateMouseRel dx dy = modifyTVar mousePos \(x,y) -> (x+fromIntegral dx,y+fromIntegral dy) updateMouseAbsX v = modifyTVar mousePos \(_,y) -> (fromIntegral v * wf,y) updateMouseAbsY v = modifyTVar mousePos \(x,_) -> (x,fromIntegral v * hf) points <- newTVarIO [] writeStrLn term "Loading input devices..." inputs <- loadInputDevices dm forM_ inputs \inp -> onEvent (inputDeviceBundles inp) \(InputEventBundle events) -> do atomically <| forM_ (fmap inputEventType events) \case InputKeyEvent KeyPress MouseLeft -> do p <- readTVar mousePos modifyTVar points (p:) mouse move : using qemu -show - cursor InputRelativeEvent RelativeX v -> updateMouseRel v 0 InputRelativeEvent RelativeY v -> updateMouseRel 0 v mouse move : using qemu -usbdevice tablet InputAbsoluteEvent AbsoluteX v -> updateMouseAbsX v InputAbsoluteEvent AbsoluteY v -> updateMouseAbsY v Quit if ESC is pressed InputKeyEvent KeyPress Esc -> writeTVar quitKey True _ -> return () writeStrLn term "Loading graphic cards..." cards <- loadGraphicCards dm forM_ cards \card -> do -- onEvent (graphicCardChan card) <| \ev -> do writeStrLn term ( show ev ) sysLogSequence "Load graphic card" <| do sysAssert "Generic buffer capability supported" (graphicCardCapGenericBuffers card) state <- getEntitiesMap card |> assertE "Read graphics state" encoders <- assertE "Read encoders" <| getHandleEncoders (graphicCardHandle card) let encoderMap = Map.fromList (fmap encoderID encoders `zip` encoders) conns <- if Map.null (entitiesConnectorsMap state) then sysError "No graphics connector found" else return (Map.elems (entitiesConnectorsMap state)) let isValid x = case connectorState x of Connected d -> not (null <| displayModes d) _ -> False validConns = filter isValid conns select first connector conn = head validConns Connected connDev = connectorState conn -- select highest mode mode = head (displayModes connDev) fmt = makePixelFormat XRGB8888 LittleEndian width = fromIntegral <| modeHorizontalDisplay mode :: Float height = fromIntegral <| modeVerticalDisplay mode :: Float frame1 <- createGenericFullScreenFrame card mode fmt 0 frame2 <- createGenericFullScreenFrame card mode fmt 0 let Just ctrl = do encId <- connectorEncoderID conn enc <- Map.lookup encId encoderMap ctrlId <- encoderControllerID enc Map.lookup ctrlId (entitiesControllersMap state) -- set mode and connectors setController ctrl (UseFrame frame1) [conn] (Just mode) |> assertE "Set controller" -- let gamma ' = replicate ( fromIntegral ( controllerGammaTableSize ctrl ) ) 0x0000 -- gamma = (gamma',gamma',gamma') -- setControllerGamma ctrl gamma -- ga <- getControllerGamma ctrl writeStrLn term ( show ) -- frame switch let setFb fb = switchFrame ctrl fb (BitSet.fromList [SwitchFrameGenerateEvent]) 0 |> assertE "Switch frame" setFb frame1 writeStrLn term "Drawing..." fps <- atomically <| newTVar (0 :: Word) let speed = 15 mainLoop !color !b !step = do (mx,my) <- readTVarIO mousePos ps <- readTVarIO points let frame = if b then frame1 else frame2 drawColor = PixelRGBA8 0 0x86 0xc1 255 ptrColor = PixelRGBA8 0x50 0x50 0x50 255 redColor = PixelRGBA8 0x86 0xc1 0 255 bgColor = PixelRGBA8 0 0 0 0 img = renderDrawing (floor width) (floor height) bgColor <| do withTexture (uniformTexture drawColor) <| do forM_ (ps `zip` tail ps) <| \((x1,y1),(x2,y2)) -> stroke 17 JoinRound (CapRound, CapRound) <| line (V2 x1 y1) (V2 x2 y2) when (not (null ps)) <| do let (lx,ly) = head ps withTexture (uniformTexture redColor) <| do stroke 17 JoinRound (CapRound, CapRound) <| line (V2 lx ly) (V2 mx my) withTexture (uniformTexture ptrColor) <| do let len = 8 stroke 2 (JoinMiter 0) (CapStraight 0, CapStraight 0) <| line (V2 (mx-len) my) (V2 (mx+len) my) stroke 2 (JoinMiter 0) (CapStraight 0, CapStraight 0) <| line (V2 mx (my-len)) (V2 mx (my+len)) img2 = rasterizeDiagram (mkWidth width) diag where pts = map (\(x,y) -> D.p2 (x,-1 * y)) ps :: [D.P2 Float] diag = D.rect width height <> D.moveOriginBy (D.r2 (width / 2 :: Float, -1 * height / 2)) (D.position (pts `zip` repeat spot) <> D.cubicSpline False pts ) spot = D.circle 5 # fc blue # lw none liftIO <| do fillFrame frame color blendImage frame img BlendAlpha (0,0) (0,0,imageWidth img, imageHeight img) blendImage frame img2 BlendAlpha (0,0) (0,0,imageWidth img2, imageHeight img2) blendImage frame logo BlendAlpha (20,20) (0,0,imageWidth logo,imageHeight logo) setFb frame atomically <| modifyTVar' fps (+1) threadDelayMilliSec 100 yield -- switch to another thread let !step2 = case color of c | c >= 0x00D3D3FF -> -1 * speed | c <= 0x00D3D300 -> speed | otherwise -> step !color2 = case color+step2 of c | c >= 0x00D3D3FF -> 0xD3D3FF | c <= 0x00D3D300 -> 0xD3D300 | otherwise -> c mainLoop color2 (not b) step2 sysFork "Main display loop" <| mainLoop 0x00D3D300 False speed lift < | fillScreen 0x00D3D3D3 ( ) setFb fb2 -- show FPS sysFork "FPS displayer" <| forever <| do v <- atomically <| swapTVar fps 0 writeStrLn term ("FPS: " ++ show v) threadDelaySec 1 return () return () writeStrLn term "Done." wait for a key in the standard input ( in the console ) or ESC ( in the graphic interface ) sysFork "Wait for key" <| do waitForKey term atomically <| writeTVar quitKey True atomically <| do q <- readTVar quitKey case q of True -> return () False -> retry writeStrLn term "Log:" sysLogPrint -- shutdown the computer powerOff listDir :: Terminal -> FilePath -> Sys () listDir term path = do dls <- assertE "List directory" do rt <- open Nothing path (BitSet.fromList [HandleDirectory]) BitSet.empty |> liftE @(ErrorCode : OpenErrors) ls <- liftE <| listDirectory rt void <| liftE (close rt) return ls writeStrLn term (concat . intersperse "\n" . fmap entryName <| dls)
null
https://raw.githubusercontent.com/haskus/haskus-system/38b3a363c26bc4d82e3493d8638d46bc35678616/haskus-system-examples/src/test/Main.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # onEvent (graphicCardChan card) <| \ev -> do select highest mode set mode and connectors let gamma = (gamma',gamma',gamma') setControllerGamma ctrl gamma ga <- getControllerGamma ctrl frame switch switch to another thread show FPS shutdown the computer
# LANGUAGE TemplateHaskell # # LANGUAGE NoMonomorphismRestriction # # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # # LANGUAGE LambdaCase # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE DataKinds # # LANGUAGE BlockArguments # import Haskus.System import Haskus.System.Linux.FileSystem.Directory import Haskus.System.Linux.FileSystem import qualified Haskus.Binary.Buffer as B import Haskus.Binary.Endianness import qualified Haskus.Binary.BitSet as BitSet import Haskus.System.Linux.Graphics.State import Haskus.System.Linux.Graphics.Mode import Haskus.System.Linux.Graphics.PixelFormat import Haskus.System.Linux.Graphics.Helper import Haskus.System.Linux.Graphics.KIO import Haskus.System.Linux.ErrorCode import Haskus.System.Graphics.Drawing import qualified Haskus.System.Graphics.Diagrams as D import Haskus.System.Graphics.Diagrams ((#),fc,lw,rasterizeDiagram,mkWidth,none) import Haskus.Utils.Embed.ByteString import Haskus.Utils.STM import qualified Haskus.Utils.Map as Map import Data.Colour.Names (blue) import Data.List (intersperse) import Data.ByteString (ByteString) import Codec.Picture.Types rawlogo :: ByteString rawlogo = $(embedBSFile "src/image/logo.png") main :: IO () main = runSys' <| do let logo = loadPng (B.Buffer rawlogo) term <- defaultTerminal writeStrLn term "Initializing the system..." sys <- defaultSystemInit let dm = systemDeviceManager sys listDir term "/system/sys/class/sound" wait for mouse driver to be loaded ( FIXME : use plug - and - play detection ) threadDelaySec 2 quitKey <- atomically <| newTVar False mousePos <- newTVarIO (250.0,250.0) let wf = 1024 / 0x7FFF :: Float hf = 768 / 0x7FFF :: Float updateMouseRel dx dy = modifyTVar mousePos \(x,y) -> (x+fromIntegral dx,y+fromIntegral dy) updateMouseAbsX v = modifyTVar mousePos \(_,y) -> (fromIntegral v * wf,y) updateMouseAbsY v = modifyTVar mousePos \(x,_) -> (x,fromIntegral v * hf) points <- newTVarIO [] writeStrLn term "Loading input devices..." inputs <- loadInputDevices dm forM_ inputs \inp -> onEvent (inputDeviceBundles inp) \(InputEventBundle events) -> do atomically <| forM_ (fmap inputEventType events) \case InputKeyEvent KeyPress MouseLeft -> do p <- readTVar mousePos modifyTVar points (p:) mouse move : using qemu -show - cursor InputRelativeEvent RelativeX v -> updateMouseRel v 0 InputRelativeEvent RelativeY v -> updateMouseRel 0 v mouse move : using qemu -usbdevice tablet InputAbsoluteEvent AbsoluteX v -> updateMouseAbsX v InputAbsoluteEvent AbsoluteY v -> updateMouseAbsY v Quit if ESC is pressed InputKeyEvent KeyPress Esc -> writeTVar quitKey True _ -> return () writeStrLn term "Loading graphic cards..." cards <- loadGraphicCards dm forM_ cards \card -> do writeStrLn term ( show ev ) sysLogSequence "Load graphic card" <| do sysAssert "Generic buffer capability supported" (graphicCardCapGenericBuffers card) state <- getEntitiesMap card |> assertE "Read graphics state" encoders <- assertE "Read encoders" <| getHandleEncoders (graphicCardHandle card) let encoderMap = Map.fromList (fmap encoderID encoders `zip` encoders) conns <- if Map.null (entitiesConnectorsMap state) then sysError "No graphics connector found" else return (Map.elems (entitiesConnectorsMap state)) let isValid x = case connectorState x of Connected d -> not (null <| displayModes d) _ -> False validConns = filter isValid conns select first connector conn = head validConns Connected connDev = connectorState conn mode = head (displayModes connDev) fmt = makePixelFormat XRGB8888 LittleEndian width = fromIntegral <| modeHorizontalDisplay mode :: Float height = fromIntegral <| modeVerticalDisplay mode :: Float frame1 <- createGenericFullScreenFrame card mode fmt 0 frame2 <- createGenericFullScreenFrame card mode fmt 0 let Just ctrl = do encId <- connectorEncoderID conn enc <- Map.lookup encId encoderMap ctrlId <- encoderControllerID enc Map.lookup ctrlId (entitiesControllersMap state) setController ctrl (UseFrame frame1) [conn] (Just mode) |> assertE "Set controller" gamma ' = replicate ( fromIntegral ( controllerGammaTableSize ctrl ) ) 0x0000 writeStrLn term ( show ) let setFb fb = switchFrame ctrl fb (BitSet.fromList [SwitchFrameGenerateEvent]) 0 |> assertE "Switch frame" setFb frame1 writeStrLn term "Drawing..." fps <- atomically <| newTVar (0 :: Word) let speed = 15 mainLoop !color !b !step = do (mx,my) <- readTVarIO mousePos ps <- readTVarIO points let frame = if b then frame1 else frame2 drawColor = PixelRGBA8 0 0x86 0xc1 255 ptrColor = PixelRGBA8 0x50 0x50 0x50 255 redColor = PixelRGBA8 0x86 0xc1 0 255 bgColor = PixelRGBA8 0 0 0 0 img = renderDrawing (floor width) (floor height) bgColor <| do withTexture (uniformTexture drawColor) <| do forM_ (ps `zip` tail ps) <| \((x1,y1),(x2,y2)) -> stroke 17 JoinRound (CapRound, CapRound) <| line (V2 x1 y1) (V2 x2 y2) when (not (null ps)) <| do let (lx,ly) = head ps withTexture (uniformTexture redColor) <| do stroke 17 JoinRound (CapRound, CapRound) <| line (V2 lx ly) (V2 mx my) withTexture (uniformTexture ptrColor) <| do let len = 8 stroke 2 (JoinMiter 0) (CapStraight 0, CapStraight 0) <| line (V2 (mx-len) my) (V2 (mx+len) my) stroke 2 (JoinMiter 0) (CapStraight 0, CapStraight 0) <| line (V2 mx (my-len)) (V2 mx (my+len)) img2 = rasterizeDiagram (mkWidth width) diag where pts = map (\(x,y) -> D.p2 (x,-1 * y)) ps :: [D.P2 Float] diag = D.rect width height <> D.moveOriginBy (D.r2 (width / 2 :: Float, -1 * height / 2)) (D.position (pts `zip` repeat spot) <> D.cubicSpline False pts ) spot = D.circle 5 # fc blue # lw none liftIO <| do fillFrame frame color blendImage frame img BlendAlpha (0,0) (0,0,imageWidth img, imageHeight img) blendImage frame img2 BlendAlpha (0,0) (0,0,imageWidth img2, imageHeight img2) blendImage frame logo BlendAlpha (20,20) (0,0,imageWidth logo,imageHeight logo) setFb frame atomically <| modifyTVar' fps (+1) threadDelayMilliSec 100 let !step2 = case color of c | c >= 0x00D3D3FF -> -1 * speed | c <= 0x00D3D300 -> speed | otherwise -> step !color2 = case color+step2 of c | c >= 0x00D3D3FF -> 0xD3D3FF | c <= 0x00D3D300 -> 0xD3D300 | otherwise -> c mainLoop color2 (not b) step2 sysFork "Main display loop" <| mainLoop 0x00D3D300 False speed lift < | fillScreen 0x00D3D3D3 ( ) setFb fb2 sysFork "FPS displayer" <| forever <| do v <- atomically <| swapTVar fps 0 writeStrLn term ("FPS: " ++ show v) threadDelaySec 1 return () return () writeStrLn term "Done." wait for a key in the standard input ( in the console ) or ESC ( in the graphic interface ) sysFork "Wait for key" <| do waitForKey term atomically <| writeTVar quitKey True atomically <| do q <- readTVar quitKey case q of True -> return () False -> retry writeStrLn term "Log:" sysLogPrint powerOff listDir :: Terminal -> FilePath -> Sys () listDir term path = do dls <- assertE "List directory" do rt <- open Nothing path (BitSet.fromList [HandleDirectory]) BitSet.empty |> liftE @(ErrorCode : OpenErrors) ls <- liftE <| listDirectory rt void <| liftE (close rt) return ls writeStrLn term (concat . intersperse "\n" . fmap entryName <| dls)
4b38b2ae980afd147622c75950209c3ac90ba368ca7c077b39b7791b16f35337
mzp/coq-ruby
tacticals.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) i $ I d : tacticals.mli 11735 2009 - 01 - 02 17:22:31Z herbelin $ i (*i*) open Pp open Util open Names open Term open Sign open Tacmach open Proof_type open Clenv open Reduction open Pattern open Genarg open Tacexpr (*i*) (* Tacticals i.e. functions from tactics to tactics. *) val tclNORMEVAR : tactic val tclIDTAC : tactic val tclIDTAC_MESSAGE : std_ppcmds -> tactic val tclORELSE0 : tactic -> tactic -> tactic val tclORELSE : tactic -> tactic -> tactic val tclTHEN : tactic -> tactic -> tactic val tclTHENSEQ : tactic list -> tactic val tclTHENLIST : tactic list -> tactic val tclTHEN_i : tactic -> (int -> tactic) -> tactic val tclTHENFIRST : tactic -> tactic -> tactic val tclTHENLAST : tactic -> tactic -> tactic val tclTHENS : tactic -> tactic list -> tactic val tclTHENSV : tactic -> tactic array -> tactic val tclTHENSLASTn : tactic -> tactic -> tactic array -> tactic val tclTHENLASTn : tactic -> tactic array -> tactic val tclTHENSFIRSTn : tactic -> tactic array -> tactic -> tactic val tclTHENFIRSTn : tactic -> tactic array -> tactic val tclREPEAT : tactic -> tactic val tclREPEAT_MAIN : tactic -> tactic val tclFIRST : tactic list -> tactic val tclSOLVE : tactic list -> tactic val tclTRY : tactic -> tactic val tclINFO : tactic -> tactic val tclCOMPLETE : tactic -> tactic val tclAT_LEAST_ONCE : tactic -> tactic val tclFAIL : int -> std_ppcmds -> tactic val tclDO : int -> tactic -> tactic val tclPROGRESS : tactic -> tactic val tclWEAK_PROGRESS : tactic -> tactic val tclNOTSAMEGOAL : tactic -> tactic val tclTHENTRY : tactic -> tactic -> tactic val tclNTH_HYP : int -> (constr -> tactic) -> tactic val tclNTH_DECL : int -> (named_declaration -> tactic) -> tactic val tclMAP : ('a -> tactic) -> 'a list -> tactic val tclLAST_HYP : (constr -> tactic) -> tactic val tclLAST_DECL : (named_declaration -> tactic) -> tactic val tclLAST_NHYPS : int -> (identifier list -> tactic) -> tactic val tclTRY_sign : (constr -> tactic) -> named_context -> tactic val tclTRY_HYPS : (constr -> tactic) -> tactic val tclIFTHENELSE : tactic -> tactic -> tactic -> tactic val tclIFTHENSELSE : tactic -> tactic list -> tactic -> tactic val tclIFTHENSVELSE : tactic -> tactic array -> tactic -> tactic val tclIFTHENTRYELSEMUST : tactic -> tactic -> tactic val unTAC : tactic -> goal sigma -> proof_tree sigma (*s Clause tacticals. *) type simple_clause = identifier gsimple_clause type clause = identifier gclause val allClauses : 'a gclause val allHyps : clause val onHyp : identifier -> clause val onConcl : 'a gclause val nth_clause : int -> goal sigma -> clause val clause_type : clause -> goal sigma -> constr val simple_clause_list_of : clause -> goal sigma -> simple_clause list val pf_matches : goal sigma -> constr_pattern -> constr -> patvar_map val pf_is_matching : goal sigma -> constr_pattern -> constr -> bool val afterHyp : identifier -> goal sigma -> named_context val lastHyp : goal sigma -> identifier val nLastHyps : int -> goal sigma -> named_context val onCL : (goal sigma -> clause) -> (clause -> tactic) -> tactic val tryAllClauses : (simple_clause -> tactic) -> tactic val onAllClauses : (simple_clause -> tactic) -> tactic val onClause : (clause -> tactic) -> clause -> tactic val onClauses : (simple_clause -> tactic) -> clause -> tactic val onAllClausesLR : (simple_clause -> tactic) -> tactic val onNthLastHyp : int -> (clause -> tactic) -> tactic val clauseTacThen : (clause -> tactic) -> tactic -> clause -> tactic val if_tac : (goal sigma -> bool) -> tactic -> (tactic) -> tactic val ifOnClause : (clause * types -> bool) -> (clause -> tactic) -> (clause -> tactic) -> clause -> tactic val ifOnHyp : (identifier * types -> bool) -> (identifier -> tactic) -> (identifier -> tactic) -> identifier -> tactic val onHyps : (goal sigma -> named_context) -> (named_context -> tactic) -> tactic val tryAllHyps : (identifier -> tactic) -> tactic val onNLastHyps : int -> (named_declaration -> tactic) -> tactic val onLastHyp : (identifier -> tactic) -> tactic (*s Elimination tacticals. *) type branch_args = { ity : inductive; (* the type we were eliminating on *) largs : constr list; (* its arguments *) branchnum : int; (* the branch number *) pred : constr; (* the predicate we used *) nassums : int; (* the number of assumptions to be introduced *) branchsign : bool list; (* the signature of the branch. true=recursive argument, false=constant *) branchnames : intro_pattern_expr located list} type branch_assumptions = { ba : branch_args; (* the branch args *) assums : named_context} (* the list of assumptions introduced *) [ check_disjunctive_pattern_size loc pats n ] returns an appropriate (* error message if |pats| <> n *) val check_or_and_pattern_size : Util.loc -> or_and_intro_pattern_expr -> int -> unit (* Tolerate "[]" to mean a disjunctive pattern of any length *) val fix_empty_or_and_pattern : int -> or_and_intro_pattern_expr -> or_and_intro_pattern_expr (* Useful for [as intro_pattern] modifier *) val compute_induction_names : int -> intro_pattern_expr located option -> intro_pattern_expr located list array val elimination_sort_of_goal : goal sigma -> sorts_family val elimination_sort_of_hyp : identifier -> goal sigma -> sorts_family val elimination_sort_of_clause : identifier option -> goal sigma -> sorts_family val general_elim_then_using : (inductive -> goal sigma -> constr) -> rec_flag -> intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val elimination_then_using : (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> constr -> tactic val elimination_then : (branch_args -> tactic) -> (arg_bindings * arg_bindings) -> constr -> tactic val case_then_using : intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val case_nodep_then_using : intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val simple_elimination_then : (branch_args -> tactic) -> constr -> tactic val elim_on_ba : (branch_assumptions -> tactic) -> branch_args -> tactic val case_on_ba : (branch_assumptions -> tactic) -> branch_args -> tactic
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/tactics/tacticals.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i i Tacticals i.e. functions from tactics to tactics. s Clause tacticals. s Elimination tacticals. the type we were eliminating on its arguments the branch number the predicate we used the number of assumptions to be introduced the signature of the branch. true=recursive argument, false=constant the branch args the list of assumptions introduced error message if |pats| <> n Tolerate "[]" to mean a disjunctive pattern of any length Useful for [as intro_pattern] modifier
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i $ I d : tacticals.mli 11735 2009 - 01 - 02 17:22:31Z herbelin $ i open Pp open Util open Names open Term open Sign open Tacmach open Proof_type open Clenv open Reduction open Pattern open Genarg open Tacexpr val tclNORMEVAR : tactic val tclIDTAC : tactic val tclIDTAC_MESSAGE : std_ppcmds -> tactic val tclORELSE0 : tactic -> tactic -> tactic val tclORELSE : tactic -> tactic -> tactic val tclTHEN : tactic -> tactic -> tactic val tclTHENSEQ : tactic list -> tactic val tclTHENLIST : tactic list -> tactic val tclTHEN_i : tactic -> (int -> tactic) -> tactic val tclTHENFIRST : tactic -> tactic -> tactic val tclTHENLAST : tactic -> tactic -> tactic val tclTHENS : tactic -> tactic list -> tactic val tclTHENSV : tactic -> tactic array -> tactic val tclTHENSLASTn : tactic -> tactic -> tactic array -> tactic val tclTHENLASTn : tactic -> tactic array -> tactic val tclTHENSFIRSTn : tactic -> tactic array -> tactic -> tactic val tclTHENFIRSTn : tactic -> tactic array -> tactic val tclREPEAT : tactic -> tactic val tclREPEAT_MAIN : tactic -> tactic val tclFIRST : tactic list -> tactic val tclSOLVE : tactic list -> tactic val tclTRY : tactic -> tactic val tclINFO : tactic -> tactic val tclCOMPLETE : tactic -> tactic val tclAT_LEAST_ONCE : tactic -> tactic val tclFAIL : int -> std_ppcmds -> tactic val tclDO : int -> tactic -> tactic val tclPROGRESS : tactic -> tactic val tclWEAK_PROGRESS : tactic -> tactic val tclNOTSAMEGOAL : tactic -> tactic val tclTHENTRY : tactic -> tactic -> tactic val tclNTH_HYP : int -> (constr -> tactic) -> tactic val tclNTH_DECL : int -> (named_declaration -> tactic) -> tactic val tclMAP : ('a -> tactic) -> 'a list -> tactic val tclLAST_HYP : (constr -> tactic) -> tactic val tclLAST_DECL : (named_declaration -> tactic) -> tactic val tclLAST_NHYPS : int -> (identifier list -> tactic) -> tactic val tclTRY_sign : (constr -> tactic) -> named_context -> tactic val tclTRY_HYPS : (constr -> tactic) -> tactic val tclIFTHENELSE : tactic -> tactic -> tactic -> tactic val tclIFTHENSELSE : tactic -> tactic list -> tactic -> tactic val tclIFTHENSVELSE : tactic -> tactic array -> tactic -> tactic val tclIFTHENTRYELSEMUST : tactic -> tactic -> tactic val unTAC : tactic -> goal sigma -> proof_tree sigma type simple_clause = identifier gsimple_clause type clause = identifier gclause val allClauses : 'a gclause val allHyps : clause val onHyp : identifier -> clause val onConcl : 'a gclause val nth_clause : int -> goal sigma -> clause val clause_type : clause -> goal sigma -> constr val simple_clause_list_of : clause -> goal sigma -> simple_clause list val pf_matches : goal sigma -> constr_pattern -> constr -> patvar_map val pf_is_matching : goal sigma -> constr_pattern -> constr -> bool val afterHyp : identifier -> goal sigma -> named_context val lastHyp : goal sigma -> identifier val nLastHyps : int -> goal sigma -> named_context val onCL : (goal sigma -> clause) -> (clause -> tactic) -> tactic val tryAllClauses : (simple_clause -> tactic) -> tactic val onAllClauses : (simple_clause -> tactic) -> tactic val onClause : (clause -> tactic) -> clause -> tactic val onClauses : (simple_clause -> tactic) -> clause -> tactic val onAllClausesLR : (simple_clause -> tactic) -> tactic val onNthLastHyp : int -> (clause -> tactic) -> tactic val clauseTacThen : (clause -> tactic) -> tactic -> clause -> tactic val if_tac : (goal sigma -> bool) -> tactic -> (tactic) -> tactic val ifOnClause : (clause * types -> bool) -> (clause -> tactic) -> (clause -> tactic) -> clause -> tactic val ifOnHyp : (identifier * types -> bool) -> (identifier -> tactic) -> (identifier -> tactic) -> identifier -> tactic val onHyps : (goal sigma -> named_context) -> (named_context -> tactic) -> tactic val tryAllHyps : (identifier -> tactic) -> tactic val onNLastHyps : int -> (named_declaration -> tactic) -> tactic val onLastHyp : (identifier -> tactic) -> tactic type branch_args = { branchnames : intro_pattern_expr located list} type branch_assumptions = { [ check_disjunctive_pattern_size loc pats n ] returns an appropriate val check_or_and_pattern_size : Util.loc -> or_and_intro_pattern_expr -> int -> unit val fix_empty_or_and_pattern : int -> or_and_intro_pattern_expr -> or_and_intro_pattern_expr val compute_induction_names : int -> intro_pattern_expr located option -> intro_pattern_expr located list array val elimination_sort_of_goal : goal sigma -> sorts_family val elimination_sort_of_hyp : identifier -> goal sigma -> sorts_family val elimination_sort_of_clause : identifier option -> goal sigma -> sorts_family val general_elim_then_using : (inductive -> goal sigma -> constr) -> rec_flag -> intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val elimination_then_using : (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> constr -> tactic val elimination_then : (branch_args -> tactic) -> (arg_bindings * arg_bindings) -> constr -> tactic val case_then_using : intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val case_nodep_then_using : intro_pattern_expr located option -> (branch_args -> tactic) -> constr option -> (arg_bindings * arg_bindings) -> inductive -> clausenv -> tactic val simple_elimination_then : (branch_args -> tactic) -> constr -> tactic val elim_on_ba : (branch_assumptions -> tactic) -> branch_args -> tactic val case_on_ba : (branch_assumptions -> tactic) -> branch_args -> tactic
38c21da19768c658c1d419b6b0395282e508f3fe85e61ef5b547c45d41e940ad
chenyukang/eopl
21.scm
(load-relative "../libs/init.scm") (load-relative "./base/classes/test.scm") (load-relative "./base/classes/store.scm") (load-relative "./base/classes/data-structures.scm") (load-relative "./base/classes/environments.scm") (load-relative "./base/classes/lang.scm") (load-relative "./base/classes/interp.scm") (load-relative "./base/classes/classes.scm") (load-relative "./base/classes/class-cases.scm") ;; use hash-table for method-env lookup - method will cost O(1 ) in thoery . ;; find-method : Sym * Sym -> Method (define find-method (lambda (c-name name) (let ((m-env (class->method-env (lookup-class c-name)))) (if (hash-table-exists? m-env name) (hash-table-ref m-env name) (report-method-not-found name))))) (define report-method-not-found (lambda (name) (error 'find-method "unknown method ~s" name))) ;; merge-method-envs : MethodEnv * MethodEnv -> MethodEnv (define merge-method-envs (lambda (super-m-env new-m-env) (begin (hash-table-for-each super-m-env (lambda (k v) (if (not (hash-table-exists? new-m-env k)) (hash-table-set! new-m-env k v)))) new-m-env))) ;; method-decls->method-env : ;; Listof(MethodDecl) * ClassName * Listof(FieldName) -> MethodEnv (define method-decls->method-env (lambda (m-decls super-name field-names) (let ((m-env (make-hash-table))) (begin (map (lambda (m-decl) (cases method-decl m-decl (a-method-decl (method-name vars body) (hash-table-set! m-env method-name (a-method vars body super-name field-names))))) m-decls) m-env)))) ;; just use hash-table? (define method-environment? hash-table?) (define-datatype class class? (a-class (super-name (maybe symbol?)) (field-names (list-of symbol?)) (method-env method-environment?))) (define initialize-class-env! (lambda (c-decls) (set! the-class-env (list (list 'object (a-class #f '() (make-hash-table))))) (for-each initialize-class-decl! c-decls))) ;; initialize-class-decl! : ClassDecl -> Unspecified (define initialize-class-decl! (lambda (c-decl) (cases class-decl c-decl (a-class-decl (c-name s-name f-names m-decls) (let ((f-names (append-field-names (class->field-names (lookup-class s-name)) f-names))) (add-to-class-env! c-name (a-class s-name f-names (merge-method-envs (class->method-env (lookup-class s-name)) (method-decls->method-env m-decls s-name f-names))))))))) (run-all)
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch9/21.scm
scheme
use hash-table for method-env find-method : Sym * Sym -> Method merge-method-envs : MethodEnv * MethodEnv -> MethodEnv method-decls->method-env : Listof(MethodDecl) * ClassName * Listof(FieldName) -> MethodEnv just use hash-table? initialize-class-decl! : ClassDecl -> Unspecified
(load-relative "../libs/init.scm") (load-relative "./base/classes/test.scm") (load-relative "./base/classes/store.scm") (load-relative "./base/classes/data-structures.scm") (load-relative "./base/classes/environments.scm") (load-relative "./base/classes/lang.scm") (load-relative "./base/classes/interp.scm") (load-relative "./base/classes/classes.scm") (load-relative "./base/classes/class-cases.scm") lookup - method will cost O(1 ) in thoery . (define find-method (lambda (c-name name) (let ((m-env (class->method-env (lookup-class c-name)))) (if (hash-table-exists? m-env name) (hash-table-ref m-env name) (report-method-not-found name))))) (define report-method-not-found (lambda (name) (error 'find-method "unknown method ~s" name))) (define merge-method-envs (lambda (super-m-env new-m-env) (begin (hash-table-for-each super-m-env (lambda (k v) (if (not (hash-table-exists? new-m-env k)) (hash-table-set! new-m-env k v)))) new-m-env))) (define method-decls->method-env (lambda (m-decls super-name field-names) (let ((m-env (make-hash-table))) (begin (map (lambda (m-decl) (cases method-decl m-decl (a-method-decl (method-name vars body) (hash-table-set! m-env method-name (a-method vars body super-name field-names))))) m-decls) m-env)))) (define method-environment? hash-table?) (define-datatype class class? (a-class (super-name (maybe symbol?)) (field-names (list-of symbol?)) (method-env method-environment?))) (define initialize-class-env! (lambda (c-decls) (set! the-class-env (list (list 'object (a-class #f '() (make-hash-table))))) (for-each initialize-class-decl! c-decls))) (define initialize-class-decl! (lambda (c-decl) (cases class-decl c-decl (a-class-decl (c-name s-name f-names m-decls) (let ((f-names (append-field-names (class->field-names (lookup-class s-name)) f-names))) (add-to-class-env! c-name (a-class s-name f-names (merge-method-envs (class->method-env (lookup-class s-name)) (method-decls->method-env m-decls s-name f-names))))))))) (run-all)
279c320c1ddf2f7d49be7998d5a711eb17e40d603c940faf22d6a6770495fc35
mayconamaro/ringell
Spec.hs
import Generation () import Generator import Test.QuickCheck import Test.HUnit import Parsing (allUnitTests) main :: IO () main = do runTestTT allUnitTests quickCheck (withMaxSuccess 100 propWellTyped) quickCheck (withMaxSuccess 100 propSemPreservation)
null
https://raw.githubusercontent.com/mayconamaro/ringell/4bca3d89188d775f1089575552588630710276b2/Compiler%20first%20version/test/Spec.hs
haskell
import Generation () import Generator import Test.QuickCheck import Test.HUnit import Parsing (allUnitTests) main :: IO () main = do runTestTT allUnitTests quickCheck (withMaxSuccess 100 propWellTyped) quickCheck (withMaxSuccess 100 propSemPreservation)
9e48ff3157a6f55b76987b1ad99096cb220477502198c75fecf0a7b2986bc101
Ferada/cl-mock
mock.lisp
-*- mode : lisp ; syntax : common - lisp ; coding : utf-8 - unix ; package : cl - mock - tests ; -*- (in-package #:cl-mock-tests) (in-suite cl-mock) (def-test call-with-mocks.empty () (is (eq T (with-mocks () T)))) (def-test call-with-mocks.discards-values () (is (equal '(1 2 3) (multiple-value-list (with-mocks () (values 1 2 3)))))) (declaim (notinline foo/simple)) (defun foo/simple () (fail "original function binding ~A was called" 'foo/simple)) (def-test call-with-mocks.simple () (with-mocks () (register-mock 'foo/simple) (foo/simple) (pass))) (declaim (notinline foo bar)) (defun foo () 'foo) (defun bar () 'bar) (def-test call-with-mocks.default-values () (with-mocks () (register-mock 'foo) (is (null (multiple-value-list (foo)))))) (def-test if-called.simple () (with-mocks () (if-called 'foo (constantly 42)) (is (eql 42 (foo))))) (def-test invocations.length () (with-mocks () (register-mock 'foo) (dotimes (i 3) (foo)) (is (eql 3 (length (invocations)))))) (def-test invocations.arguments () (with-mocks () (register-mock 'foo) (let ((sym (gensym))) (foo sym) (is (equal `((foo ,sym)) (invocations)))))) (def-test invocations.name () (with-mocks () (register-mock 'foo) (register-mock 'bar) (foo) (bar) (is (equal '((foo)) (invocations 'foo))))) ;; utility function to check asynchronous results (defun assert-cond (assert-fun max-time &optional (sleep-time 0.05)) (do ((wait-time sleep-time (+ wait-time sleep-time)) (fun-result nil (funcall assert-fun))) ((eq fun-result t) (return t)) (if (> wait-time max-time) (return) (sleep sleep-time)))) (def-test invocations.threaded () (with-mocks () (register-mock 'foo) (register-mock 'bar) (bt:make-thread (lambda () (foo) (bar))) (is (assert-cond (lambda () (and (equal '((foo)) (invocations 'foo)) (equal '((bar)) (invocations 'bar)))) .5))))
null
https://raw.githubusercontent.com/Ferada/cl-mock/01762fda96718fefd3745ce4a20a4013a865b109/tests/mock.lisp
lisp
syntax : common - lisp ; coding : utf-8 - unix ; package : cl - mock - tests ; -*- utility function to check asynchronous results
(in-package #:cl-mock-tests) (in-suite cl-mock) (def-test call-with-mocks.empty () (is (eq T (with-mocks () T)))) (def-test call-with-mocks.discards-values () (is (equal '(1 2 3) (multiple-value-list (with-mocks () (values 1 2 3)))))) (declaim (notinline foo/simple)) (defun foo/simple () (fail "original function binding ~A was called" 'foo/simple)) (def-test call-with-mocks.simple () (with-mocks () (register-mock 'foo/simple) (foo/simple) (pass))) (declaim (notinline foo bar)) (defun foo () 'foo) (defun bar () 'bar) (def-test call-with-mocks.default-values () (with-mocks () (register-mock 'foo) (is (null (multiple-value-list (foo)))))) (def-test if-called.simple () (with-mocks () (if-called 'foo (constantly 42)) (is (eql 42 (foo))))) (def-test invocations.length () (with-mocks () (register-mock 'foo) (dotimes (i 3) (foo)) (is (eql 3 (length (invocations)))))) (def-test invocations.arguments () (with-mocks () (register-mock 'foo) (let ((sym (gensym))) (foo sym) (is (equal `((foo ,sym)) (invocations)))))) (def-test invocations.name () (with-mocks () (register-mock 'foo) (register-mock 'bar) (foo) (bar) (is (equal '((foo)) (invocations 'foo))))) (defun assert-cond (assert-fun max-time &optional (sleep-time 0.05)) (do ((wait-time sleep-time (+ wait-time sleep-time)) (fun-result nil (funcall assert-fun))) ((eq fun-result t) (return t)) (if (> wait-time max-time) (return) (sleep sleep-time)))) (def-test invocations.threaded () (with-mocks () (register-mock 'foo) (register-mock 'bar) (bt:make-thread (lambda () (foo) (bar))) (is (assert-cond (lambda () (and (equal '((foo)) (invocations 'foo)) (equal '((bar)) (invocations 'bar)))) .5))))
0caa2906654483cc0edb0d5b94fca86dac35767a44925bed0bc39787ee5e6bf7
ygmpkk/house
Parse.hs
| A parser for the Xtract command - language . ( The string input is -- tokenised internally by the lexer 'lexXtract'.) -- See <> for the grammar that -- is accepted. Because the original Xtract grammar was left - recursive , we have -- transformed it into a non-left-recursive form. module Text.XML.HaXml.Xtract.Parse (parseXtract) where #ifdef __NHC__ import NonStdTrace (trace) #endif import Text.ParserCombinators.HuttonMeijerWallace hiding (bracket,elserror) import Text.XML.HaXml.Xtract.Lex import Text.XML.HaXml.Xtract.Combinators import Text.XML.HaXml.Combinators import List(isPrefixOf) | The cool thing is that the Xtract command parser directly builds a higher - order ' DFilter ' ( see " Text . Xml . HaXml . Xtract . Combinators " ) which can be applied to an XML document without further ado . parseXtract :: String -> DFilter parseXtract = sanitycheck . papply xql () . lexXtract sanitycheck :: (Show p,Show t) => [(a,s,[(p,t)])] -> a sanitycheck [] = error "***Error at char pos 0 in expression: no parse" sanitycheck ((x,_,[]):_) = x sanitycheck ((x,_,s@((n,_):_)):xs) = error ("***Error at "++show n++" in search expression: \""++remainder++"\"") where remainder = concatMap (show.snd) s xql = aquery (global keep) ---- Auxiliary Parsing Functions ---- string :: Parser s Token String string = P (\st inp -> case inp of { ((p,TokString n):ts) -> [(n,st,ts)]; ts -> [] } ) number :: Parser s Token Integer number = P (\st inp -> case inp of { ((p,TokNum n):ts) -> [(n,st,ts)]; ts -> [] } ) symbol :: String -> Parser s Token () symbol s = P (\st inp -> case inp of { ((p, Symbol n):ts) -> if n==s then [((),st,ts)] else []; ts -> [] } ) quote = symbol "'" +++ symbol "\"" pam fs x = [ f x | f <- fs ] -- original Xtract grammar ---- query = string tagname | string * tagname prefix | * string tagname suffix | * any element | - chardata | ( query ) | query / query parent / child relationship | query // query deep inside | query + query union of queries | query [ predicate ] | query [ positions ] predicate = quattr has attribute | quattr op ' string ' attribute has value | quattr op " string " attribute has value | quattr op quattr attribute value comparison ( lexical ) | quattr nop integer attribute has value ( numerical ) | quattr nop quattr attribute value comparison ( numerical ) | ( predicate ) bracketting | predicate & predicate logical and | predicate | predicate logical or | ~ predicate logical not attribute = @ string has attribute | query / @ string child has attribute | - has textual content | query / - child has textual content quattr = query | attribute op = = equal to | ! = not equal to | < less than | < = less than or equal to | > greater than | > = greater than or equal to nop = .=. equal to | .!=. not equal to | . < . less than | .<=. less than or equal to | . > . greater than | .>=. greater than or equal to positions = position { , positions } multiple positions | position - position ranges position = integer numbering is from 0 upwards | $ last ---- transformed grammar ( removing left recursion ) aquery = -- current context | tquery -- also current context | / tquery -- root context | // tquery -- deep context from root tquery = ( tquery ) xquery | tag xquery | - -- fixes original grammar ( " -/ * " is incorrect ) tag = string * | string | * string | * xquery = / tquery | // tquery | / @ string -- new : print attribute value | + tquery | [ tpredicate ] xquery | [ positions ] xquery | lambda tpredicate = vpredicate upredicate upredicate = & tpredicate | | tpredicate | lambda vpredicate = ( tpredicate ) | ~ tpredicate | tattribute tattribute = aquery uattribute | @ string vattribute uattribute = / @ string vattribute | vattribute vattribute = op wattribute | op ' string ' | nop wattribute | nop integer | lambda wattribute = @ string | aquery / @ string | aquery positions = integer range | $ range = - integer | - $ | lambda commapos = , | lambda op = = | ! = | < | < = | > | > = nop = .=. | .!=. | . < . | .<=. | . > . | .>=. query = string tagname | string * tagname prefix | * string tagname suffix | * any element | - chardata | ( query ) | query / query parent/child relationship | query // query deep inside | query + query union of queries | query [predicate] | query [positions] predicate = quattr has attribute | quattr op ' string ' attribute has value | quattr op " string " attribute has value | quattr op quattr attribute value comparison (lexical) | quattr nop integer attribute has value (numerical) | quattr nop quattr attribute value comparison (numerical) | ( predicate ) bracketting | predicate & predicate logical and | predicate | predicate logical or | ~ predicate logical not attribute = @ string has attribute | query / @ string child has attribute | - has textual content | query / - child has textual content quattr = query | attribute op = = equal to | != not equal to | < less than | <= less than or equal to | > greater than | >= greater than or equal to nop = .=. equal to | .!=. not equal to | .<. less than | .<=. less than or equal to | .>. greater than | .>=. greater than or equal to positions = position {, positions} multiple positions | position - position ranges position = integer numbering is from 0 upwards | $ last ---- transformed grammar (removing left recursion) aquery = ./ tquery -- current context | tquery -- also current context | / tquery -- root context | // tquery -- deep context from root tquery = ( tquery ) xquery | tag xquery | - -- fixes original grammar ("-/*" is incorrect) tag = string * | string | * string | * xquery = / tquery | // tquery | / @ string -- new: print attribute value | + tquery | [ tpredicate ] xquery | [ positions ] xquery | lambda tpredicate = vpredicate upredicate upredicate = & tpredicate | | tpredicate | lambda vpredicate = ( tpredicate ) | ~ tpredicate | tattribute tattribute = aquery uattribute | @ string vattribute uattribute = / @ string vattribute | vattribute vattribute = op wattribute | op ' string ' | nop wattribute | nop integer | lambda wattribute = @ string | aquery / @ string | aquery positions = simplepos commapos simplepos = integer range | $ range = - integer | - $ | lambda commapos = , simplepos commapos | lambda op = = | != | < | <= | > | >= nop = .=. | .!=. | .<. | .<=. | .>. | .>=. -} bracket :: Parser s Token a -> Parser s Token a bracket p = do symbol "(" x <- p symbol ")" return x ---- Xtract parsers ---- -- aquery takes a localisation filter, but if the query string starts -- from the root, we ignore the local context aquery :: DFilter -> Parser s Token DFilter aquery localise = ( do symbol "//" tquery [oglobo deep] ) +++ ( do symbol "/" tquery [oglobo id] ) +++ ( do symbol "./" tquery [(localise //>>)] ) +++ ( do tquery [(localise //>>)] ) tquery :: [DFilter->DFilter] -> Parser s Token DFilter tquery [] = tquery [id] tquery (qf:cxt) = ( do q <- bracket (tquery (qf:qf:cxt)) xquery cxt q ) +++ ( do q <- xtag xquery cxt (qf q) ) +++ ( do symbol "-" return (qf (local txt)) ) xtag :: Parser s Token DFilter xtag = ( do s <- string symbol "*" return (local (tagWith (s `isPrefixOf`))) ) +++ ( do s <- string return (local (tag s)) ) +++ ( do symbol "*" s <- string return (local (tagWith (((reverse s) `isPrefixOf`) . reverse))) ) +++ ( do symbol "*" return (local elm) ) xquery :: [DFilter->DFilter] -> DFilter -> Parser s Token DFilter xquery cxt q1 = ( do symbol "/" ((do symbol "@" attr <- string return (oiffindo attr (\s->local (literal s)) ononeo `ooo` q1)) +++ tquery ((q1 //>>):cxt)) ) +++ ( do symbol "//" tquery ((\q2-> (oloco deep) q2 `ooo` local children `ooo` q1):cxt) ) +++ ( do symbol "+" q2 <- tquery cxt return (ocato [q1,q2]) ) +++ ( do symbol "[" is <- iindex -- now extended to multiple indexes symbol "]" xquery cxt (\xml-> concat . pam is . q1 xml) ) +++ ( do symbol "[" p <- tpredicate symbol "]" xquery cxt (q1 `owitho` p) ) +++ ( do return q1 ) tpredicate :: Parser s Token DFilter tpredicate = do p <- vpredicate f <- upredicate return (f p) upredicate :: Parser s Token (DFilter->DFilter) upredicate = ( do symbol "&" p2 <- tpredicate return (`ooo` p2) ) +++ ( do symbol "|" p2 <- tpredicate return (||>|| p2) ) +++ ( do return id ) vpredicate :: Parser s Token DFilter vpredicate = ( do bracket tpredicate ) +++ ( do symbol "~" p <- tpredicate return (local keep `owithouto` p) ) +++ ( do tattribute ) tattribute :: Parser s Token DFilter tattribute = ( do q <- aquery (local keep) uattribute q ) +++ ( do symbol "@" s <- string vattribute (local keep, local (attr s), oiffindo s) ) uattribute :: DFilter -> Parser s Token DFilter uattribute q = ( do symbol "/" symbol "@" s <- string vattribute (q, local (attr s), oiffindo s) ) +++ ( do vattribute (q, local keep, oifTxto) ) vattribute :: (DFilter, DFilter, (String->DFilter)->DFilter->DFilter) -> Parser s Token DFilter vattribute (q,a,iffn) = ( do cmp <- op quote s2 <- string quote return ((iffn (\s1->if cmp s1 s2 then okeepo else ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- op (q2,iffn2) <- wattribute return ((iffn (\s1-> iffn2 (\s2-> if cmp s1 s2 then okeepo else ononeo) ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- nop n <- number return ((iffn (\s->if cmp (read s) n then okeepo else ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- nop (q2,iffn2) <- wattribute return ((iffn (\s1-> iffn2 (\s2-> if cmp (read s1) (read s2) then okeepo else ononeo) ononeo) ononeo) `ooo` q) ) +++ ( do return ((a `ooo` q))) wattribute :: Parser s Token (DFilter, (String->DFilter)->DFilter->DFilter) wattribute = ( do symbol "@" s <- string return (okeepo, oiffindo s) ) +++ ( do q <- aquery okeepo symbol "/" symbol "@" s <- string return (q, oiffindo s) ) +++ ( do q <- aquery okeepo return (q, oifTxto) ) iindex :: Parser s Token [[a]->[a]] iindex = do i <- simpleindex is <- idxcomma return (i:is) simpleindex :: Parser s Token ([a]->[a]) simpleindex = ( do n <- number r <- rrange n return r ) +++ ( do symbol "$" return (keep . last) ) rrange, numberdollar :: Integer -> Parser s Token ([a]->[a]) rrange n1 = ( do symbol "-" numberdollar n1 ) +++ ( do return (keep.(!!(fromInteger n1))) ) numberdollar n1 = ( do n2 <- number return (take (fromInteger (1+n2-n1)) . drop (fromInteger n1)) ) +++ ( do symbol "$" return (drop (fromInteger n1)) ) idxcomma :: Parser s Token [[a]->[a]] idxcomma = ( do symbol "," r <- simpleindex rs <- idxcomma return (r:rs) ) +++ ( do return [] ) op :: Parser s Token (String->String->Bool) op = ( do symbol "=" return (==) ) +++ ( do symbol "!=" return (/=) ) +++ ( do symbol "<" return (<) ) +++ ( do symbol "<=" return (<=) ) +++ ( do symbol ">" return (>) ) +++ ( do symbol ">=" return (>=) ) nop :: Parser s Token (Integer->Integer->Bool) nop = ( do symbol ".=." return (==) ) +++ ( do symbol ".!=." return (/=) ) +++ ( do symbol ".<." return (<) ) +++ ( do symbol ".<=." return (<=) ) +++ ( do symbol ".>." return (>) ) +++ ( do symbol ".>=." return (>=) )
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/HaXml/src/Text/XML/HaXml/Xtract/Parse.hs
haskell
tokenised internally by the lexer 'lexXtract'.) See <> for the grammar that is accepted. transformed it into a non-left-recursive form. -- Auxiliary Parsing Functions ---- original Xtract grammar ---- -- transformed grammar ( removing left recursion ) current context also current context root context deep context from root fixes original grammar ( " -/ * " is incorrect ) new : print attribute value -- transformed grammar (removing left recursion) current context also current context root context deep context from root fixes original grammar ("-/*" is incorrect) new: print attribute value -- Xtract parsers ---- aquery takes a localisation filter, but if the query string starts from the root, we ignore the local context now extended to multiple indexes
| A parser for the Xtract command - language . ( The string input is Because the original Xtract grammar was left - recursive , we have module Text.XML.HaXml.Xtract.Parse (parseXtract) where #ifdef __NHC__ import NonStdTrace (trace) #endif import Text.ParserCombinators.HuttonMeijerWallace hiding (bracket,elserror) import Text.XML.HaXml.Xtract.Lex import Text.XML.HaXml.Xtract.Combinators import Text.XML.HaXml.Combinators import List(isPrefixOf) | The cool thing is that the Xtract command parser directly builds a higher - order ' DFilter ' ( see " Text . Xml . HaXml . Xtract . Combinators " ) which can be applied to an XML document without further ado . parseXtract :: String -> DFilter parseXtract = sanitycheck . papply xql () . lexXtract sanitycheck :: (Show p,Show t) => [(a,s,[(p,t)])] -> a sanitycheck [] = error "***Error at char pos 0 in expression: no parse" sanitycheck ((x,_,[]):_) = x sanitycheck ((x,_,s@((n,_):_)):xs) = error ("***Error at "++show n++" in search expression: \""++remainder++"\"") where remainder = concatMap (show.snd) s xql = aquery (global keep) string :: Parser s Token String string = P (\st inp -> case inp of { ((p,TokString n):ts) -> [(n,st,ts)]; ts -> [] } ) number :: Parser s Token Integer number = P (\st inp -> case inp of { ((p,TokNum n):ts) -> [(n,st,ts)]; ts -> [] } ) symbol :: String -> Parser s Token () symbol s = P (\st inp -> case inp of { ((p, Symbol n):ts) -> if n==s then [((),st,ts)] else []; ts -> [] } ) quote = symbol "'" +++ symbol "\"" pam fs x = [ f x | f <- fs ] query = string tagname | string * tagname prefix | * string tagname suffix | * any element | - chardata | ( query ) | query / query parent / child relationship | query // query deep inside | query + query union of queries | query [ predicate ] | query [ positions ] predicate = quattr has attribute | quattr op ' string ' attribute has value | quattr op " string " attribute has value | quattr op quattr attribute value comparison ( lexical ) | quattr nop integer attribute has value ( numerical ) | quattr nop quattr attribute value comparison ( numerical ) | ( predicate ) bracketting | predicate & predicate logical and | predicate | predicate logical or | ~ predicate logical not attribute = @ string has attribute | query / @ string child has attribute | - has textual content | query / - child has textual content quattr = query | attribute op = = equal to | ! = not equal to | < less than | < = less than or equal to | > greater than | > = greater than or equal to nop = .=. equal to | .!=. not equal to | . < . less than | .<=. less than or equal to | . > . greater than | .>=. greater than or equal to positions = position { , positions } multiple positions | position - position ranges position = integer numbering is from 0 upwards | $ last tquery = ( tquery ) xquery | tag xquery tag = string * | string | * string | * xquery = / tquery | // tquery | + tquery | [ tpredicate ] xquery | [ positions ] xquery | lambda tpredicate = vpredicate upredicate upredicate = & tpredicate | | tpredicate | lambda vpredicate = ( tpredicate ) | ~ tpredicate | tattribute tattribute = aquery uattribute | @ string vattribute uattribute = / @ string vattribute | vattribute vattribute = op wattribute | op ' string ' | nop wattribute | nop integer | lambda wattribute = @ string | aquery / @ string | aquery positions = integer range | $ range = - integer | - $ | lambda commapos = , | lambda op = = | ! = | < | < = | > | > = nop = .=. | .!=. | . < . | .<=. | . > . | .>=. query = string tagname | string * tagname prefix | * string tagname suffix | * any element | - chardata | ( query ) | query / query parent/child relationship | query // query deep inside | query + query union of queries | query [predicate] | query [positions] predicate = quattr has attribute | quattr op ' string ' attribute has value | quattr op " string " attribute has value | quattr op quattr attribute value comparison (lexical) | quattr nop integer attribute has value (numerical) | quattr nop quattr attribute value comparison (numerical) | ( predicate ) bracketting | predicate & predicate logical and | predicate | predicate logical or | ~ predicate logical not attribute = @ string has attribute | query / @ string child has attribute | - has textual content | query / - child has textual content quattr = query | attribute op = = equal to | != not equal to | < less than | <= less than or equal to | > greater than | >= greater than or equal to nop = .=. equal to | .!=. not equal to | .<. less than | .<=. less than or equal to | .>. greater than | .>=. greater than or equal to positions = position {, positions} multiple positions | position - position ranges position = integer numbering is from 0 upwards | $ last tquery = ( tquery ) xquery | tag xquery tag = string * | string | * string | * xquery = / tquery | // tquery | + tquery | [ tpredicate ] xquery | [ positions ] xquery | lambda tpredicate = vpredicate upredicate upredicate = & tpredicate | | tpredicate | lambda vpredicate = ( tpredicate ) | ~ tpredicate | tattribute tattribute = aquery uattribute | @ string vattribute uattribute = / @ string vattribute | vattribute vattribute = op wattribute | op ' string ' | nop wattribute | nop integer | lambda wattribute = @ string | aquery / @ string | aquery positions = simplepos commapos simplepos = integer range | $ range = - integer | - $ | lambda commapos = , simplepos commapos | lambda op = = | != | < | <= | > | >= nop = .=. | .!=. | .<. | .<=. | .>. | .>=. -} bracket :: Parser s Token a -> Parser s Token a bracket p = do symbol "(" x <- p symbol ")" return x aquery :: DFilter -> Parser s Token DFilter aquery localise = ( do symbol "//" tquery [oglobo deep] ) +++ ( do symbol "/" tquery [oglobo id] ) +++ ( do symbol "./" tquery [(localise //>>)] ) +++ ( do tquery [(localise //>>)] ) tquery :: [DFilter->DFilter] -> Parser s Token DFilter tquery [] = tquery [id] tquery (qf:cxt) = ( do q <- bracket (tquery (qf:qf:cxt)) xquery cxt q ) +++ ( do q <- xtag xquery cxt (qf q) ) +++ ( do symbol "-" return (qf (local txt)) ) xtag :: Parser s Token DFilter xtag = ( do s <- string symbol "*" return (local (tagWith (s `isPrefixOf`))) ) +++ ( do s <- string return (local (tag s)) ) +++ ( do symbol "*" s <- string return (local (tagWith (((reverse s) `isPrefixOf`) . reverse))) ) +++ ( do symbol "*" return (local elm) ) xquery :: [DFilter->DFilter] -> DFilter -> Parser s Token DFilter xquery cxt q1 = ( do symbol "/" ((do symbol "@" attr <- string return (oiffindo attr (\s->local (literal s)) ononeo `ooo` q1)) +++ tquery ((q1 //>>):cxt)) ) +++ ( do symbol "//" tquery ((\q2-> (oloco deep) q2 `ooo` local children `ooo` q1):cxt) ) +++ ( do symbol "+" q2 <- tquery cxt return (ocato [q1,q2]) ) +++ ( do symbol "[" symbol "]" xquery cxt (\xml-> concat . pam is . q1 xml) ) +++ ( do symbol "[" p <- tpredicate symbol "]" xquery cxt (q1 `owitho` p) ) +++ ( do return q1 ) tpredicate :: Parser s Token DFilter tpredicate = do p <- vpredicate f <- upredicate return (f p) upredicate :: Parser s Token (DFilter->DFilter) upredicate = ( do symbol "&" p2 <- tpredicate return (`ooo` p2) ) +++ ( do symbol "|" p2 <- tpredicate return (||>|| p2) ) +++ ( do return id ) vpredicate :: Parser s Token DFilter vpredicate = ( do bracket tpredicate ) +++ ( do symbol "~" p <- tpredicate return (local keep `owithouto` p) ) +++ ( do tattribute ) tattribute :: Parser s Token DFilter tattribute = ( do q <- aquery (local keep) uattribute q ) +++ ( do symbol "@" s <- string vattribute (local keep, local (attr s), oiffindo s) ) uattribute :: DFilter -> Parser s Token DFilter uattribute q = ( do symbol "/" symbol "@" s <- string vattribute (q, local (attr s), oiffindo s) ) +++ ( do vattribute (q, local keep, oifTxto) ) vattribute :: (DFilter, DFilter, (String->DFilter)->DFilter->DFilter) -> Parser s Token DFilter vattribute (q,a,iffn) = ( do cmp <- op quote s2 <- string quote return ((iffn (\s1->if cmp s1 s2 then okeepo else ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- op (q2,iffn2) <- wattribute return ((iffn (\s1-> iffn2 (\s2-> if cmp s1 s2 then okeepo else ononeo) ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- nop n <- number return ((iffn (\s->if cmp (read s) n then okeepo else ononeo) ononeo) `ooo` q) ) +++ ( do cmp <- nop (q2,iffn2) <- wattribute return ((iffn (\s1-> iffn2 (\s2-> if cmp (read s1) (read s2) then okeepo else ononeo) ononeo) ononeo) `ooo` q) ) +++ ( do return ((a `ooo` q))) wattribute :: Parser s Token (DFilter, (String->DFilter)->DFilter->DFilter) wattribute = ( do symbol "@" s <- string return (okeepo, oiffindo s) ) +++ ( do q <- aquery okeepo symbol "/" symbol "@" s <- string return (q, oiffindo s) ) +++ ( do q <- aquery okeepo return (q, oifTxto) ) iindex :: Parser s Token [[a]->[a]] iindex = do i <- simpleindex is <- idxcomma return (i:is) simpleindex :: Parser s Token ([a]->[a]) simpleindex = ( do n <- number r <- rrange n return r ) +++ ( do symbol "$" return (keep . last) ) rrange, numberdollar :: Integer -> Parser s Token ([a]->[a]) rrange n1 = ( do symbol "-" numberdollar n1 ) +++ ( do return (keep.(!!(fromInteger n1))) ) numberdollar n1 = ( do n2 <- number return (take (fromInteger (1+n2-n1)) . drop (fromInteger n1)) ) +++ ( do symbol "$" return (drop (fromInteger n1)) ) idxcomma :: Parser s Token [[a]->[a]] idxcomma = ( do symbol "," r <- simpleindex rs <- idxcomma return (r:rs) ) +++ ( do return [] ) op :: Parser s Token (String->String->Bool) op = ( do symbol "=" return (==) ) +++ ( do symbol "!=" return (/=) ) +++ ( do symbol "<" return (<) ) +++ ( do symbol "<=" return (<=) ) +++ ( do symbol ">" return (>) ) +++ ( do symbol ">=" return (>=) ) nop :: Parser s Token (Integer->Integer->Bool) nop = ( do symbol ".=." return (==) ) +++ ( do symbol ".!=." return (/=) ) +++ ( do symbol ".<." return (<) ) +++ ( do symbol ".<=." return (<=) ) +++ ( do symbol ".>." return (>) ) +++ ( do symbol ".>=." return (>=) )
20b3cb4ef2dfa018effa420ad87909f1cfca8f9a91c6c4f4dad79e2656a9c6d4
mbouaziz/jsx
myPervasives.ml
include LambdaJS.Prelude let (&) f x = f x let (|>) x f = f x let (@>) f g x = g (f x) module Char = struct include Char let is_alpha = function | 'a'..'z' | 'A'..'Z' -> true | _ -> false end module List = struct include List let assoc_opt x l = try Some (assoc x l) with | Not_found -> None let rec filter_map f = function | [] -> [] | h::t -> match f h with | Some x -> x::(filter_map f t) | None -> filter_map f t let rev_filter_map f l = let rec rfmap_f accu = function | [] -> accu | h::t -> match f h with | Some x -> rfmap_f (x :: accu) t | None -> rfmap_f accu t in rfmap_f [] l (* fold_left but with fold_right syntax *) let fold_leftr f l acc = let f' a x = f x a in fold_left f' acc l let fold_leftr2 f l1 l2 acc = let f' a x1 x2 = f x1 x2 a in fold_left2 f' acc l1 l2 let fold_map f acc l = let f' (acc, l) elt = let acc, elt = f acc elt in acc, (elt::l) in let acc, l = fold_left f' (acc, []) l in acc, (rev l) let fold_map_i f acc l = let f' (acc, i, l) elt = let acc, elt = f acc i elt in acc, (i+1), (elt::l) in let acc, _, l = fold_left f' (acc, 0, []) l in acc, (rev l) let rec fold_left3 : ('a -> 'b -> 'c -> 'd -> 'a) -> 'a -> 'b list -> 'c list -> 'd list -> 'a = fun f acc l1 l2 l3 -> match l1, l2, l3 with | [], [], [] -> acc | h1::t1, h2::t2, h3::t3 -> fold_left3 f (f acc h1 h2 h3) t1 t2 t3 | _ -> raise (Invalid_argument "fold_left3") product [ 1;2 ] [ A;B ] gives [ ( 1 , A ) ; ( 1 , B ) ; ( 2 , A ) ; ( 2 , B ) ] product [1;2] [A;B] gives [(1, A); (1, B); (2, A); (2, B)] *) let product list1 list2 = let rec aux l1 l2 acc = match l1, l2 with | [], _ -> acc | _::l1, [] -> aux l1 list2 acc | x::_, y::l2 -> aux l1 l2 ((x, y)::acc) in rev (aux list1 list2 []) tr_product [ 1;2 ] [ A;B ] gives [ ( 1 , A ) ; ( 2 , A ) ; ( 1 , B ) ; ( 2 , B ) ] tr_product [1;2] [A;B] gives [(1, A); (2, A); (1, B); (2, B)] *) let tr_product list1 list2 = let rec aux l1 l2 acc = match l1, l2 with | _, [] -> acc | [], _::l2 -> aux list1 l2 acc | x::l1, y::_ -> aux l1 l2 ((x, y)::acc) in rev (aux list1 list2 []);; let assoc_flip l = List.map (fun (x,y)->y,x) l end module Big_int = struct include Big_int shift_right finally returns 0 with a positive sign will be fixed in OCaml > = 3.12.1 let buggy_zero_big_int = shift_right_towards_zero_big_int (big_int_of_int 1) 1 let count_bits bi = assert (ge_big_int bi zero_big_int); let rec aux bi = if eq_big_int bi zero_big_int || eq_big_int bi buggy_zero_big_int then 0 else 1 + (aux (shift_right_towards_zero_big_int bi 1)) in aux bi let simplify_fraction (h, l) = let gcd = gcd_big_int h l in div_big_int h gcd, div_big_int l gcd let is_int_fraction (h, l) = is_int_big_int h && is_int_big_int l let int_of_fraction (h, l) = (int_of_big_int h, int_of_big_int l) end module String = struct include String let index_or_zero s c = try index s c with Not_found -> 0 let index_or_length s c = try index s c with Not_found -> length s let after s i = sub s i (length s - i) let safe_after s i = if i < 0 then s else if i >= length s then "" else after s i let left s n = sub s 0 (min n (length s)) let between s i1 i2 = sub s (i1+1) (max 0 (i2-i1-1)) let before_char s c = try sub s 0 (index s c) with Not_found -> "" let after_char s c = try after s (index s c + 1) with Not_found -> "" let between_chars s c1 c2 = try let i1 = index s c1 in let i2 = try index_from s (i1+1) c2 with Not_found -> length s in sub s (i1+1) (i2-i1-1) with _ -> "" let split2 char_sep s = try let i = index s char_sep in left s i, after s (i+1) with Not_found -> s, "" let nsplit_char char_sep s = let rec aux i = try let j = index_from s i char_sep in (sub s i (j-i))::(aux (j+1)) with | Invalid_argument _ -> [""] | Not_found -> [after s i] in if s = "" then [] else aux 0 let interline ?(sep='\n') ins = nsplit_char sep @> concat (sprintf "%c%s" sep ins) let to_array s = Array.init (length s) (fun i -> s.[i]) let of_array a = let l = Array.length a in let s = create l in for i = 0 to l - 1 do s.[i] <- a.(i) done; s let map f s = for i = 0 to length s - 1 do s.[i] <- f s.[i] done let map_copy f s = let s = copy s in map f s; s let repl_char c1 c2 s = map_copy (fun c -> if c = c1 then c2 else c) s let for_all p s = let res = ref true in iter (fun c -> if not (p c) then res := false) s; !res let pad_left c len s = let l = length s in if l >= len then s else let r = String.make len c in String.blit s 0 r (len - l) l; r module Numeric = struct let is_numeric = for_all (fun c -> c >= '0' && c <= '9') let is_zero = for_all ((=) '0') end Converts an ASCII string to a big_int First char corresponds to the 8 - lowest bits First char corresponds to the 8-lowest bits *) let to_big_int s = let rec aux i bi = if i < 0 then bi else bi |> Big_int.mult_int_big_int 256 |> Big_int.add_int_big_int (Char.code s.[i]) |> aux (i-1) in aux ((length s) - 1) Big_int.zero_big_int let of_big_int = let bi256 = Big_int.big_int_of_int 256 in let rec aux bi = if Big_int.eq_big_int bi Big_int.zero_big_int then "" else let q, r = Big_int.quomod_big_int bi bi256 in let l = Big_int.int_of_big_int r |> Char.chr |> String.make 1 in let h = aux q in l ^ h in aux end module Filename = struct include Filename let get_suffix filename = let dot_index = try String.rindex filename '.' with Not_found -> String.length filename in String.sub filename dot_index ((String.length filename) - dot_index) end module Array = struct include Array let fold_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array = fun f acc arr -> let f' (acc, lst) elt = let acc, elt = f acc elt in acc, (elt::lst) in let acc, lst = Array.fold_left f' (acc, []) arr in acc, (Array.of_list (List.rev lst)) let fold_map_i : ('a -> int -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array = fun f acc arr -> let f' (acc, i, lst) elt = let acc, elt = f acc i elt in acc, (i+1), (elt::lst) in let acc, _, lst = Array.fold_left f' (acc, 0, []) arr in acc, (Array.of_list (List.rev lst)) let fold_left_i : ('a -> int -> 'b -> 'a) -> 'a -> 'b array -> 'a = fun f acc arr -> let f' (acc, i) elt = (f acc i elt), (i + 1) in fst (Array.fold_left f' (acc, 0) arr) let fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b array -> 'c array -> 'a = fun f acc arr1 arr2 -> assert (length arr1 = length arr2); let f' (acc, i) elt1 = (f acc elt1 arr2.(i)), (i+1) in fst (Array.fold_left f' (acc, 0) arr1) let fold_leftr2 : ('a -> 'b -> 'c -> 'c) -> 'a array -> 'b array -> 'c -> 'c = fun f arr1 arr2 acc -> assert (length arr1 = length arr2); let f' (acc, i) elt1 = (f elt1 arr2.(i) acc), (i+1) in fst (Array.fold_left f' (acc, 0) arr1) let split : ('a * 'b) array -> 'a array * 'b array = fun a -> let n = length a in (init n (fun i -> fst (a.(i)))), (init n (fun i -> snd (a.(i)))) let find_map : ('a -> 'b option) -> 'a array -> 'b option = fun f a -> let l = length a in let rec aux i = if i = l then None else match f a.(i) with | Some x -> Some x | None -> aux (i+1) in aux 0 end module StringMap = Map.Make(String) module StringMmap = MultiMap.Make(String) module IdMmap = MultiMap.Make(IdOrderedType) let sprintf = Printf.sprintf let pretty_position ?(alone=true) (p, e) = let open Lexing in if alone then sprintf "File \"%s\", line %d, characters %d-%d:" p.pos_fname p.pos_lnum (p.pos_cnum - p.pos_bol) (e.pos_cnum - e.pos_bol) else sprintf "file \"%s\", line %d, characters %d-%d" p.pos_fname p.pos_lnum (p.pos_cnum - p.pos_bol) (e.pos_cnum - e.pos_bol) let warning msg = prerr_endline (sprintf "Warning: %s" msg) let run_under_backtrace f check_print = Printexc.record_backtrace true; try f () with e -> print_endline (Printexc.to_string e); if check_print() then Printexc.print_backtrace stdout; exit 1
null
https://raw.githubusercontent.com/mbouaziz/jsx/b70768890e9e2d52e189d1a96f1a73c59a572a0f/myPervasives.ml
ocaml
fold_left but with fold_right syntax
include LambdaJS.Prelude let (&) f x = f x let (|>) x f = f x let (@>) f g x = g (f x) module Char = struct include Char let is_alpha = function | 'a'..'z' | 'A'..'Z' -> true | _ -> false end module List = struct include List let assoc_opt x l = try Some (assoc x l) with | Not_found -> None let rec filter_map f = function | [] -> [] | h::t -> match f h with | Some x -> x::(filter_map f t) | None -> filter_map f t let rev_filter_map f l = let rec rfmap_f accu = function | [] -> accu | h::t -> match f h with | Some x -> rfmap_f (x :: accu) t | None -> rfmap_f accu t in rfmap_f [] l let fold_leftr f l acc = let f' a x = f x a in fold_left f' acc l let fold_leftr2 f l1 l2 acc = let f' a x1 x2 = f x1 x2 a in fold_left2 f' acc l1 l2 let fold_map f acc l = let f' (acc, l) elt = let acc, elt = f acc elt in acc, (elt::l) in let acc, l = fold_left f' (acc, []) l in acc, (rev l) let fold_map_i f acc l = let f' (acc, i, l) elt = let acc, elt = f acc i elt in acc, (i+1), (elt::l) in let acc, _, l = fold_left f' (acc, 0, []) l in acc, (rev l) let rec fold_left3 : ('a -> 'b -> 'c -> 'd -> 'a) -> 'a -> 'b list -> 'c list -> 'd list -> 'a = fun f acc l1 l2 l3 -> match l1, l2, l3 with | [], [], [] -> acc | h1::t1, h2::t2, h3::t3 -> fold_left3 f (f acc h1 h2 h3) t1 t2 t3 | _ -> raise (Invalid_argument "fold_left3") product [ 1;2 ] [ A;B ] gives [ ( 1 , A ) ; ( 1 , B ) ; ( 2 , A ) ; ( 2 , B ) ] product [1;2] [A;B] gives [(1, A); (1, B); (2, A); (2, B)] *) let product list1 list2 = let rec aux l1 l2 acc = match l1, l2 with | [], _ -> acc | _::l1, [] -> aux l1 list2 acc | x::_, y::l2 -> aux l1 l2 ((x, y)::acc) in rev (aux list1 list2 []) tr_product [ 1;2 ] [ A;B ] gives [ ( 1 , A ) ; ( 2 , A ) ; ( 1 , B ) ; ( 2 , B ) ] tr_product [1;2] [A;B] gives [(1, A); (2, A); (1, B); (2, B)] *) let tr_product list1 list2 = let rec aux l1 l2 acc = match l1, l2 with | _, [] -> acc | [], _::l2 -> aux list1 l2 acc | x::l1, y::_ -> aux l1 l2 ((x, y)::acc) in rev (aux list1 list2 []);; let assoc_flip l = List.map (fun (x,y)->y,x) l end module Big_int = struct include Big_int shift_right finally returns 0 with a positive sign will be fixed in OCaml > = 3.12.1 let buggy_zero_big_int = shift_right_towards_zero_big_int (big_int_of_int 1) 1 let count_bits bi = assert (ge_big_int bi zero_big_int); let rec aux bi = if eq_big_int bi zero_big_int || eq_big_int bi buggy_zero_big_int then 0 else 1 + (aux (shift_right_towards_zero_big_int bi 1)) in aux bi let simplify_fraction (h, l) = let gcd = gcd_big_int h l in div_big_int h gcd, div_big_int l gcd let is_int_fraction (h, l) = is_int_big_int h && is_int_big_int l let int_of_fraction (h, l) = (int_of_big_int h, int_of_big_int l) end module String = struct include String let index_or_zero s c = try index s c with Not_found -> 0 let index_or_length s c = try index s c with Not_found -> length s let after s i = sub s i (length s - i) let safe_after s i = if i < 0 then s else if i >= length s then "" else after s i let left s n = sub s 0 (min n (length s)) let between s i1 i2 = sub s (i1+1) (max 0 (i2-i1-1)) let before_char s c = try sub s 0 (index s c) with Not_found -> "" let after_char s c = try after s (index s c + 1) with Not_found -> "" let between_chars s c1 c2 = try let i1 = index s c1 in let i2 = try index_from s (i1+1) c2 with Not_found -> length s in sub s (i1+1) (i2-i1-1) with _ -> "" let split2 char_sep s = try let i = index s char_sep in left s i, after s (i+1) with Not_found -> s, "" let nsplit_char char_sep s = let rec aux i = try let j = index_from s i char_sep in (sub s i (j-i))::(aux (j+1)) with | Invalid_argument _ -> [""] | Not_found -> [after s i] in if s = "" then [] else aux 0 let interline ?(sep='\n') ins = nsplit_char sep @> concat (sprintf "%c%s" sep ins) let to_array s = Array.init (length s) (fun i -> s.[i]) let of_array a = let l = Array.length a in let s = create l in for i = 0 to l - 1 do s.[i] <- a.(i) done; s let map f s = for i = 0 to length s - 1 do s.[i] <- f s.[i] done let map_copy f s = let s = copy s in map f s; s let repl_char c1 c2 s = map_copy (fun c -> if c = c1 then c2 else c) s let for_all p s = let res = ref true in iter (fun c -> if not (p c) then res := false) s; !res let pad_left c len s = let l = length s in if l >= len then s else let r = String.make len c in String.blit s 0 r (len - l) l; r module Numeric = struct let is_numeric = for_all (fun c -> c >= '0' && c <= '9') let is_zero = for_all ((=) '0') end Converts an ASCII string to a big_int First char corresponds to the 8 - lowest bits First char corresponds to the 8-lowest bits *) let to_big_int s = let rec aux i bi = if i < 0 then bi else bi |> Big_int.mult_int_big_int 256 |> Big_int.add_int_big_int (Char.code s.[i]) |> aux (i-1) in aux ((length s) - 1) Big_int.zero_big_int let of_big_int = let bi256 = Big_int.big_int_of_int 256 in let rec aux bi = if Big_int.eq_big_int bi Big_int.zero_big_int then "" else let q, r = Big_int.quomod_big_int bi bi256 in let l = Big_int.int_of_big_int r |> Char.chr |> String.make 1 in let h = aux q in l ^ h in aux end module Filename = struct include Filename let get_suffix filename = let dot_index = try String.rindex filename '.' with Not_found -> String.length filename in String.sub filename dot_index ((String.length filename) - dot_index) end module Array = struct include Array let fold_map : ('a -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array = fun f acc arr -> let f' (acc, lst) elt = let acc, elt = f acc elt in acc, (elt::lst) in let acc, lst = Array.fold_left f' (acc, []) arr in acc, (Array.of_list (List.rev lst)) let fold_map_i : ('a -> int -> 'b -> 'a * 'c) -> 'a -> 'b array -> 'a * 'c array = fun f acc arr -> let f' (acc, i, lst) elt = let acc, elt = f acc i elt in acc, (i+1), (elt::lst) in let acc, _, lst = Array.fold_left f' (acc, 0, []) arr in acc, (Array.of_list (List.rev lst)) let fold_left_i : ('a -> int -> 'b -> 'a) -> 'a -> 'b array -> 'a = fun f acc arr -> let f' (acc, i) elt = (f acc i elt), (i + 1) in fst (Array.fold_left f' (acc, 0) arr) let fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b array -> 'c array -> 'a = fun f acc arr1 arr2 -> assert (length arr1 = length arr2); let f' (acc, i) elt1 = (f acc elt1 arr2.(i)), (i+1) in fst (Array.fold_left f' (acc, 0) arr1) let fold_leftr2 : ('a -> 'b -> 'c -> 'c) -> 'a array -> 'b array -> 'c -> 'c = fun f arr1 arr2 acc -> assert (length arr1 = length arr2); let f' (acc, i) elt1 = (f elt1 arr2.(i) acc), (i+1) in fst (Array.fold_left f' (acc, 0) arr1) let split : ('a * 'b) array -> 'a array * 'b array = fun a -> let n = length a in (init n (fun i -> fst (a.(i)))), (init n (fun i -> snd (a.(i)))) let find_map : ('a -> 'b option) -> 'a array -> 'b option = fun f a -> let l = length a in let rec aux i = if i = l then None else match f a.(i) with | Some x -> Some x | None -> aux (i+1) in aux 0 end module StringMap = Map.Make(String) module StringMmap = MultiMap.Make(String) module IdMmap = MultiMap.Make(IdOrderedType) let sprintf = Printf.sprintf let pretty_position ?(alone=true) (p, e) = let open Lexing in if alone then sprintf "File \"%s\", line %d, characters %d-%d:" p.pos_fname p.pos_lnum (p.pos_cnum - p.pos_bol) (e.pos_cnum - e.pos_bol) else sprintf "file \"%s\", line %d, characters %d-%d" p.pos_fname p.pos_lnum (p.pos_cnum - p.pos_bol) (e.pos_cnum - e.pos_bol) let warning msg = prerr_endline (sprintf "Warning: %s" msg) let run_under_backtrace f check_print = Printexc.record_backtrace true; try f () with e -> print_endline (Printexc.to_string e); if check_print() then Printexc.print_backtrace stdout; exit 1
80d3ce5dc4de547576c78a6e9abe3fbf621e0fb9f2d992a02e5ed65e024fbeef
jahfer/othello
server.clj
(ns plaintext.server (:use [org.httpkit.server :only [run-server]]) (:require [clojure.java.io :as io] [compojure.core :refer [ANY GET PUT POST DELETE defroutes]] [compojure.route :refer [resources]] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.json :refer [wrap-json-response]] [onelog.core :as log] [environ.core :refer [env]] [ring.adapter.jetty :refer [run-jetty]] [taoensso.sente :as sente] [taoensso.sente.server-adapters.http-kit :refer (sente-web-server-adapter)] [plaintext.documents :as doc] [othello.store :as store]) (:gen-class)) (let [{:keys [ch-recv send-fn ajax-post-fn ajax-get-or-ws-handshake-fn connected-uids]} (sente/make-channel-socket! sente-web-server-adapter {})] (def ring-ajax-post ajax-post-fn) (def ring-ajax-get-or-ws-handshake ajax-get-or-ws-handshake-fn) (def ch-chsk ch-recv) (def chsk-send! send-fn) (def connected-uids connected-uids)) (defn broadcast! [event data] (doseq [uid (:any @connected-uids)] (chsk-send! uid [event data]))) (defn event-msg-handler [{:as ev-msg :keys [id ?data]}] (when (= id :document/some-id) (let [inserted (doc/insert! ?data)] (broadcast! :editor/operation inserted)))) (defroutes routes (GET "/chsk" req (ring-ajax-get-or-ws-handshake req)) (POST "/chsk" req (ring-ajax-post req)) (GET "/document.json" [] {:status 200 :body (let [{:keys [last-id operations]} (doc/serialize)] {:last-id last-id :initial-text (store/as-string operations)})}) (GET "/" [] {:status 200 :headers {"Content-Type" "text/html; charset=utf-8"} :body (io/input-stream (io/resource "public/index.html"))}) (resources "/")) (defonce system (atom {})) (def http-handler (-> routes (wrap-defaults site-defaults) wrap-json-response ring.middleware.keyword-params/wrap-keyword-params ring.middleware.params/wrap-params)) (defn start! [handler & port] (let [port (Integer. (or port (env :port) 8080))] (sente/start-server-chsk-router! ch-chsk event-msg-handler) (swap! system assoc :server (run-server handler {:port port :join? false})))) (defn stop! [] (let [server (get @system :server)] (server))) (defn reset-state! [] (doc/init) (broadcast! :browser/refresh true)) (defn -main [& [port]] (start! http-handler port))
null
https://raw.githubusercontent.com/jahfer/othello/443fc3aae65a6d7ebd8f5943279f029a091edf4c/examples/plaintext/src/clj/plaintext/server.clj
clojure
(ns plaintext.server (:use [org.httpkit.server :only [run-server]]) (:require [clojure.java.io :as io] [compojure.core :refer [ANY GET PUT POST DELETE defroutes]] [compojure.route :refer [resources]] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.json :refer [wrap-json-response]] [onelog.core :as log] [environ.core :refer [env]] [ring.adapter.jetty :refer [run-jetty]] [taoensso.sente :as sente] [taoensso.sente.server-adapters.http-kit :refer (sente-web-server-adapter)] [plaintext.documents :as doc] [othello.store :as store]) (:gen-class)) (let [{:keys [ch-recv send-fn ajax-post-fn ajax-get-or-ws-handshake-fn connected-uids]} (sente/make-channel-socket! sente-web-server-adapter {})] (def ring-ajax-post ajax-post-fn) (def ring-ajax-get-or-ws-handshake ajax-get-or-ws-handshake-fn) (def ch-chsk ch-recv) (def chsk-send! send-fn) (def connected-uids connected-uids)) (defn broadcast! [event data] (doseq [uid (:any @connected-uids)] (chsk-send! uid [event data]))) (defn event-msg-handler [{:as ev-msg :keys [id ?data]}] (when (= id :document/some-id) (let [inserted (doc/insert! ?data)] (broadcast! :editor/operation inserted)))) (defroutes routes (GET "/chsk" req (ring-ajax-get-or-ws-handshake req)) (POST "/chsk" req (ring-ajax-post req)) (GET "/document.json" [] {:status 200 :body (let [{:keys [last-id operations]} (doc/serialize)] {:last-id last-id :initial-text (store/as-string operations)})}) (GET "/" [] {:status 200 :headers {"Content-Type" "text/html; charset=utf-8"} :body (io/input-stream (io/resource "public/index.html"))}) (resources "/")) (defonce system (atom {})) (def http-handler (-> routes (wrap-defaults site-defaults) wrap-json-response ring.middleware.keyword-params/wrap-keyword-params ring.middleware.params/wrap-params)) (defn start! [handler & port] (let [port (Integer. (or port (env :port) 8080))] (sente/start-server-chsk-router! ch-chsk event-msg-handler) (swap! system assoc :server (run-server handler {:port port :join? false})))) (defn stop! [] (let [server (get @system :server)] (server))) (defn reset-state! [] (doc/init) (broadcast! :browser/refresh true)) (defn -main [& [port]] (start! http-handler port))
65675ff5e32a24f74402ebfbd3e15172a9ebc1ae5b0d0c3d37d1bce5067ba380
gvannest/piscine_OCaml
Card.ml
module Color = struct type t = Spade | Heart | Diamond | Club let all = [Spade ; Heart ; Diamond ; Club] let toString (color:t) = match color with | Spade -> "S" | Heart -> "H" | Diamond -> "D" | Club -> "C" let toStringVerbose (color:t) = match color with | Spade -> "Spade" | Heart -> "Heart" | Diamond -> "Diamond" | Club -> "Club" end module Value = struct type t = T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10 | Jack | Queen | King | As let all = [T2 ; T3 ; T4 ; T5 ; T6 ; T7 ; T8 ; T9 ; T10 ; Jack ; Queen ; King ; As] let toInt (card:t) = match card with | T2 -> 1 | T3 -> 2 | T4 -> 3 | T5 -> 4 | T6 -> 5 | T7 -> 6 | T8 -> 7 | T9 -> 8 | T10 -> 9 | Jack -> 10 | Queen -> 11 | King -> 12 | As -> 13 let toString (card:t) = match card with | T2 -> "2" | T3 -> "3" | T4 -> "4" | T5 -> "5" | T6 -> "6" | T7 -> "7" | T8 -> "8" | T9 -> "9" | T10 -> "10" | Jack -> "J" | Queen -> "Q" | King -> "K" | As -> "A" let toStringVerbose (card:t) = match card with | T2 -> "2" | T3 -> "3" | T4 -> "4" | T5 -> "5" | T6 -> "6" | T7 -> "7" | T8 -> "8" | T9 -> "9" | T10 -> "10" | Jack -> "Jack" | Queen -> "Queen" | King -> "King" | As -> "As" let next (card:t) = match card with | As -> invalid_arg "Error : provided card is As. No next card." | _ -> begin let rec nextInAll (l:t list) = match l with | [] -> invalid_arg "Error: card not found" | h :: n :: t when h = card -> n | h :: t -> nextInAll t in nextInAll all end let previous (card:t) = match card with | T2 -> invalid_arg "Error : provided card is T2. No previous card." | _ -> let rec previousInAll (l:t list) = match l with | [] -> invalid_arg "Error: card not found" | h :: n :: t when n = card -> h | h :: t -> previousInAll t in previousInAll all end type t = { value : Value.t; color : Color.t; } let newCard (v:Value.t) (c:Color.t) = { value = v ; color = c } let allSpades = let rec createAllSpades (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllSpades t ((newCard h Color.Spade) :: result) in createAllSpades Value.all [] let allHearts = let rec createAllHearts (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllHearts t ((newCard h Color.Heart) :: result) in createAllHearts Value.all [] let allDiamonds = let rec createAllDiamonds (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllDiamonds t ((newCard h Color.Diamond) :: result) in createAllDiamonds Value.all [] let allClubs = let rec createAllClubs (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllClubs t ((newCard h Color.Club) :: result) in createAllClubs Value.all [] let all = allSpades @ allHearts @ allDiamonds @ allClubs let getValue (card:t) = card.value let getColor (card:t) = card.color let toString (card:t) = Printf.sprintf "%s%s" (Value.toString card.value) (Color.toString card.color) let toStringVerbose (card:t) = Printf.sprintf "Card(%s, %s)" (Value.toStringVerbose card.value) (Color.toStringVerbose card.color) let compare (c1:t) (c2:t) = (Value.toInt c1.value) - (Value.toInt c2.value) let max (c1:t) (c2:t) = if (Value.toInt c1.value) >= (Value.toInt c2.value) then c1 else c2 let min (c1:t) (c2:t) = if (Value.toInt c1.value) <= (Value.toInt c2.value) then c1 else c2 let best (cardList:t list) = match cardList with | [] -> invalid_arg "Error: list of cards passed to best is empty." | _ -> List.fold_left max (List.hd cardList) (List.tl cardList) let isOf (card:t) (color:Color.t) = card.color = color let isSpade (card:t) = card.color = Color.Spade let isHeart (card:t) = card.color = Color.Heart let isDiamond (card:t) = card.color = Color.Diamond let isClub (card:t) = card.color = Color.Club
null
https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d04/ex02/Card.ml
ocaml
module Color = struct type t = Spade | Heart | Diamond | Club let all = [Spade ; Heart ; Diamond ; Club] let toString (color:t) = match color with | Spade -> "S" | Heart -> "H" | Diamond -> "D" | Club -> "C" let toStringVerbose (color:t) = match color with | Spade -> "Spade" | Heart -> "Heart" | Diamond -> "Diamond" | Club -> "Club" end module Value = struct type t = T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10 | Jack | Queen | King | As let all = [T2 ; T3 ; T4 ; T5 ; T6 ; T7 ; T8 ; T9 ; T10 ; Jack ; Queen ; King ; As] let toInt (card:t) = match card with | T2 -> 1 | T3 -> 2 | T4 -> 3 | T5 -> 4 | T6 -> 5 | T7 -> 6 | T8 -> 7 | T9 -> 8 | T10 -> 9 | Jack -> 10 | Queen -> 11 | King -> 12 | As -> 13 let toString (card:t) = match card with | T2 -> "2" | T3 -> "3" | T4 -> "4" | T5 -> "5" | T6 -> "6" | T7 -> "7" | T8 -> "8" | T9 -> "9" | T10 -> "10" | Jack -> "J" | Queen -> "Q" | King -> "K" | As -> "A" let toStringVerbose (card:t) = match card with | T2 -> "2" | T3 -> "3" | T4 -> "4" | T5 -> "5" | T6 -> "6" | T7 -> "7" | T8 -> "8" | T9 -> "9" | T10 -> "10" | Jack -> "Jack" | Queen -> "Queen" | King -> "King" | As -> "As" let next (card:t) = match card with | As -> invalid_arg "Error : provided card is As. No next card." | _ -> begin let rec nextInAll (l:t list) = match l with | [] -> invalid_arg "Error: card not found" | h :: n :: t when h = card -> n | h :: t -> nextInAll t in nextInAll all end let previous (card:t) = match card with | T2 -> invalid_arg "Error : provided card is T2. No previous card." | _ -> let rec previousInAll (l:t list) = match l with | [] -> invalid_arg "Error: card not found" | h :: n :: t when n = card -> h | h :: t -> previousInAll t in previousInAll all end type t = { value : Value.t; color : Color.t; } let newCard (v:Value.t) (c:Color.t) = { value = v ; color = c } let allSpades = let rec createAllSpades (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllSpades t ((newCard h Color.Spade) :: result) in createAllSpades Value.all [] let allHearts = let rec createAllHearts (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllHearts t ((newCard h Color.Heart) :: result) in createAllHearts Value.all [] let allDiamonds = let rec createAllDiamonds (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllDiamonds t ((newCard h Color.Diamond) :: result) in createAllDiamonds Value.all [] let allClubs = let rec createAllClubs (valueList:Value.t list) (result:t list) = match valueList with | [] -> List.rev result | h :: t -> createAllClubs t ((newCard h Color.Club) :: result) in createAllClubs Value.all [] let all = allSpades @ allHearts @ allDiamonds @ allClubs let getValue (card:t) = card.value let getColor (card:t) = card.color let toString (card:t) = Printf.sprintf "%s%s" (Value.toString card.value) (Color.toString card.color) let toStringVerbose (card:t) = Printf.sprintf "Card(%s, %s)" (Value.toStringVerbose card.value) (Color.toStringVerbose card.color) let compare (c1:t) (c2:t) = (Value.toInt c1.value) - (Value.toInt c2.value) let max (c1:t) (c2:t) = if (Value.toInt c1.value) >= (Value.toInt c2.value) then c1 else c2 let min (c1:t) (c2:t) = if (Value.toInt c1.value) <= (Value.toInt c2.value) then c1 else c2 let best (cardList:t list) = match cardList with | [] -> invalid_arg "Error: list of cards passed to best is empty." | _ -> List.fold_left max (List.hd cardList) (List.tl cardList) let isOf (card:t) (color:Color.t) = card.color = color let isSpade (card:t) = card.color = Color.Spade let isHeart (card:t) = card.color = Color.Heart let isDiamond (card:t) = card.color = Color.Diamond let isClub (card:t) = card.color = Color.Club
e54c5a2f06174483edd8ea6e52362bd6014e2b24d229fe3c10330e0ba23dfb94
tweag/inline-java
Unsafe.hs
# LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # | Low - level bindings to the Java Native Interface ( JNI ) . -- -- Read the -- < JNI spec> -- for authoritative documentation as to what each of the functions in -- this module does. The names of the bindings in this module were chosen to match the names of the functions in the JNI spec . -- All bindings in this module access the JNI via a thread - local variable of -- type @JNIEnv *@. If the current OS thread has not yet been "attached" to the JVM , it needs to be attached . See ' JNI.runInAttachedThread ' . -- -- The 'String' type in this module is the type of JNI strings. See " Foreign . JNI.String " . -- -- The functions in this module are considered unsafe in opposition to those in " Foreign . JNI.Safe " , which ensure that local references are not -- leaked. Reexports definitions from " Foreign . . Internal " . module Foreign.JNI.Unsafe ( module Foreign.JNI.Unsafe.Internal , NoSuchMethod(..) , getMethodID , getStaticMethodID , showException ) where import Control.Exception (Exception, bracket, catch, throwIO) import Data.List (intersperse) import Data.Singletons (sing) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Foreign.JNI.Types import Foreign.JNI.Internal (MethodSignature(..), jniMethodToJavaSignature) import qualified Foreign.JNI.String as JNI import qualified Foreign.JNI.Unsafe.Internal as Internal import Foreign.JNI.Unsafe.Internal hiding (getMethodID, getStaticMethodID) import Foreign.JNI.Unsafe.Internal.Introspection import System.IO.Unsafe (unsafePerformIO) -- | Throws when a method can't be found data NoSuchMethod = NoSuchMethod { noSuchMethodClassName :: Text , noSuchMethodName :: Text , noSuchMethodSignature :: Text , noSuchMethodOverloadings :: [Text] } deriving Exception instance Show NoSuchMethod where show exn = Text.unpack $ Text.concat $ case noSuchMethodOverloadings exn of [] -> [ "No method named ", noSuchMethodName exn , " was found in class ", noSuchMethodClassName exn , "\nWas there a mispelling?" ] sigs -> [ "Couldn't find method\n " , showMethod (noSuchMethodName exn) (noSuchMethodSignature exn) , "\nin class ", noSuchMethodClassName exn , ".\nThe available method overloadings are:\n" , Text.unlines $ map (" "<>) sigs ] where showMethod methodName sig = case jniMethodToJavaSignature sig of A Left value is a bug , but we provide the JNI signature -- which is still useful. Left _ -> methodName <> ": " <> sig Right (args, ret) -> Text.concat $ ret : " " : methodName : "(" : intersperse "," args ++ [")"] getMethodID :: JClass -- ^ A class object as returned by 'findClass' -> JNI.String -- ^ Field name -> MethodSignature -- ^ JNI signature -> IO JMethodID getMethodID cls method sig = catch (Internal.getMethodID cls method sig) (handleJVMException cls method sig) getStaticMethodID :: JClass -- ^ A class object as returned by 'findClass' -> JNI.String -- ^ Field name -> MethodSignature -- ^ JNI signature -> IO JMethodID getStaticMethodID cls method sig = catch (Internal.getStaticMethodID cls method sig) (handleJVMException cls method sig) -- | The "NoSuchMethodError" class. kexception :: JClass # NOINLINE kexception # kexception = unsafePerformIO $ bracket (findClass $ referenceTypeName $ sing @('Class "java.lang.NoSuchMethodError")) deleteLocalRef newGlobalRef | When the exception is an instance of java.lang . NoSuchMethodError , -- throw a verbose exception suggesting possible corrections. -- If it isn't, throw it as is. handleJVMException :: JClass -> JNI.String -> MethodSignature -> JVMException -> IO a handleJVMException cls method (MethodSignature sig) (JVMException e) = isInstanceOf (upcast e) kexception >>= \case True -> do noSuchMethodOverloadings <- getSignatures cls method noSuchMethodClassName <- getClassName cls throwIO $ NoSuchMethod { noSuchMethodClassName , noSuchMethodName = Text.decodeUtf8 (JNI.toByteString method) , noSuchMethodSignature = Text.decodeUtf8 (JNI.toByteString sig) , noSuchMethodOverloadings } False -> throwIO $ JVMException e
null
https://raw.githubusercontent.com/tweag/inline-java/a2daaa3cfc5cb172b6334bf5904d1a57025e709a/jni/src/common/Foreign/JNI/Unsafe.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # Read the < JNI spec> for authoritative documentation as to what each of the functions in this module does. The names of the bindings in this module were chosen to type @JNIEnv *@. If the current OS thread has not yet been "attached" to the The 'String' type in this module is the type of JNI strings. See The functions in this module are considered unsafe in opposition leaked. | Throws when a method can't be found which is still useful. ^ A class object as returned by 'findClass' ^ Field name ^ JNI signature ^ A class object as returned by 'findClass' ^ Field name ^ JNI signature | The "NoSuchMethodError" class. throw a verbose exception suggesting possible corrections. If it isn't, throw it as is.
# LANGUAGE DataKinds # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # | Low - level bindings to the Java Native Interface ( JNI ) . match the names of the functions in the JNI spec . All bindings in this module access the JNI via a thread - local variable of JVM , it needs to be attached . See ' JNI.runInAttachedThread ' . " Foreign . JNI.String " . to those in " Foreign . JNI.Safe " , which ensure that local references are not Reexports definitions from " Foreign . . Internal " . module Foreign.JNI.Unsafe ( module Foreign.JNI.Unsafe.Internal , NoSuchMethod(..) , getMethodID , getStaticMethodID , showException ) where import Control.Exception (Exception, bracket, catch, throwIO) import Data.List (intersperse) import Data.Singletons (sing) import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Foreign.JNI.Types import Foreign.JNI.Internal (MethodSignature(..), jniMethodToJavaSignature) import qualified Foreign.JNI.String as JNI import qualified Foreign.JNI.Unsafe.Internal as Internal import Foreign.JNI.Unsafe.Internal hiding (getMethodID, getStaticMethodID) import Foreign.JNI.Unsafe.Internal.Introspection import System.IO.Unsafe (unsafePerformIO) data NoSuchMethod = NoSuchMethod { noSuchMethodClassName :: Text , noSuchMethodName :: Text , noSuchMethodSignature :: Text , noSuchMethodOverloadings :: [Text] } deriving Exception instance Show NoSuchMethod where show exn = Text.unpack $ Text.concat $ case noSuchMethodOverloadings exn of [] -> [ "No method named ", noSuchMethodName exn , " was found in class ", noSuchMethodClassName exn , "\nWas there a mispelling?" ] sigs -> [ "Couldn't find method\n " , showMethod (noSuchMethodName exn) (noSuchMethodSignature exn) , "\nin class ", noSuchMethodClassName exn , ".\nThe available method overloadings are:\n" , Text.unlines $ map (" "<>) sigs ] where showMethod methodName sig = case jniMethodToJavaSignature sig of A Left value is a bug , but we provide the JNI signature Left _ -> methodName <> ": " <> sig Right (args, ret) -> Text.concat $ ret : " " : methodName : "(" : intersperse "," args ++ [")"] getMethodID -> IO JMethodID getMethodID cls method sig = catch (Internal.getMethodID cls method sig) (handleJVMException cls method sig) getStaticMethodID -> IO JMethodID getStaticMethodID cls method sig = catch (Internal.getStaticMethodID cls method sig) (handleJVMException cls method sig) kexception :: JClass # NOINLINE kexception # kexception = unsafePerformIO $ bracket (findClass $ referenceTypeName $ sing @('Class "java.lang.NoSuchMethodError")) deleteLocalRef newGlobalRef | When the exception is an instance of java.lang . NoSuchMethodError , handleJVMException :: JClass -> JNI.String -> MethodSignature -> JVMException -> IO a handleJVMException cls method (MethodSignature sig) (JVMException e) = isInstanceOf (upcast e) kexception >>= \case True -> do noSuchMethodOverloadings <- getSignatures cls method noSuchMethodClassName <- getClassName cls throwIO $ NoSuchMethod { noSuchMethodClassName , noSuchMethodName = Text.decodeUtf8 (JNI.toByteString method) , noSuchMethodSignature = Text.decodeUtf8 (JNI.toByteString sig) , noSuchMethodOverloadings } False -> throwIO $ JVMException e
e7299b9389248ebc662a9550663b241476d983dcfeddcec09acf72e22317333d
coq/coq
globEnv.mli
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \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) *) (************************************************************************) open Names open Environ open Evd open EConstr open Ltac_pretype open Evarutil (** Type of environment extended with naming and ltac interpretation data *) type t * To embed constr in glob_constr type 'a obj_interp_fun = ?loc:Loc.t -> poly:bool -> t -> Evd.evar_map -> Evardefine.type_constraint -> 'a -> unsafe_judgment * Evd.evar_map val register_constr_interp0 : ('r, 'g, 't) Genarg.genarg_type -> 'g obj_interp_fun -> unit * { 6 Pretyping name management } * The following provides a level of abstraction for the kind of environment used for type inference ( so - called pretyping ) ; in particular : - it supports that term variables can be interpreted as variables pointing to the effective expected name - it incrementally and lazily computes the renaming of rel variables used to build purely - named evar contexts environment used for type inference (so-called pretyping); in particular: - it supports that term variables can be interpreted as Ltac variables pointing to the effective expected name - it incrementally and lazily computes the renaming of rel variables used to build purely-named evar contexts *) (** Build a pretyping environment from an ltac environment *) val make : hypnaming:naming_mode -> env -> evar_map -> ltac_var_map -> t (** Export the underlying environment *) val env : t -> env val renamed_env : t -> env val lfun : t -> unbound_ltac_var_map val vars_of_env : t -> Id.Set.t (** Push to the environment, returning the declaration(s) with interpreted names *) val push_rel : hypnaming:naming_mode -> evar_map -> rel_declaration -> t -> rel_declaration * t val push_rel_context : hypnaming:naming_mode -> ?force_names:bool -> evar_map -> rel_context -> t -> rel_context * t val push_rec_types : hypnaming:naming_mode -> evar_map -> Name.t Context.binder_annot array * constr array -> t -> Name.t Context.binder_annot array * t (** Declare an evar using renaming information *) val new_evar : t -> evar_map -> ?src:Evar_kinds.t Loc.located -> ?naming:Namegen.intro_pattern_naming_expr -> constr -> evar_map * constr val new_type_evar : t -> evar_map -> src:Evar_kinds.t Loc.located -> evar_map * constr * [ hide_variable env na i d ] tells to hide the binding of [ i d ] in the ltac environment part of [ env ] and to additionally rebind it to [ i d ' ] in case [ na ] is some [ Name i d ' ] . It is useful e.g. for the dual status of [ y ] as term and binder . This is the case of [ match y return p with ... end ] which implicitly denotes [ match z as z return p with ... end ] when [ y ] is bound to a variable [ z ] and [ match t as y return p with ... end ] when [ y ] is bound to a non - variable term [ t ] . In the latter case , the binding of [ y ] to [ t ] should be hidden in [ p ] . the ltac environment part of [env] and to additionally rebind it to [id'] in case [na] is some [Name id']. It is useful e.g. for the dual status of [y] as term and binder. This is the case of [match y return p with ... end] which implicitly denotes [match z as z return p with ... end] when [y] is bound to a variable [z] and [match t as y return p with ... end] when [y] is bound to a non-variable term [t]. In the latter case, the binding of [y] to [t] should be hidden in [p]. *) val hide_variable : t -> Name.t -> Id.t -> t (** In case a variable is not bound by a term binder, look if it has an interpretation as a term in the ltac_var_map *) val interp_ltac_variable : ?loc:Loc.t -> (t -> Glob_term.glob_constr -> evar_map * unsafe_judgment) -> t -> evar_map -> Id.t -> evar_map * unsafe_judgment (** Interp an identifier as an ltac variable bound to an identifier, or as the identifier itself if not bound to an ltac variable *) val interp_ltac_id : t -> Id.t -> Id.t (** Interpreting a generic argument, typically a "ltac:(...)", taking into account the possible renaming *) val interp_glob_genarg : ?loc:Loc.t -> poly:bool -> t -> evar_map -> Evardefine.type_constraint -> Genarg.glob_generic_argument -> unsafe_judgment * evar_map
null
https://raw.githubusercontent.com/coq/coq/110921a449fcb830ec2a1cd07e3acc32319feae6/pretyping/globEnv.mli
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Type of environment extended with naming and ltac interpretation data * Build a pretyping environment from an ltac environment * Export the underlying environment * Push to the environment, returning the declaration(s) with interpreted names * Declare an evar using renaming information * In case a variable is not bound by a term binder, look if it has an interpretation as a term in the ltac_var_map * Interp an identifier as an ltac variable bound to an identifier, or as the identifier itself if not bound to an ltac variable * Interpreting a generic argument, typically a "ltac:(...)", taking into account the possible renaming
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Names open Environ open Evd open EConstr open Ltac_pretype open Evarutil type t * To embed constr in glob_constr type 'a obj_interp_fun = ?loc:Loc.t -> poly:bool -> t -> Evd.evar_map -> Evardefine.type_constraint -> 'a -> unsafe_judgment * Evd.evar_map val register_constr_interp0 : ('r, 'g, 't) Genarg.genarg_type -> 'g obj_interp_fun -> unit * { 6 Pretyping name management } * The following provides a level of abstraction for the kind of environment used for type inference ( so - called pretyping ) ; in particular : - it supports that term variables can be interpreted as variables pointing to the effective expected name - it incrementally and lazily computes the renaming of rel variables used to build purely - named evar contexts environment used for type inference (so-called pretyping); in particular: - it supports that term variables can be interpreted as Ltac variables pointing to the effective expected name - it incrementally and lazily computes the renaming of rel variables used to build purely-named evar contexts *) val make : hypnaming:naming_mode -> env -> evar_map -> ltac_var_map -> t val env : t -> env val renamed_env : t -> env val lfun : t -> unbound_ltac_var_map val vars_of_env : t -> Id.Set.t val push_rel : hypnaming:naming_mode -> evar_map -> rel_declaration -> t -> rel_declaration * t val push_rel_context : hypnaming:naming_mode -> ?force_names:bool -> evar_map -> rel_context -> t -> rel_context * t val push_rec_types : hypnaming:naming_mode -> evar_map -> Name.t Context.binder_annot array * constr array -> t -> Name.t Context.binder_annot array * t val new_evar : t -> evar_map -> ?src:Evar_kinds.t Loc.located -> ?naming:Namegen.intro_pattern_naming_expr -> constr -> evar_map * constr val new_type_evar : t -> evar_map -> src:Evar_kinds.t Loc.located -> evar_map * constr * [ hide_variable env na i d ] tells to hide the binding of [ i d ] in the ltac environment part of [ env ] and to additionally rebind it to [ i d ' ] in case [ na ] is some [ Name i d ' ] . It is useful e.g. for the dual status of [ y ] as term and binder . This is the case of [ match y return p with ... end ] which implicitly denotes [ match z as z return p with ... end ] when [ y ] is bound to a variable [ z ] and [ match t as y return p with ... end ] when [ y ] is bound to a non - variable term [ t ] . In the latter case , the binding of [ y ] to [ t ] should be hidden in [ p ] . the ltac environment part of [env] and to additionally rebind it to [id'] in case [na] is some [Name id']. It is useful e.g. for the dual status of [y] as term and binder. This is the case of [match y return p with ... end] which implicitly denotes [match z as z return p with ... end] when [y] is bound to a variable [z] and [match t as y return p with ... end] when [y] is bound to a non-variable term [t]. In the latter case, the binding of [y] to [t] should be hidden in [p]. *) val hide_variable : t -> Name.t -> Id.t -> t val interp_ltac_variable : ?loc:Loc.t -> (t -> Glob_term.glob_constr -> evar_map * unsafe_judgment) -> t -> evar_map -> Id.t -> evar_map * unsafe_judgment val interp_ltac_id : t -> Id.t -> Id.t val interp_glob_genarg : ?loc:Loc.t -> poly:bool -> t -> evar_map -> Evardefine.type_constraint -> Genarg.glob_generic_argument -> unsafe_judgment * evar_map
0b3f198f91538d49dc3d3ea9504dd9c2662cedc5f72b3a284ef71a6b4aee1a2e
carl-eastlund/mischief
stylish.rkt
#lang mischief (provide stylish-test-suite) (require rackunit (for-syntax mischief)) (module+ test (require rackunit/text-ui) (void (run-tests stylish-test-suite))) (module+ main (require rackunit/gui) (test/gui stylish-test-suite #:wait? #true)) (define-syntax (test stx) (syntax-parse stx [(_ actual:expr expected:expr) (quasisyntax/loc stx (test-case (format "~s" 'actual) (define a #false) (define e #false) #,(syntax/loc stx (check-not-exn (lambda {} (set! a actual)))) #,(syntax/loc stx (check-not-exn (lambda {} (set! e expected)))) #,(syntax/loc stx (check-equal? a e))))])) (define stylish-test-suite (test-suite "mischief/stylish" (test-suite "stylish-value->expr" (test-suite "self-quoting values" (test (stylish-value->expr 0) 0) (test (stylish-value->expr "text") "text") (test (stylish-value->expr #true) #true) (test (stylish-value->expr #\c) #\c)) (test-suite "quotable values" (test (stylish-value->expr 'sym) '(quote sym)) (test (stylish-value->expr '()) '(quote ())) (test (stylish-value->expr '(0 "text" #true #\c sym)) '(quote (0 "text" #true #\c sym))) (test (stylish-value->expr (vector-immutable '(1 2 3) '(one two three) "abc")) '(quote #((1 2 3) (one two three) "abc"))) (test (stylish-value->expr (box-immutable (vector-immutable (list 1 'two "three")))) '(quote #&#((1 two "three")))) (test (stylish-value->expr (prefab 'type 1 (box-immutable 2) (list 3))) '(quote #s(type 1 #&2 (3)))) (test (stylish-value->expr (hasheqv 1 'one 2 'two 3 'three)) '(quote #hasheqv((1 . one) (2 . two) (3 . three))))) (test-suite "unquotable values" (test (stylish-value->expr (void)) '(void)) (test (stylish-value->expr (letrec {[a a]} a)) (stylish-unprintable-expr 'undefined)) (test (stylish-value->expr eof) 'eof) (test (stylish-value->expr (srcloc "source" 1 2 3 4)) '(srcloc "source" 1 2 3 4)) (test (stylish-value->expr (list 1 (list 2 3) (srcloc (list 4 5) 6 7 8 9))) '(list 1 (quote (2 3)) (srcloc (quote (4 5)) 6 7 8 9))) (test (stylish-value->expr (vector (quote (1 2 3)) (quote (one two three)) "abc")) '(vector '(1 2 3) '(one two three) "abc")) (test (stylish-value->expr (box (vector-immutable (list 1 'two "three")))) '(box (quote #((1 two "three")))))))))
null
https://raw.githubusercontent.com/carl-eastlund/mischief/ce58c3170240f12297e2f98475f53c9514225825/mischief/tests/stylish.rkt
racket
#lang mischief (provide stylish-test-suite) (require rackunit (for-syntax mischief)) (module+ test (require rackunit/text-ui) (void (run-tests stylish-test-suite))) (module+ main (require rackunit/gui) (test/gui stylish-test-suite #:wait? #true)) (define-syntax (test stx) (syntax-parse stx [(_ actual:expr expected:expr) (quasisyntax/loc stx (test-case (format "~s" 'actual) (define a #false) (define e #false) #,(syntax/loc stx (check-not-exn (lambda {} (set! a actual)))) #,(syntax/loc stx (check-not-exn (lambda {} (set! e expected)))) #,(syntax/loc stx (check-equal? a e))))])) (define stylish-test-suite (test-suite "mischief/stylish" (test-suite "stylish-value->expr" (test-suite "self-quoting values" (test (stylish-value->expr 0) 0) (test (stylish-value->expr "text") "text") (test (stylish-value->expr #true) #true) (test (stylish-value->expr #\c) #\c)) (test-suite "quotable values" (test (stylish-value->expr 'sym) '(quote sym)) (test (stylish-value->expr '()) '(quote ())) (test (stylish-value->expr '(0 "text" #true #\c sym)) '(quote (0 "text" #true #\c sym))) (test (stylish-value->expr (vector-immutable '(1 2 3) '(one two three) "abc")) '(quote #((1 2 3) (one two three) "abc"))) (test (stylish-value->expr (box-immutable (vector-immutable (list 1 'two "three")))) '(quote #&#((1 two "three")))) (test (stylish-value->expr (prefab 'type 1 (box-immutable 2) (list 3))) '(quote #s(type 1 #&2 (3)))) (test (stylish-value->expr (hasheqv 1 'one 2 'two 3 'three)) '(quote #hasheqv((1 . one) (2 . two) (3 . three))))) (test-suite "unquotable values" (test (stylish-value->expr (void)) '(void)) (test (stylish-value->expr (letrec {[a a]} a)) (stylish-unprintable-expr 'undefined)) (test (stylish-value->expr eof) 'eof) (test (stylish-value->expr (srcloc "source" 1 2 3 4)) '(srcloc "source" 1 2 3 4)) (test (stylish-value->expr (list 1 (list 2 3) (srcloc (list 4 5) 6 7 8 9))) '(list 1 (quote (2 3)) (srcloc (quote (4 5)) 6 7 8 9))) (test (stylish-value->expr (vector (quote (1 2 3)) (quote (one two three)) "abc")) '(vector '(1 2 3) '(one two three) "abc")) (test (stylish-value->expr (box (vector-immutable (list 1 'two "three")))) '(box (quote #((1 two "three")))))))))
e0548ac0953b357435fdbc7fc9c58d4e238f89af531fe1827a26084abc5bfb1b
evincarofautumn/kitten
Enter.hs
| Module : Kitten . Enter Description : Inserting entries into the dictionary Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.Enter Description : Inserting entries into the dictionary Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} {-# LANGUAGE OverloadedStrings #-} module Kitten.Enter ( fragment , fragmentFromSource , resolveAndDesugar ) where import Control.Monad ((>=>)) import Data.Foldable (foldlM) import Data.Text (Text) import Kitten.Bracket (bracket) import Kitten.Declaration (Declaration) import Kitten.Definition (Definition) import Kitten.Dictionary (Dictionary) import Kitten.Fragment (Fragment) import Kitten.Infer (mangleInstance, typecheck) import Kitten.Informer (checkpoint, report) import Kitten.Instantiated (Instantiated(Instantiated)) import Kitten.Metadata (Metadata) import Kitten.Monad (K) import Kitten.Name import Kitten.Scope (scope) import Kitten.Term (Term) import Kitten.Tokenize (tokenize) import Kitten.TypeDefinition (TypeDefinition) import qualified Data.HashMap.Strict as HashMap import qualified Kitten.Declaration as Declaration import qualified Kitten.Definition as Definition import qualified Kitten.Desugar.Infix as Infix import qualified Kitten.Desugar.Quotations as Quotations import qualified Kitten.Dictionary as Dictionary import qualified Kitten.Entry as Entry import qualified Kitten.Entry.Category as Category import qualified Kitten.Entry.Merge as Merge import qualified Kitten.Fragment as Fragment import qualified Kitten.Metadata as Metadata import qualified Kitten.Parse as Parse import qualified Kitten.Pretty as Pretty import qualified Kitten.Quantify as Quantify import qualified Kitten.Report as Report import qualified Kitten.Resolve as Resolve import qualified Kitten.Signature as Signature import qualified Kitten.Term as Term import qualified Kitten.TypeDefinition as TypeDefinition import qualified Text.PrettyPrint as Pretty -- | Enters a program fragment into a dictionary. fragment :: Fragment () -> Dictionary -> K Dictionary fragment f -- TODO: Link constructors to parent type. = foldlMx declareType (Fragment.types f) -- We enter declarations of all traits and intrinsics. >=> foldlMx enterDeclaration (Fragment.declarations f) -- Then declare all permissions. >=> foldlMx declareWord (filter ((== Category.Permission) . Definition.category) $ Fragment.definitions f) -- With everything type-level declared, we can resolve type signatures. >=> foldlMx resolveSignature (map Declaration.name (Fragment.declarations f)) -- And declare regular words. >=> foldlMx declareWord (filter ((/= Category.Permission) . Definition.category) $ Fragment.definitions f) -- Then resolve their signatures. >=> foldlMx resolveSignature (map Definition.name (Fragment.definitions f) ++ map Declaration.name (Fragment.declarations f)) -- Add their metadata (esp. for operator metadata). >=> foldlMx addMetadata (Fragment.metadata f) -- And finally enter their definitions. >=> foldlMx defineWord (Fragment.definitions f) where foldlMx :: (Foldable f, Monad m) => (b -> a -> m b) -> f a -> b -> m b foldlMx = flip . foldlM enterDeclaration :: Dictionary -> Declaration -> K Dictionary enterDeclaration dictionary declaration = do let name = Declaration.name declaration signature = Declaration.signature declaration origin = Declaration.origin declaration case Dictionary.lookup (Instantiated name []) dictionary of -- TODO: Check signatures. Just _existing -> return dictionary Nothing -> case Declaration.category declaration of Declaration.Intrinsic -> do let entry = Entry.Word Category.Word Merge.Deny origin -- FIXME: Does a declaration ever need a parent? Nothing (Just signature) Nothing return $ Dictionary.insert (Instantiated name []) entry dictionary Declaration.Trait -> do let entry = Entry.Trait origin signature return $ Dictionary.insert (Instantiated name []) entry dictionary -- declare type, declare & define constructors declareType :: Dictionary -> TypeDefinition -> K Dictionary declareType dictionary type_ = let name = TypeDefinition.name type_ in case Dictionary.lookup (Instantiated name []) dictionary of -- Not previously declared. Nothing -> do let entry = Entry.Type (TypeDefinition.origin type_) (TypeDefinition.parameters type_) (TypeDefinition.constructors type_) return $ Dictionary.insert (Instantiated name []) entry dictionary -- Previously declared with the same parameters. Just (Entry.Type _origin parameters _ctors) | parameters == TypeDefinition.parameters type_ -> return dictionary -- Already declared or defined differently. Just{} -> error $ Pretty.render $ Pretty.hsep [ "type" , Pretty.quote name , "already declared or defined differently" ] declareWord :: Dictionary -> Definition () -> K Dictionary declareWord dictionary definition = let name = Definition.name definition signature = Definition.signature definition in case Dictionary.lookup (Instantiated name []) dictionary of -- Not previously declared or defined. Nothing -> do let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just signature) Nothing return $ Dictionary.insert (Instantiated name []) entry dictionary -- Already declared with the same signature. Just (Entry.Word _ _ originalOrigin _ mSignature _) | Definition.inferSignature definition || mSignature == Just signature -> return dictionary | otherwise -> do report $ Report.WordRedeclaration (Signature.origin signature) name signature originalOrigin mSignature return dictionary -- Already declared or defined as a trait. Just (Entry.Trait _origin traitSignature) -- TODO: Better error reporting when a non-instance matches a trait. | Definition.category definition == Category.Instance -> do let qualifier = qualifierName name resolvedSignature <- Resolve.run $ Resolve.signature dictionary qualifier $ Definition.signature definition mangledName <- mangleInstance dictionary (Definition.name definition) resolvedSignature traitSignature let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just resolvedSignature) Nothing return $ Dictionary.insert mangledName entry dictionary -- Already declared or defined with a different signature. Just{} -> error $ Pretty.render $ Pretty.hsep [ "word" , Pretty.quote name , "already declared or defined without signature or as a non-word" ] addMetadata :: Dictionary -> Metadata -> K Dictionary addMetadata dictionary0 metadata = foldlM addField dictionary0 $ HashMap.toList $ Metadata.fields metadata where QualifiedName qualified = Metadata.name metadata origin = Metadata.origin metadata qualifier = qualifierFromName qualified addField :: Dictionary -> (Unqualified, Term ()) -> K Dictionary addField dictionary (unqualified, term) = do let name = Qualified qualifier unqualified case Dictionary.lookup (Instantiated name []) dictionary of Just{} -> return dictionary -- TODO: Report duplicates or merge? Nothing -> return $ Dictionary.insert (Instantiated name []) (Entry.Metadata origin term) dictionary resolveSignature :: Dictionary -> Qualified -> K Dictionary resolveSignature dictionary name = do let qualifier = qualifierName name case Dictionary.lookup (Instantiated name []) dictionary of Just (Entry.Word category merge origin parent (Just signature) body) -> do signature' <- Resolve.run $ Resolve.signature dictionary qualifier signature let entry = Entry.Word category merge origin parent (Just signature') body return $ Dictionary.insert (Instantiated name []) entry dictionary Just (Entry.Trait origin signature) -> do signature' <- Resolve.run $ Resolve.signature dictionary qualifier signature let entry = Entry.Trait origin signature' return $ Dictionary.insert (Instantiated name []) entry dictionary _ -> return dictionary -- typecheck and define user-defined words -- desugaring of operators has to take place here defineWord :: Dictionary -> Definition () -> K Dictionary defineWord dictionary definition = do let name = Definition.name definition resolved <- resolveAndDesugar dictionary definition checkpoint let resolvedSignature = Definition.signature resolved -- Note that we use the resolved signature here. (typecheckedBody, type_) <- typecheck dictionary (if Definition.inferSignature definition then Nothing else Just resolvedSignature) $ Definition.body resolved checkpoint case Dictionary.lookup (Instantiated name []) dictionary of -- Already declared or defined as a trait. Just (Entry.Trait _origin traitSignature) | Definition.category definition == Category.Instance -> do mangledName <- mangleInstance dictionary name resolvedSignature traitSignature -- Should this use the mangled name? (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term type_ typecheckedBody let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just resolvedSignature) (Just flattenedBody) return $ Dictionary.insert mangledName entry dictionary' -- Previously declared with same signature, but not defined. Just (Entry.Word category merge origin' parent signature' Nothing) | maybe True (resolvedSignature ==) signature' -> do (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term type_ typecheckedBody let entry = Entry.Word category merge origin' parent (Just $ if Definition.inferSignature definition then Signature.Type type_ else resolvedSignature) $ Just flattenedBody return $ Dictionary.insert (Instantiated name []) entry dictionary' -- Already defined as concatenable. Just (Entry.Word category origin' parent mSignature body) | Definition.inferSignature definition || Just resolvedSignature == mSignature -> do composedBody <- case body of Just existing -> do let strippedBody = Term.stripMetadata existing return $ Term.Compose () strippedBody $ Definition.body resolved Nothing -> return $ Definition.body resolved (composed, composedType) <- typecheck dictionary (if Definition.inferSignature definition then Nothing else Just resolvedSignature) composedBody (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term composedType composed let entry = Entry.Word category merge origin' parent (if Definition.inferSignature definition Just ( Signature . Type composedType ) else mSignature) $ Just flattenedBody return $ Dictionary.insert (Instantiated name []) entry dictionary' -- Already defined, not concatenable. Just (Entry.Word _ Merge.Deny originalOrigin _ (Just _sig) _) -> do report $ Report.WordRedefinition (Definition.origin definition) name originalOrigin return dictionary -- Not previously declared as word. _ -> error $ Pretty.render $ Pretty.hsep [ "defining word" , Pretty.quote name , "not previously declared" ] -- | Parses a source file into a program fragment. fragmentFromSource :: [GeneralName] ^ List of permissions granted to -> Maybe Qualified ^ Override name of -> Int -- ^ Initial source line (e.g. for REPL offset). -> FilePath -- ^ Source file path for error reporting. -> Text -- ^ Source itself. -> K (Fragment ()) ^ program fragment . fragmentFromSource mainPermissions mainName line path source = do -- Sources are lexed into a stream of tokens. tokenized <- tokenize line path source checkpoint -- The layout rule is applied to desugar indentation-based syntax, so that the -- parser can find the ends of blocks without checking the indentation of -- tokens. bracketed <- bracket path tokenized -- We then parse the token stream as a series of top-level program elements. Datatype definitions are desugared into regular definitions , so that name -- resolution can find their names. parsed <- Parse.fragment line path mainPermissions mainName bracketed checkpoint return parsed resolveAndDesugar :: Dictionary -> Definition () -> K (Definition ()) resolveAndDesugar dictionary definition = do -- Name resolution rewrites unqualified names into fully qualified names, so -- that it's evident from a name which program element it refers to. -- needs dictionary for declared names resolved <- Resolve.run $ Resolve.definition dictionary definition checkpoint -- After names have been resolved, the precedences of operators are known, so -- infix operators can be desugared into postfix syntax. -- needs dictionary for operator metadata postfix <- Infix.desugar dictionary resolved checkpoint -- In addition, now that we know which names refer to local variables, -- quotations can be rewritten into closures that explicitly capture the -- variables they use from the enclosing scope. return postfix { Definition.body = scope $ Definition.body postfix }
null
https://raw.githubusercontent.com/evincarofautumn/kitten/a5301fe24dbb9ea91974abee73ad544156ee4722/lib/Kitten/Enter.hs
haskell
# LANGUAGE OverloadedStrings # | Enters a program fragment into a dictionary. TODO: Link constructors to parent type. We enter declarations of all traits and intrinsics. Then declare all permissions. With everything type-level declared, we can resolve type signatures. And declare regular words. Then resolve their signatures. Add their metadata (esp. for operator metadata). And finally enter their definitions. TODO: Check signatures. FIXME: Does a declaration ever need a parent? declare type, declare & define constructors Not previously declared. Previously declared with the same parameters. Already declared or defined differently. Not previously declared or defined. Already declared with the same signature. Already declared or defined as a trait. TODO: Better error reporting when a non-instance matches a trait. Already declared or defined with a different signature. TODO: Report duplicates or merge? typecheck and define user-defined words desugaring of operators has to take place here Note that we use the resolved signature here. Already declared or defined as a trait. Should this use the mangled name? Previously declared with same signature, but not defined. Already defined as concatenable. Already defined, not concatenable. Not previously declared as word. | Parses a source file into a program fragment. ^ Initial source line (e.g. for REPL offset). ^ Source file path for error reporting. ^ Source itself. Sources are lexed into a stream of tokens. The layout rule is applied to desugar indentation-based syntax, so that the parser can find the ends of blocks without checking the indentation of tokens. We then parse the token stream as a series of top-level program elements. resolution can find their names. Name resolution rewrites unqualified names into fully qualified names, so that it's evident from a name which program element it refers to. needs dictionary for declared names After names have been resolved, the precedences of operators are known, so infix operators can be desugared into postfix syntax. needs dictionary for operator metadata In addition, now that we know which names refer to local variables, quotations can be rewritten into closures that explicitly capture the variables they use from the enclosing scope.
| Module : Kitten . Enter Description : Inserting entries into the dictionary Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.Enter Description : Inserting entries into the dictionary Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} module Kitten.Enter ( fragment , fragmentFromSource , resolveAndDesugar ) where import Control.Monad ((>=>)) import Data.Foldable (foldlM) import Data.Text (Text) import Kitten.Bracket (bracket) import Kitten.Declaration (Declaration) import Kitten.Definition (Definition) import Kitten.Dictionary (Dictionary) import Kitten.Fragment (Fragment) import Kitten.Infer (mangleInstance, typecheck) import Kitten.Informer (checkpoint, report) import Kitten.Instantiated (Instantiated(Instantiated)) import Kitten.Metadata (Metadata) import Kitten.Monad (K) import Kitten.Name import Kitten.Scope (scope) import Kitten.Term (Term) import Kitten.Tokenize (tokenize) import Kitten.TypeDefinition (TypeDefinition) import qualified Data.HashMap.Strict as HashMap import qualified Kitten.Declaration as Declaration import qualified Kitten.Definition as Definition import qualified Kitten.Desugar.Infix as Infix import qualified Kitten.Desugar.Quotations as Quotations import qualified Kitten.Dictionary as Dictionary import qualified Kitten.Entry as Entry import qualified Kitten.Entry.Category as Category import qualified Kitten.Entry.Merge as Merge import qualified Kitten.Fragment as Fragment import qualified Kitten.Metadata as Metadata import qualified Kitten.Parse as Parse import qualified Kitten.Pretty as Pretty import qualified Kitten.Quantify as Quantify import qualified Kitten.Report as Report import qualified Kitten.Resolve as Resolve import qualified Kitten.Signature as Signature import qualified Kitten.Term as Term import qualified Kitten.TypeDefinition as TypeDefinition import qualified Text.PrettyPrint as Pretty fragment :: Fragment () -> Dictionary -> K Dictionary fragment f = foldlMx declareType (Fragment.types f) >=> foldlMx enterDeclaration (Fragment.declarations f) >=> foldlMx declareWord (filter ((== Category.Permission) . Definition.category) $ Fragment.definitions f) >=> foldlMx resolveSignature (map Declaration.name (Fragment.declarations f)) >=> foldlMx declareWord (filter ((/= Category.Permission) . Definition.category) $ Fragment.definitions f) >=> foldlMx resolveSignature (map Definition.name (Fragment.definitions f) ++ map Declaration.name (Fragment.declarations f)) >=> foldlMx addMetadata (Fragment.metadata f) >=> foldlMx defineWord (Fragment.definitions f) where foldlMx :: (Foldable f, Monad m) => (b -> a -> m b) -> f a -> b -> m b foldlMx = flip . foldlM enterDeclaration :: Dictionary -> Declaration -> K Dictionary enterDeclaration dictionary declaration = do let name = Declaration.name declaration signature = Declaration.signature declaration origin = Declaration.origin declaration case Dictionary.lookup (Instantiated name []) dictionary of Just _existing -> return dictionary Nothing -> case Declaration.category declaration of Declaration.Intrinsic -> do let entry = Entry.Word Category.Word Merge.Deny origin Nothing (Just signature) Nothing return $ Dictionary.insert (Instantiated name []) entry dictionary Declaration.Trait -> do let entry = Entry.Trait origin signature return $ Dictionary.insert (Instantiated name []) entry dictionary declareType :: Dictionary -> TypeDefinition -> K Dictionary declareType dictionary type_ = let name = TypeDefinition.name type_ in case Dictionary.lookup (Instantiated name []) dictionary of Nothing -> do let entry = Entry.Type (TypeDefinition.origin type_) (TypeDefinition.parameters type_) (TypeDefinition.constructors type_) return $ Dictionary.insert (Instantiated name []) entry dictionary Just (Entry.Type _origin parameters _ctors) | parameters == TypeDefinition.parameters type_ -> return dictionary Just{} -> error $ Pretty.render $ Pretty.hsep [ "type" , Pretty.quote name , "already declared or defined differently" ] declareWord :: Dictionary -> Definition () -> K Dictionary declareWord dictionary definition = let name = Definition.name definition signature = Definition.signature definition in case Dictionary.lookup (Instantiated name []) dictionary of Nothing -> do let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just signature) Nothing return $ Dictionary.insert (Instantiated name []) entry dictionary Just (Entry.Word _ _ originalOrigin _ mSignature _) | Definition.inferSignature definition || mSignature == Just signature -> return dictionary | otherwise -> do report $ Report.WordRedeclaration (Signature.origin signature) name signature originalOrigin mSignature return dictionary Just (Entry.Trait _origin traitSignature) | Definition.category definition == Category.Instance -> do let qualifier = qualifierName name resolvedSignature <- Resolve.run $ Resolve.signature dictionary qualifier $ Definition.signature definition mangledName <- mangleInstance dictionary (Definition.name definition) resolvedSignature traitSignature let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just resolvedSignature) Nothing return $ Dictionary.insert mangledName entry dictionary Just{} -> error $ Pretty.render $ Pretty.hsep [ "word" , Pretty.quote name , "already declared or defined without signature or as a non-word" ] addMetadata :: Dictionary -> Metadata -> K Dictionary addMetadata dictionary0 metadata = foldlM addField dictionary0 $ HashMap.toList $ Metadata.fields metadata where QualifiedName qualified = Metadata.name metadata origin = Metadata.origin metadata qualifier = qualifierFromName qualified addField :: Dictionary -> (Unqualified, Term ()) -> K Dictionary addField dictionary (unqualified, term) = do let name = Qualified qualifier unqualified case Dictionary.lookup (Instantiated name []) dictionary of Nothing -> return $ Dictionary.insert (Instantiated name []) (Entry.Metadata origin term) dictionary resolveSignature :: Dictionary -> Qualified -> K Dictionary resolveSignature dictionary name = do let qualifier = qualifierName name case Dictionary.lookup (Instantiated name []) dictionary of Just (Entry.Word category merge origin parent (Just signature) body) -> do signature' <- Resolve.run $ Resolve.signature dictionary qualifier signature let entry = Entry.Word category merge origin parent (Just signature') body return $ Dictionary.insert (Instantiated name []) entry dictionary Just (Entry.Trait origin signature) -> do signature' <- Resolve.run $ Resolve.signature dictionary qualifier signature let entry = Entry.Trait origin signature' return $ Dictionary.insert (Instantiated name []) entry dictionary _ -> return dictionary defineWord :: Dictionary -> Definition () -> K Dictionary defineWord dictionary definition = do let name = Definition.name definition resolved <- resolveAndDesugar dictionary definition checkpoint let resolvedSignature = Definition.signature resolved (typecheckedBody, type_) <- typecheck dictionary (if Definition.inferSignature definition then Nothing else Just resolvedSignature) $ Definition.body resolved checkpoint case Dictionary.lookup (Instantiated name []) dictionary of Just (Entry.Trait _origin traitSignature) | Definition.category definition == Category.Instance -> do mangledName <- mangleInstance dictionary name resolvedSignature traitSignature (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term type_ typecheckedBody let entry = Entry.Word (Definition.category definition) (Definition.merge definition) (Definition.origin definition) (Definition.parent definition) (Just resolvedSignature) (Just flattenedBody) return $ Dictionary.insert mangledName entry dictionary' Just (Entry.Word category merge origin' parent signature' Nothing) | maybe True (resolvedSignature ==) signature' -> do (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term type_ typecheckedBody let entry = Entry.Word category merge origin' parent (Just $ if Definition.inferSignature definition then Signature.Type type_ else resolvedSignature) $ Just flattenedBody return $ Dictionary.insert (Instantiated name []) entry dictionary' Just (Entry.Word category origin' parent mSignature body) | Definition.inferSignature definition || Just resolvedSignature == mSignature -> do composedBody <- case body of Just existing -> do let strippedBody = Term.stripMetadata existing return $ Term.Compose () strippedBody $ Definition.body resolved Nothing -> return $ Definition.body resolved (composed, composedType) <- typecheck dictionary (if Definition.inferSignature definition then Nothing else Just resolvedSignature) composedBody (flattenedBody, dictionary') <- Quotations.desugar dictionary (qualifierFromName name) $ Quantify.term composedType composed let entry = Entry.Word category merge origin' parent (if Definition.inferSignature definition Just ( Signature . Type composedType ) else mSignature) $ Just flattenedBody return $ Dictionary.insert (Instantiated name []) entry dictionary' Just (Entry.Word _ Merge.Deny originalOrigin _ (Just _sig) _) -> do report $ Report.WordRedefinition (Definition.origin definition) name originalOrigin return dictionary _ -> error $ Pretty.render $ Pretty.hsep [ "defining word" , Pretty.quote name , "not previously declared" ] fragmentFromSource :: [GeneralName] ^ List of permissions granted to -> Maybe Qualified ^ Override name of -> Int -> FilePath -> Text -> K (Fragment ()) ^ program fragment . fragmentFromSource mainPermissions mainName line path source = do tokenized <- tokenize line path source checkpoint bracketed <- bracket path tokenized Datatype definitions are desugared into regular definitions , so that name parsed <- Parse.fragment line path mainPermissions mainName bracketed checkpoint return parsed resolveAndDesugar :: Dictionary -> Definition () -> K (Definition ()) resolveAndDesugar dictionary definition = do resolved <- Resolve.run $ Resolve.definition dictionary definition checkpoint postfix <- Infix.desugar dictionary resolved checkpoint return postfix { Definition.body = scope $ Definition.body postfix }
02a6331ce30096dbba348cc2935a534f2150997124228b7a5d61cd9d441f031f
robstewart57/rdf4h
OWL.hs
# LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -Wno - missing - signatures # module Data.RDF.Vocabulary.OWL where import qualified Data.RDF.Namespace (mkPrefixedNS) import qualified Data.RDF.Types (unode) import Data.RDF.Vocabulary.Generator.VocabularyGenerator (genVocabulary) import qualified Data.Text (pack) $(genVocabulary "resources/owl.ttl")
null
https://raw.githubusercontent.com/robstewart57/rdf4h/22538a916ec35ad1c46f9946ca66efed24d95c75/src/Data/RDF/Vocabulary/OWL.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -Wno - missing - signatures # module Data.RDF.Vocabulary.OWL where import qualified Data.RDF.Namespace (mkPrefixedNS) import qualified Data.RDF.Types (unode) import Data.RDF.Vocabulary.Generator.VocabularyGenerator (genVocabulary) import qualified Data.Text (pack) $(genVocabulary "resources/owl.ttl")
5c31a032d90059883be31a8a128297f0a5a4eb7487cc5a46ea1e8122e04b3673
mariari/Misc-Lisp-Scripts
sort.lisp
(ql:quickload 'trivia) (use-package 'trivia) (defun heap-sort (a &optional (func #'<) (count (length a))) "Heap sort, pass a function (#'< or #'>) to sort the final array default is max at end" (macrolet ((ref (i) `(aref a ,i)) (swap (i j) `(rotatef (ref ,i) (ref ,j))) (ref< (i j) `(funcall func (ref ,i) (ref ,j)))) (labels ((sift (root count) (let ((cl (+ (* 2 root) 1)) (cr (+ (* 2 root) 2))) (when (< cl count) (let ((c (if (and (< cr count) (ref< cl cr)) cr cl))) (when (ref< root c) (swap root c) (sift c count))))))) (loop for start from (1- (floor count 2)) downto 0 do (sift start count)) (loop for end from (1- count) downto 1 do (swap 0 end) (sift 0 end)))) a) (defun merge-sort (sequence &optional (f #'<)) "Does not have Side effects" (let ((len (length sequence))) (if (= len 1) sequence (let ((half (truncate (/ len 2)))) (merge (type-of sequence) (merge-sort (subseq sequence 0 half)) (merge-sort (subseq sequence half)) f))))) (defun my-merge-sort (sequence &optional (f #'<)) "Does not have Side effects" (let ((len (length sequence))) (if (= len 1) (coerce sequence 'list) (let ((half (truncate (/ len 2)))) (my-merge (merge-sort (subseq sequence 0 half)) (merge-sort (subseq sequence half)) f))))) (defun my-merge (list1 list2 &optional (pred #'<) (cps #'identity)) (flet ((recur (fn1 fn2 lesser) (my-merge (funcall fn1 list1) (funcall fn2 list2) pred (lambda (x) (funcall cps (cons (car lesser) x)))))) (cond ((null list1) (funcall cps list2)) ((null list2) (funcall cps list1)) ((funcall pred (car list1) (car list2)) (recur #'cdr #'identity list1)) (t (recur #'identity #'cdr list2))))) (defun insertion-sort% (l &optional (pred '<=)) "a variation on insertion sort where elements get appended to the front instead of checking in place same O(n^2)" (labels ((insert (x ys) (match ys ((guard (cons y _) (funcall pred x y)) (cons x ys)) ((cons y rst) (cons y (insert x rst))) (nil (list x))))) (coerce (reduce #'insert l :initial-value '() :from-end t) (type-of l)))) (defun insertion-sort (seq &optional (f #'>)) "Has Side effects" (let ((key 0) (i 0)) (dotimes (j (1- (length seq))) (setf key (elt seq (1+ j))) (setf i j) (loop :while (and (> i -1) (funcall f (elt seq i) key)) :do (progn (setf (elt seq (1+ i)) (elt seq i)) (decf i))) (setf (elt seq (1+ i)) key))) seq) FROM (defun span (predicate list) (let ((tail (member-if-not predicate list))) (values (ldiff list tail) tail))) (defun less-than (x) (lambda (y) (< y x))) (defun insert (list elt) (multiple-value-bind (left right) (span (less-than elt) list) (append left (list elt) right))) (defun insertion-sort%% (list) (reduce #'insert list :initial-value nil)) ;;---------------------------------------------------- ( defun insertion - sort% ( deq & optional ( f # ' > ) ) ) (defun test (type) (flet ((test-ab (seq name) (format t "-----------------------------------------------------------------~a-----------------------------------------------------------------" name) (print "----------------------------------------------------------------MERGE-SORT----------------------------------------------------------------") (map 'list (lambda (x) (time (merge-sort x))) seq) (print "--------------------------------------------------------------INSERTION-SORT--------------------------------------------------------------") (map 'list (lambda (x) (time (insertion-sort x))) seq)) (make-seq (up-to) (coerce (loop for j from 1 to 10 collect (loop for i from 1 to up-to collect (random 1342))) type))) (let* ((a4 (make-seq 4)) (a16 (make-seq 16)) (a32 (make-seq 32)) (a64 (make-seq 64)) (a256 (make-seq 256)) (a1024 (make-seq 1024))) (test-ab a4 "a4") (test-ab a16 "a16") (test-ab a32 "a32") (test-ab a64 "a64") (test-ab a256 "a256") (test-ab a1024 "a1024") nil))) (defun test-arr () (test 'vector)) (defun test-list () (test 'list)) (defun test-worst (type) (flet ((test-ab (seq name) (format t "-----------------------------------------------------------------~a-----------------------------------------------------------------" name) (print "----------------------------------------------------------------MERGE-SORT----------------------------------------------------------------") (map 'list (lambda (x) (time (merge-sort x))) seq) (print "--------------------------------------------------------------INSERTION-SORT--------------------------------------------------------------") (map 'list (lambda (x) (time (insertion-sort x))) seq)) (make-seq (up-to) (coerce (loop for j from 1 to 3 collect (reverse (loop for i from 1 to up-to collect i))) type))) (let* ((a4 (make-seq 4)) (a16 (make-seq 16)) (a32 (make-seq 32)) (a64 (make-seq 64)) (a256 (make-seq 256)) (a1024 (make-seq 1024))) (test-ab a4 "a4") (test-ab a16 "a16") (test-ab a32 "a32") (test-ab a64 "a64") (test-ab a256 "a256") (test-ab a1024 "a1024") nil))) ;; (test-worst 'list) ;; (defun my-merge-sort (sequence) ;; (labels (merge-them)) ( if (= ( length sequence ) 1 ) ;; sequence ( let ( ( half ( truncate ( / ( length sequence ) 2 ) ) ) ) ; ; MERGE is a standard common - lisp function , which does just ;; ;; what we want. ;; (merge-them (subseq sequence 0 half)))))
null
https://raw.githubusercontent.com/mariari/Misc-Lisp-Scripts/acecadc75fcbe15e6b97e084d179aacdbbde06a8/sort.lisp
lisp
---------------------------------------------------- (test-worst 'list) (defun my-merge-sort (sequence) (labels (merge-them)) sequence ; MERGE is a standard common - lisp function , which does just ;; what we want. (merge-them (subseq sequence 0 half)))))
(ql:quickload 'trivia) (use-package 'trivia) (defun heap-sort (a &optional (func #'<) (count (length a))) "Heap sort, pass a function (#'< or #'>) to sort the final array default is max at end" (macrolet ((ref (i) `(aref a ,i)) (swap (i j) `(rotatef (ref ,i) (ref ,j))) (ref< (i j) `(funcall func (ref ,i) (ref ,j)))) (labels ((sift (root count) (let ((cl (+ (* 2 root) 1)) (cr (+ (* 2 root) 2))) (when (< cl count) (let ((c (if (and (< cr count) (ref< cl cr)) cr cl))) (when (ref< root c) (swap root c) (sift c count))))))) (loop for start from (1- (floor count 2)) downto 0 do (sift start count)) (loop for end from (1- count) downto 1 do (swap 0 end) (sift 0 end)))) a) (defun merge-sort (sequence &optional (f #'<)) "Does not have Side effects" (let ((len (length sequence))) (if (= len 1) sequence (let ((half (truncate (/ len 2)))) (merge (type-of sequence) (merge-sort (subseq sequence 0 half)) (merge-sort (subseq sequence half)) f))))) (defun my-merge-sort (sequence &optional (f #'<)) "Does not have Side effects" (let ((len (length sequence))) (if (= len 1) (coerce sequence 'list) (let ((half (truncate (/ len 2)))) (my-merge (merge-sort (subseq sequence 0 half)) (merge-sort (subseq sequence half)) f))))) (defun my-merge (list1 list2 &optional (pred #'<) (cps #'identity)) (flet ((recur (fn1 fn2 lesser) (my-merge (funcall fn1 list1) (funcall fn2 list2) pred (lambda (x) (funcall cps (cons (car lesser) x)))))) (cond ((null list1) (funcall cps list2)) ((null list2) (funcall cps list1)) ((funcall pred (car list1) (car list2)) (recur #'cdr #'identity list1)) (t (recur #'identity #'cdr list2))))) (defun insertion-sort% (l &optional (pred '<=)) "a variation on insertion sort where elements get appended to the front instead of checking in place same O(n^2)" (labels ((insert (x ys) (match ys ((guard (cons y _) (funcall pred x y)) (cons x ys)) ((cons y rst) (cons y (insert x rst))) (nil (list x))))) (coerce (reduce #'insert l :initial-value '() :from-end t) (type-of l)))) (defun insertion-sort (seq &optional (f #'>)) "Has Side effects" (let ((key 0) (i 0)) (dotimes (j (1- (length seq))) (setf key (elt seq (1+ j))) (setf i j) (loop :while (and (> i -1) (funcall f (elt seq i) key)) :do (progn (setf (elt seq (1+ i)) (elt seq i)) (decf i))) (setf (elt seq (1+ i)) key))) seq) FROM (defun span (predicate list) (let ((tail (member-if-not predicate list))) (values (ldiff list tail) tail))) (defun less-than (x) (lambda (y) (< y x))) (defun insert (list elt) (multiple-value-bind (left right) (span (less-than elt) list) (append left (list elt) right))) (defun insertion-sort%% (list) (reduce #'insert list :initial-value nil)) ( defun insertion - sort% ( deq & optional ( f # ' > ) ) ) (defun test (type) (flet ((test-ab (seq name) (format t "-----------------------------------------------------------------~a-----------------------------------------------------------------" name) (print "----------------------------------------------------------------MERGE-SORT----------------------------------------------------------------") (map 'list (lambda (x) (time (merge-sort x))) seq) (print "--------------------------------------------------------------INSERTION-SORT--------------------------------------------------------------") (map 'list (lambda (x) (time (insertion-sort x))) seq)) (make-seq (up-to) (coerce (loop for j from 1 to 10 collect (loop for i from 1 to up-to collect (random 1342))) type))) (let* ((a4 (make-seq 4)) (a16 (make-seq 16)) (a32 (make-seq 32)) (a64 (make-seq 64)) (a256 (make-seq 256)) (a1024 (make-seq 1024))) (test-ab a4 "a4") (test-ab a16 "a16") (test-ab a32 "a32") (test-ab a64 "a64") (test-ab a256 "a256") (test-ab a1024 "a1024") nil))) (defun test-arr () (test 'vector)) (defun test-list () (test 'list)) (defun test-worst (type) (flet ((test-ab (seq name) (format t "-----------------------------------------------------------------~a-----------------------------------------------------------------" name) (print "----------------------------------------------------------------MERGE-SORT----------------------------------------------------------------") (map 'list (lambda (x) (time (merge-sort x))) seq) (print "--------------------------------------------------------------INSERTION-SORT--------------------------------------------------------------") (map 'list (lambda (x) (time (insertion-sort x))) seq)) (make-seq (up-to) (coerce (loop for j from 1 to 3 collect (reverse (loop for i from 1 to up-to collect i))) type))) (let* ((a4 (make-seq 4)) (a16 (make-seq 16)) (a32 (make-seq 32)) (a64 (make-seq 64)) (a256 (make-seq 256)) (a1024 (make-seq 1024))) (test-ab a4 "a4") (test-ab a16 "a16") (test-ab a32 "a32") (test-ab a64 "a64") (test-ab a256 "a256") (test-ab a1024 "a1024") nil))) ( if (= ( length sequence ) 1 ) ( let ( ( half ( truncate ( / ( length sequence ) 2 ) ) ) )
d767bbee37c2e4f0167402a71a6224fe15b2c5a050b4c878be853b4aa6d25c81
dancrumb/clojure-brave-and-true
core_test.clj
(ns clojure-brave-and-true.core-test (:require [clojure.test :refer :all] [clojure-brave-and-true.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/dancrumb/clojure-brave-and-true/6ae47dcfc3274b6751156f54c486b0732d0e5edc/test/clojure_brave_and_true/core_test.clj
clojure
(ns clojure-brave-and-true.core-test (:require [clojure.test :refer :all] [clojure-brave-and-true.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
a93757906a0fa1a9f591ea4f6a6b4d840875f928d6df341b047267cfcc1dff16
janestreet/async_smtp
server_plugin_intf.ml
open Core open Async open Async_smtp_types module type State = T module type Start_tls = sig type session * [ upgrade_to_tls ] is called when initiating an upgrade to TLS . [ Session.greeting ] will be called to send a suitable greeting after the upgrade . [Session.greeting] will be called to send a suitable greeting after the upgrade. *) val upgrade_to_tls : log:Mail_log.t -> session -> session Smtp_monad.t end module type Auth = Auth.Server module Extension = struct type 'session t = | Start_tls of (module Start_tls with type session = 'session) | Auth of (module Auth with type session = 'session) end module type Session = sig type state type t * [ connect ] is called when a client first connects , before any messages are accepted . [ Ok session ] accepts the connection , creating a session . [ Error err ] terminates the connection , sending the reject ( or [ service_unavailable ] ) . accepted. [Ok session] accepts the connection, creating a session. [Error err] terminates the connection, sending the reject (or [service_unavailable]). *) val connect : state:state -> log:Mail_log.t -> local:Socket.Address.Inet.t -> remote:Socket.Address.Inet.t -> t Smtp_monad.t (** [greeting] to send to clients after the connection has been accepted. *) val greeting : t -> string * [ helo ] is called in response to initial handshakes ( i.e. HELO or EHLO ) . [ Ok session ] allows the SMTP session to continue . [ Error err ] terminates the connection , sending the reject ( or [ service_unavailable ] ) . [Ok session] allows the SMTP session to continue. [Error err] terminates the connection, sending the reject (or [service_unavailable]). *) val helo : state:state -> log:Mail_log.t -> t -> string -> t Smtp_monad.t (** [extensions] that are supported including the associated implementations. It is assumed that this will only change after [connect], [helo] and [Start_tls.upgrade_to_tls]. *) val extensions : state:state -> t -> t Extension.t list (** [disconnect] is called when an SMTP connection is closed. It allows the plugin to cleanup any resources associated with this session *) val disconnect : state:state -> log:Log.t -> t -> unit Smtp_monad.t end module type Envelope = sig type state type session type t val smtp_envelope_info : t -> Smtp_envelope.Info.t * [ mail_from ] is called in the event of a " MAIL FROM " SMTP command . [ Ok t ] creates an envelope that is updated by [ rcpt_to ] and finally processed by [ data ] . [ Error err ] sends the reject ( or [ service_unavailable ] ) [Ok t] creates an envelope that is updated by [rcpt_to] and finally processed by [data]. [Error err] sends the reject (or [service_unavailable]) *) val mail_from : state:state -> log:Mail_log.t -> session -> Smtp_envelope.Sender.t -> Smtp_envelope.Sender_argument.t list -> t Smtp_monad.t * [ rcpt_to ] is called in the event of a " RCPT TO " SMTP command . [ Ok t ] augments the envelope in the pipeline and passes it on to the next phase . [ Error err ] sends the reject ( or [ service_unavailable ] ) . [Ok t] augments the envelope in the pipeline and passes it on to the next phase. [Error err] sends the reject (or [service_unavailable]). *) val rcpt_to : state:state -> log:Mail_log.t -> session -> t -> Email_address.t -> t Smtp_monad.t (** [accept_data] is called when the [DATA] command is received to decide whether or not to accept the message data. *) val accept_data : state:state -> log:Mail_log.t -> session -> t -> t Smtp_monad.t * [ process ] is called when the message body has been received ( after the DATA command and [ accept_data ] ) . The returned string is used to construct the SMTP reply . [ Ok str ] results in " 250 Ok : < str > " . (after the DATA command and [accept_data]). The returned string is used to construct the SMTP reply. [Ok str] results in "250 Ok: <str>". *) val process : state:state -> log: Mail_log.t -> flows:Mail_log.Flows.t -> session -> t -> Email.t -> string Smtp_monad.t end module type S = sig module State : State module Session : Session with type state := State.t module Envelope : Envelope with type state := State.t and type session := Session.t val rpcs : unit -> State.t Rpc.Implementation.t list end * [ Simple ] provides a basic plugin implementation of [ S ] to be used as the foundation for a plugin that overrides only specific callbacks . NOTE : [ Envelope.process ] is unimplemented . It will unconditionally return back " 554 Message processing not implemented " . for a plugin that overrides only specific callbacks. NOTE: [Envelope.process] is unimplemented. It will unconditionally return back "554 Message processing not implemented". *) module Simple : sig module State : State with type t = unit module Session : sig type t = { local : Socket.Address.Inet.t ; remote : Socket.Address.Inet.t ; helo : string option ; tls : bool ; authenticated : string option } [@@deriving fields, sexp_of] val empty : t (*_ include Session with type state := 'state *) val connect : state:'state -> log:Mail_log.t -> local:Socket.Address.Inet.t -> remote:Socket.Address.Inet.t -> t Smtp_monad.t val greeting : 't -> string val helo : state:'state -> log:Mail_log.t -> t -> string -> t Smtp_monad.t val extensions : state:'state -> 't -> 't Extension.t list val disconnect : state:'state -> log:Log.t -> 't -> unit Smtp_monad.t end module Envelope : sig type t = { id : Smtp_envelope.Id.t ; sender : Smtp_envelope.Sender.t ; sender_args : Smtp_envelope.Sender_argument.t list ; recipients : Email_address.t list } [@@deriving fields, sexp_of] val smtp_envelope : t -> Email.t -> Smtp_envelope.t (*_ include Envelope with type state := 'state and type session := 'session *) val smtp_envelope_info : t -> Smtp_envelope.Info.t val mail_from : state:'state -> log:Mail_log.t -> 'session -> Smtp_envelope.Sender.t -> Smtp_envelope.Sender_argument.t list -> t Smtp_monad.t val rcpt_to : state:'state -> log:Mail_log.t -> 'session -> t -> Email_address.t -> t Smtp_monad.t val accept_data : state:'state -> log:Mail_log.t -> 'session -> t -> t Smtp_monad.t val process : state:'state -> log:Mail_log.t -> flows:Mail_log.Flows.t -> 'session -> t -> Email.t -> string Smtp_monad.t end include S with module State := State with module Session := Session and module Envelope := Envelope end = struct open Smtp_monad.Let_syntax module State = Unit module Session = struct type t = { local : Socket.Address.Inet.t ; remote : Socket.Address.Inet.t ; helo : string option ; tls : bool ; authenticated : string option } [@@deriving fields, sexp_of] let empty = let null_inet_addr = Socket.Address.Inet.create_bind_any ~port:0 in { local = null_inet_addr ; remote = null_inet_addr ; helo = None ; tls = false ; authenticated = None } ;; let connect ~state:_ ~log:_ ~local ~remote = return { empty with local; remote } let greeting _ = sprintf "%s ocaml/mailcore 0.2 %s" (Unix.gethostname ()) (Time_float.now () |> Time_float.to_string_abs ~zone:Time_float.Zone.utc) ;; let extensions ~state:_ _ = [] let helo ~state:_ ~log:_ session helo = return { session with helo = Some helo } let disconnect ~state:_ ~log:_ _ = return () end module Envelope = struct type t = { id : Smtp_envelope.Id.t ; sender : Smtp_envelope.Sender.t ; sender_args : Smtp_envelope.Sender_argument.t list ; recipients : Email_address.t list } [@@deriving sexp_of, fields] let smtp_envelope_info { id; sender; sender_args; recipients } = Smtp_envelope.Info.create ~id ~sender ~sender_args ~recipients () ;; let smtp_envelope t email = let info = smtp_envelope_info t in Smtp_envelope.create' ~info ~email ;; let mail_from ~state:_ ~log:_ _session sender sender_args = return { id = Smtp_envelope.Id.create (); sender; sender_args; recipients = [] } ;; let rcpt_to ~state:_ ~log:_ _session t recipient = return { t with recipients = t.recipients @ [ recipient ] } ;; let accept_data ~state:_ ~log:_ _session t = if List.is_empty t.recipients then Smtp_monad.reject ~here:[%here] (Smtp_reply.bad_sequence_of_commands_503 Smtp_command.Data) else return t ;; let process ~state:_ ~log:_ ~flows:_ _session _t _email = Smtp_monad.reject ~here:[%here] (Smtp_reply.transaction_failed_554 "Message processing not implemented") ;; end let rpcs () = [] end
null
https://raw.githubusercontent.com/janestreet/async_smtp/f900fa3f028725539f1336900b5631d2522fc154/src/server_plugin_intf.ml
ocaml
* [greeting] to send to clients after the connection has been accepted. * [extensions] that are supported including the associated implementations. It is assumed that this will only change after [connect], [helo] and [Start_tls.upgrade_to_tls]. * [disconnect] is called when an SMTP connection is closed. It allows the plugin to cleanup any resources associated with this session * [accept_data] is called when the [DATA] command is received to decide whether or not to accept the message data. _ include Session with type state := 'state _ include Envelope with type state := 'state and type session := 'session
open Core open Async open Async_smtp_types module type State = T module type Start_tls = sig type session * [ upgrade_to_tls ] is called when initiating an upgrade to TLS . [ Session.greeting ] will be called to send a suitable greeting after the upgrade . [Session.greeting] will be called to send a suitable greeting after the upgrade. *) val upgrade_to_tls : log:Mail_log.t -> session -> session Smtp_monad.t end module type Auth = Auth.Server module Extension = struct type 'session t = | Start_tls of (module Start_tls with type session = 'session) | Auth of (module Auth with type session = 'session) end module type Session = sig type state type t * [ connect ] is called when a client first connects , before any messages are accepted . [ Ok session ] accepts the connection , creating a session . [ Error err ] terminates the connection , sending the reject ( or [ service_unavailable ] ) . accepted. [Ok session] accepts the connection, creating a session. [Error err] terminates the connection, sending the reject (or [service_unavailable]). *) val connect : state:state -> log:Mail_log.t -> local:Socket.Address.Inet.t -> remote:Socket.Address.Inet.t -> t Smtp_monad.t val greeting : t -> string * [ helo ] is called in response to initial handshakes ( i.e. HELO or EHLO ) . [ Ok session ] allows the SMTP session to continue . [ Error err ] terminates the connection , sending the reject ( or [ service_unavailable ] ) . [Ok session] allows the SMTP session to continue. [Error err] terminates the connection, sending the reject (or [service_unavailable]). *) val helo : state:state -> log:Mail_log.t -> t -> string -> t Smtp_monad.t val extensions : state:state -> t -> t Extension.t list val disconnect : state:state -> log:Log.t -> t -> unit Smtp_monad.t end module type Envelope = sig type state type session type t val smtp_envelope_info : t -> Smtp_envelope.Info.t * [ mail_from ] is called in the event of a " MAIL FROM " SMTP command . [ Ok t ] creates an envelope that is updated by [ rcpt_to ] and finally processed by [ data ] . [ Error err ] sends the reject ( or [ service_unavailable ] ) [Ok t] creates an envelope that is updated by [rcpt_to] and finally processed by [data]. [Error err] sends the reject (or [service_unavailable]) *) val mail_from : state:state -> log:Mail_log.t -> session -> Smtp_envelope.Sender.t -> Smtp_envelope.Sender_argument.t list -> t Smtp_monad.t * [ rcpt_to ] is called in the event of a " RCPT TO " SMTP command . [ Ok t ] augments the envelope in the pipeline and passes it on to the next phase . [ Error err ] sends the reject ( or [ service_unavailable ] ) . [Ok t] augments the envelope in the pipeline and passes it on to the next phase. [Error err] sends the reject (or [service_unavailable]). *) val rcpt_to : state:state -> log:Mail_log.t -> session -> t -> Email_address.t -> t Smtp_monad.t val accept_data : state:state -> log:Mail_log.t -> session -> t -> t Smtp_monad.t * [ process ] is called when the message body has been received ( after the DATA command and [ accept_data ] ) . The returned string is used to construct the SMTP reply . [ Ok str ] results in " 250 Ok : < str > " . (after the DATA command and [accept_data]). The returned string is used to construct the SMTP reply. [Ok str] results in "250 Ok: <str>". *) val process : state:state -> log: Mail_log.t -> flows:Mail_log.Flows.t -> session -> t -> Email.t -> string Smtp_monad.t end module type S = sig module State : State module Session : Session with type state := State.t module Envelope : Envelope with type state := State.t and type session := Session.t val rpcs : unit -> State.t Rpc.Implementation.t list end * [ Simple ] provides a basic plugin implementation of [ S ] to be used as the foundation for a plugin that overrides only specific callbacks . NOTE : [ Envelope.process ] is unimplemented . It will unconditionally return back " 554 Message processing not implemented " . for a plugin that overrides only specific callbacks. NOTE: [Envelope.process] is unimplemented. It will unconditionally return back "554 Message processing not implemented". *) module Simple : sig module State : State with type t = unit module Session : sig type t = { local : Socket.Address.Inet.t ; remote : Socket.Address.Inet.t ; helo : string option ; tls : bool ; authenticated : string option } [@@deriving fields, sexp_of] val empty : t val connect : state:'state -> log:Mail_log.t -> local:Socket.Address.Inet.t -> remote:Socket.Address.Inet.t -> t Smtp_monad.t val greeting : 't -> string val helo : state:'state -> log:Mail_log.t -> t -> string -> t Smtp_monad.t val extensions : state:'state -> 't -> 't Extension.t list val disconnect : state:'state -> log:Log.t -> 't -> unit Smtp_monad.t end module Envelope : sig type t = { id : Smtp_envelope.Id.t ; sender : Smtp_envelope.Sender.t ; sender_args : Smtp_envelope.Sender_argument.t list ; recipients : Email_address.t list } [@@deriving fields, sexp_of] val smtp_envelope : t -> Email.t -> Smtp_envelope.t val smtp_envelope_info : t -> Smtp_envelope.Info.t val mail_from : state:'state -> log:Mail_log.t -> 'session -> Smtp_envelope.Sender.t -> Smtp_envelope.Sender_argument.t list -> t Smtp_monad.t val rcpt_to : state:'state -> log:Mail_log.t -> 'session -> t -> Email_address.t -> t Smtp_monad.t val accept_data : state:'state -> log:Mail_log.t -> 'session -> t -> t Smtp_monad.t val process : state:'state -> log:Mail_log.t -> flows:Mail_log.Flows.t -> 'session -> t -> Email.t -> string Smtp_monad.t end include S with module State := State with module Session := Session and module Envelope := Envelope end = struct open Smtp_monad.Let_syntax module State = Unit module Session = struct type t = { local : Socket.Address.Inet.t ; remote : Socket.Address.Inet.t ; helo : string option ; tls : bool ; authenticated : string option } [@@deriving fields, sexp_of] let empty = let null_inet_addr = Socket.Address.Inet.create_bind_any ~port:0 in { local = null_inet_addr ; remote = null_inet_addr ; helo = None ; tls = false ; authenticated = None } ;; let connect ~state:_ ~log:_ ~local ~remote = return { empty with local; remote } let greeting _ = sprintf "%s ocaml/mailcore 0.2 %s" (Unix.gethostname ()) (Time_float.now () |> Time_float.to_string_abs ~zone:Time_float.Zone.utc) ;; let extensions ~state:_ _ = [] let helo ~state:_ ~log:_ session helo = return { session with helo = Some helo } let disconnect ~state:_ ~log:_ _ = return () end module Envelope = struct type t = { id : Smtp_envelope.Id.t ; sender : Smtp_envelope.Sender.t ; sender_args : Smtp_envelope.Sender_argument.t list ; recipients : Email_address.t list } [@@deriving sexp_of, fields] let smtp_envelope_info { id; sender; sender_args; recipients } = Smtp_envelope.Info.create ~id ~sender ~sender_args ~recipients () ;; let smtp_envelope t email = let info = smtp_envelope_info t in Smtp_envelope.create' ~info ~email ;; let mail_from ~state:_ ~log:_ _session sender sender_args = return { id = Smtp_envelope.Id.create (); sender; sender_args; recipients = [] } ;; let rcpt_to ~state:_ ~log:_ _session t recipient = return { t with recipients = t.recipients @ [ recipient ] } ;; let accept_data ~state:_ ~log:_ _session t = if List.is_empty t.recipients then Smtp_monad.reject ~here:[%here] (Smtp_reply.bad_sequence_of_commands_503 Smtp_command.Data) else return t ;; let process ~state:_ ~log:_ ~flows:_ _session _t _email = Smtp_monad.reject ~here:[%here] (Smtp_reply.transaction_failed_554 "Message processing not implemented") ;; end let rpcs () = [] end
3d8cea1fea2f19556cbd8ba92d33bd837db77a77a50790791e16664e21556cf9
tomgr/libcspm
Names.hs
# LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses , TypeSynonymInstances # TypeSynonymInstances #-} | Names used by the evaluator . This is heavily inspired by GHC . module CSPM.Syntax.Names ( -- * Data Types OccName(..), UnRenamedName(..), Name(..), NameType(..), -- * Construction Helpers mkExternalName, mkInternalName, mkWiredInName, mkFreshInternalName, -- * Utility Functions isNameDataConstructor, ) where import Control.Monad.Trans import qualified Data.ByteString.Char8 as B import Data.Hashable import Data.IORef import Data.Supply import Data.Typeable import System.IO.Unsafe import Util.Annotated import qualified Util.MonadicPrettyPrint as M import Util.PrettyPrint -- | A name that occurs in the source code somewhere. data OccName = OccName B.ByteString deriving (Eq, Ord, Show, Typeable) instance PrettyPrintable OccName where prettyPrint (OccName s) = bytestring s instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m OccName where prettyPrint (OccName s) = M.bytestring s -- | A name that has not yet been renamed. Created by the parser. data UnRenamedName = UnQual OccName | Qual { unRenamedNameModuleName :: OccName, unRenamedNameMemberName :: UnRenamedName } deriving (Eq, Ord, Show, Typeable) instance PrettyPrintable UnRenamedName where prettyPrint (UnQual n) = prettyPrint n prettyPrint (Qual mn n) = prettyPrint mn <> text "::" <> prettyPrint n instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m UnRenamedName where prettyPrint (UnQual n) = M.prettyPrint n prettyPrint (Qual mn n) = M.prettyPrint mn M.<> M.text "::" M.<> M.prettyPrint n -- | A renamed name and is the exclusive type used after the renamer. Names are guaranteed to be unique , meaning that two names are equal iff they refer to the same binding instance . For example , consider the following CSPM -- code: -- -- @ f = 1 g = let f = 2 within ( f , f ) -- @ -- -- This will be renamed to: -- -- @ f0 = 1 g = let f1 = 2 within ( f1 , f1 ) -- @ -- data Name = Name { -- | The type of this name. nameType :: NameType, -- | The original occurence of this name (used for error messages). nameFullyQualified :: !UnRenamedName, -- | Where this name was defined. If this occurs in a pattern, then it -- will be equal to the location of the pattern, otherwise it will be -- equal to the location of the definition that this name binds to. nameDefinition :: !SrcSpan, -- | The unique identifier for this name. Inserted by the renamer. nameUnique :: !Int, -- | Is this name a type constructor, i.e. a datatype or a channel? nameIsConstructor :: Bool } deriving Typeable data NameType = -- | An externally visible name (like a top level definition). ExternalName -- | A name created by the renamer, but from the users' source (e.g. from -- a lambda). | InternalName -- | A built in name. | WiredInName deriving Eq instance Eq Name where n1 == n2 = nameUnique n1 == nameUnique n2 instance Hashable Name where hashWithSalt s n = s `hashWithSalt` nameUnique n hash n = nameUnique n instance Ord Name where compare n1 n2 = compare (nameUnique n1) (nameUnique n2) instance PrettyPrintable Name where prettyPrint n = prettyPrint (nameFullyQualified n) instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m Name where prettyPrint n = M.prettyPrint (nameFullyQualified n) instance Show Name where show n = show (prettyPrint n) nameUniqueSupply :: IORef (Supply Int) nameUniqueSupply = unsafePerformIO $ do s <- newNumSupply newIORef s # NOINLINE nameUniqueSupply # takeNameUnique :: MonadIO m => m Int takeNameUnique = do s <- liftIO $ atomicModifyIORef nameUniqueSupply split2 return $ supplyValue s mkExternalName :: MonadIO m => UnRenamedName -> SrcSpan -> Bool -> m Name mkExternalName o s b = do u <- takeNameUnique return $ Name ExternalName o s u b mkInternalName :: MonadIO m => UnRenamedName -> SrcSpan -> m Name mkInternalName o s = do u <- takeNameUnique return $ Name InternalName o s u False mkFreshInternalName :: MonadIO m => m Name mkFreshInternalName = do u <- takeNameUnique let s = B.pack ('i':show u) return $ Name InternalName (UnQual (OccName s)) Unknown u False mkWiredInName :: MonadIO m => UnRenamedName -> Bool -> m Name mkWiredInName o b = do u <- takeNameUnique return $ Name WiredInName o BuiltIn u b -- | Does the given Name correspond to a data type or a channel definition. isNameDataConstructor :: Name -> Bool isNameDataConstructor n = nameIsConstructor n
null
https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/CSPM/Syntax/Names.hs
haskell
* Data Types * Construction Helpers * Utility Functions | A name that occurs in the source code somewhere. | A name that has not yet been renamed. Created by the parser. | A renamed name and is the exclusive type used after the renamer. Names code: @ @ This will be renamed to: @ @ | The type of this name. | The original occurence of this name (used for error messages). | Where this name was defined. If this occurs in a pattern, then it will be equal to the location of the pattern, otherwise it will be equal to the location of the definition that this name binds to. | The unique identifier for this name. Inserted by the renamer. | Is this name a type constructor, i.e. a datatype or a channel? | An externally visible name (like a top level definition). | A name created by the renamer, but from the users' source (e.g. from a lambda). | A built in name. | Does the given Name correspond to a data type or a channel definition.
# LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses , TypeSynonymInstances # TypeSynonymInstances #-} | Names used by the evaluator . This is heavily inspired by GHC . module CSPM.Syntax.Names ( OccName(..), UnRenamedName(..), Name(..), NameType(..), mkExternalName, mkInternalName, mkWiredInName, mkFreshInternalName, isNameDataConstructor, ) where import Control.Monad.Trans import qualified Data.ByteString.Char8 as B import Data.Hashable import Data.IORef import Data.Supply import Data.Typeable import System.IO.Unsafe import Util.Annotated import qualified Util.MonadicPrettyPrint as M import Util.PrettyPrint data OccName = OccName B.ByteString deriving (Eq, Ord, Show, Typeable) instance PrettyPrintable OccName where prettyPrint (OccName s) = bytestring s instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m OccName where prettyPrint (OccName s) = M.bytestring s data UnRenamedName = UnQual OccName | Qual { unRenamedNameModuleName :: OccName, unRenamedNameMemberName :: UnRenamedName } deriving (Eq, Ord, Show, Typeable) instance PrettyPrintable UnRenamedName where prettyPrint (UnQual n) = prettyPrint n prettyPrint (Qual mn n) = prettyPrint mn <> text "::" <> prettyPrint n instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m UnRenamedName where prettyPrint (UnQual n) = M.prettyPrint n prettyPrint (Qual mn n) = M.prettyPrint mn M.<> M.text "::" M.<> M.prettyPrint n are guaranteed to be unique , meaning that two names are equal iff they refer to the same binding instance . For example , consider the following CSPM f = 1 g = let f = 2 within ( f , f ) f0 = 1 g = let f1 = 2 within ( f1 , f1 ) data Name = Name { nameType :: NameType, nameFullyQualified :: !UnRenamedName, nameDefinition :: !SrcSpan, nameUnique :: !Int, nameIsConstructor :: Bool } deriving Typeable data NameType = ExternalName | InternalName | WiredInName deriving Eq instance Eq Name where n1 == n2 = nameUnique n1 == nameUnique n2 instance Hashable Name where hashWithSalt s n = s `hashWithSalt` nameUnique n hash n = nameUnique n instance Ord Name where compare n1 n2 = compare (nameUnique n1) (nameUnique n2) instance PrettyPrintable Name where prettyPrint n = prettyPrint (nameFullyQualified n) instance (Applicative m, Monad m) => M.MonadicPrettyPrintable m Name where prettyPrint n = M.prettyPrint (nameFullyQualified n) instance Show Name where show n = show (prettyPrint n) nameUniqueSupply :: IORef (Supply Int) nameUniqueSupply = unsafePerformIO $ do s <- newNumSupply newIORef s # NOINLINE nameUniqueSupply # takeNameUnique :: MonadIO m => m Int takeNameUnique = do s <- liftIO $ atomicModifyIORef nameUniqueSupply split2 return $ supplyValue s mkExternalName :: MonadIO m => UnRenamedName -> SrcSpan -> Bool -> m Name mkExternalName o s b = do u <- takeNameUnique return $ Name ExternalName o s u b mkInternalName :: MonadIO m => UnRenamedName -> SrcSpan -> m Name mkInternalName o s = do u <- takeNameUnique return $ Name InternalName o s u False mkFreshInternalName :: MonadIO m => m Name mkFreshInternalName = do u <- takeNameUnique let s = B.pack ('i':show u) return $ Name InternalName (UnQual (OccName s)) Unknown u False mkWiredInName :: MonadIO m => UnRenamedName -> Bool -> m Name mkWiredInName o b = do u <- takeNameUnique return $ Name WiredInName o BuiltIn u b isNameDataConstructor :: Name -> Bool isNameDataConstructor n = nameIsConstructor n
faf11391ec156090d6f2eca2e8937ba81497672895024b381127fe612747fb8b
oliyh/re-graph
core.cljc
(ns re-graph.core (:require [re-frame.core :as re-frame] [re-graph.internals :as internals :refer [interceptors]] [re-graph.logging :as log] [clojure.string :as string] [clojure.spec.alpha :as s] [re-graph.spec :as spec])) ;; queries and mutations (re-frame/reg-event-fx ::mutate (interceptors ::spec/mutate) (fn [{:keys [db]} {:keys [id query variables callback] :or {id (internals/generate-id)} :as event-payload}] (let [query (str "mutation " (string/replace query #"^mutation\s?" "")) websocket-supported? (contains? (get-in db [:ws :supported-operations]) :mutate)] (cond (or (get-in db [:http :requests id]) (get-in db [:subscriptions id])) {} ;; duplicate in-flight mutation (and websocket-supported? (get-in db [:ws :ready?])) {:db (assoc-in db [:subscriptions id] {:callback callback}) ::internals/send-ws [(get-in db [:ws :connection]) {:id id :type "start" :payload {:query query :variables variables}}]} (and websocket-supported? (:ws db)) {:db (update-in db [:ws :queue] conj [::mutate event-payload])} :else {:db (assoc-in db [:http :requests id] {:callback callback}) ::internals/send-http {:url (get-in db [:http :url]) :request (get-in db [:http :impl]) :payload {:query query :variables variables} :event (assoc event-payload :id id)}})))) (defn mutate "Execute a GraphQL mutation. See ::spec/mutate for the arguments" [opts] (re-frame/dispatch [::mutate (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef mutate :args (s/cat :opts ::spec/mutate)) #?(:clj (def ^{:doc "Executes a mutation synchronously. Options are per `mutate` with an additional optional `:timeout` specified in milliseconds."} mutate-sync (partial internals/sync-wrapper mutate))) (re-frame/reg-event-fx ::query (interceptors ::spec/query) (fn [{:keys [db]} {:keys [id query variables callback legacy?] :or {id (internals/generate-id)} :as event-payload}] ;; prepend `query` if it is omitted (and not a fragment declaration) (let [query (if (re-find #"^(query|fragment)" query) query (str "query " query)) websocket-supported? (contains? (get-in db [:ws :supported-operations]) :query)] (cond (or (get-in db [:http :requests id]) (get-in db [:subscriptions id])) {} ;; duplicate in-flight query (and websocket-supported? (get-in db [:ws :ready?])) {:db (assoc-in db [:subscriptions id] {:callback callback :legacy? legacy?}) ::internals/send-ws [(get-in db [:ws :connection]) {:id id :type "start" :payload {:query query :variables variables}}]} (and websocket-supported? (:ws db)) {:db (update-in db [:ws :queue] conj [::query event-payload])} :else {:db (assoc-in db [:http :requests id] {:callback callback}) ::internals/send-http {:url (get-in db [:http :url]) :request (get-in db [:http :impl]) :payload {:query query :variables variables} :event (assoc event-payload :id id)}})))) (defn query "Execute a GraphQL query. See ::spec/query for the arguments" [opts] (re-frame/dispatch [::query (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef query :args (s/cat :opts ::spec/query)) #?(:clj (def ^{:doc "Executes a query synchronously. Options are per `query` with an additional optional `:timeout` specified in milliseconds."} query-sync (partial internals/sync-wrapper query))) (re-frame/reg-event-fx ::abort (interceptors ::spec/abort) (fn [{:keys [db]} {:keys [id]}] (merge {:db (-> db (update :subscriptions dissoc id) (update-in [:http :requests] dissoc id))} (when-let [abort-fn (get-in db [:http :requests id :abort])] {::internals/call-abort abort-fn}) ))) (defn abort "Abort a pending query or mutation. See ::spec/abort for the arguments" [opts] (re-frame/dispatch [::abort opts])) (s/fdef abort :args (s/cat :opts ::spec/abort)) ;; subscriptions (re-frame/reg-event-fx ::subscribe (interceptors ::spec/subscribe) (fn [{:keys [db]} {:keys [id query variables callback instance-id legacy?] :as event}] (cond (get-in db [:subscriptions (name id) :active?]) {} ;; duplicate subscription (get-in db [:ws :ready?]) {:db (assoc-in db [:subscriptions (name id)] {:callback callback :event [::subscribe event] :active? true :legacy? legacy?}) ::internals/send-ws [(get-in db [:ws :connection]) {:id (name id) :type "start" :payload {:query (str "subscription " (string/replace query #"^subscription\s?" "")) :variables variables}}]} (:ws db) {:db (update-in db [:ws :queue] conj [::subscribe event])} :else (log/error (str "Error creating subscription " id " on instance " instance-id ": Websocket is not enabled, subscriptions are not possible. Please check your re-graph configuration"))))) (defn subscribe "Create a GraphQL subscription. See ::spec/subscribe for the arguments" [opts] (re-frame/dispatch [::subscribe (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef subscribe :args (s/cat :opts ::spec/subscribe)) (re-frame/reg-event-fx ::unsubscribe (interceptors ::spec/unsubscribe) (fn [{:keys [db]} {:keys [id] :as event}] (if (get-in db [:ws :ready?]) {:db (update db :subscriptions dissoc (name id)) ::internals/send-ws [(get-in db [:ws :connection]) {:id (name id) :type "stop"}]} {:db (update-in db [:ws :queue] conj [::unsubscribe event])}))) (defn unsubscribe "Cancel an existing GraphQL subscription. See ::spec/unsubscribe for the arguments" [opts] (re-frame/dispatch [::unsubscribe opts])) (s/fdef unsubscribe :args (s/cat :opts ::spec/unsubscribe)) ;; re-graph lifecycle (re-frame/reg-event-fx ::init [re-frame/unwrap (internals/assert-spec ::spec/init)] (fn [{:keys [db]} {:keys [instance-id] :or {instance-id internals/default-instance-id} :as opts}] (let [{:keys [ws] :as opts} (merge opts (internals/ws-options opts) (internals/http-options opts))] (merge {:db (assoc-in db [:re-graph instance-id] opts)} (when ws {::internals/connect-ws [instance-id ws]}))))) (defn init "Initialise an instance of re-graph. See ::spec/init for the arguments" [opts] (re-frame/dispatch [::init opts])) (s/fdef init :args (s/cat :opts ::spec/init)) (re-frame/reg-event-fx ::re-init [re-frame/unwrap internals/select-instance (internals/assert-spec ::spec/re-init)] (fn [{:keys [db]} opts] (let [new-db (internals/deep-merge db opts)] (merge {:db new-db} (when (get-in new-db [:ws :ready?]) {:dispatch [::internals/connection-init opts]}))))) (defn re-init "Re-initialise an instance of re-graph. See ::spec/re-init for the arguments" [opts] (re-frame/dispatch [::re-init opts])) (s/fdef re-init :args (s/cat :opts ::spec/re-init)) (re-frame/reg-event-fx ::destroy (interceptors ::spec/destroy) (fn [{:keys [db]} {:keys [instance-id]}] (if-let [ids (not-empty (-> db :subscriptions keys))] {:dispatch-n (for [id ids] [::unsubscribe {:instance-id instance-id :id id}]) :dispatch [::destroy {:instance-id instance-id}]} (merge {:db (assoc db :destroyed? true)} (when-let [ws (get-in db [:ws :connection])] {::internals/disconnect-ws [ws]}))))) (defn destroy "Destroy an instance of re-graph. See ::spec/destroy for the arguments" [opts] (re-frame/dispatch [::destroy opts])) (s/fdef destroy :args (s/cat :opts ::spec/destroy))
null
https://raw.githubusercontent.com/oliyh/re-graph/250f2ebd0eb68752e96bd524c2ee86b1e93e0887/src/re_graph/core.cljc
clojure
queries and mutations duplicate in-flight mutation prepend `query` if it is omitted (and not a fragment declaration) duplicate in-flight query subscriptions duplicate subscription re-graph lifecycle
(ns re-graph.core (:require [re-frame.core :as re-frame] [re-graph.internals :as internals :refer [interceptors]] [re-graph.logging :as log] [clojure.string :as string] [clojure.spec.alpha :as s] [re-graph.spec :as spec])) (re-frame/reg-event-fx ::mutate (interceptors ::spec/mutate) (fn [{:keys [db]} {:keys [id query variables callback] :or {id (internals/generate-id)} :as event-payload}] (let [query (str "mutation " (string/replace query #"^mutation\s?" "")) websocket-supported? (contains? (get-in db [:ws :supported-operations]) :mutate)] (cond (or (get-in db [:http :requests id]) (get-in db [:subscriptions id])) (and websocket-supported? (get-in db [:ws :ready?])) {:db (assoc-in db [:subscriptions id] {:callback callback}) ::internals/send-ws [(get-in db [:ws :connection]) {:id id :type "start" :payload {:query query :variables variables}}]} (and websocket-supported? (:ws db)) {:db (update-in db [:ws :queue] conj [::mutate event-payload])} :else {:db (assoc-in db [:http :requests id] {:callback callback}) ::internals/send-http {:url (get-in db [:http :url]) :request (get-in db [:http :impl]) :payload {:query query :variables variables} :event (assoc event-payload :id id)}})))) (defn mutate "Execute a GraphQL mutation. See ::spec/mutate for the arguments" [opts] (re-frame/dispatch [::mutate (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef mutate :args (s/cat :opts ::spec/mutate)) #?(:clj (def ^{:doc "Executes a mutation synchronously. Options are per `mutate` with an additional optional `:timeout` specified in milliseconds."} mutate-sync (partial internals/sync-wrapper mutate))) (re-frame/reg-event-fx ::query (interceptors ::spec/query) (fn [{:keys [db]} {:keys [id query variables callback legacy?] :or {id (internals/generate-id)} :as event-payload}] (let [query (if (re-find #"^(query|fragment)" query) query (str "query " query)) websocket-supported? (contains? (get-in db [:ws :supported-operations]) :query)] (cond (or (get-in db [:http :requests id]) (get-in db [:subscriptions id])) (and websocket-supported? (get-in db [:ws :ready?])) {:db (assoc-in db [:subscriptions id] {:callback callback :legacy? legacy?}) ::internals/send-ws [(get-in db [:ws :connection]) {:id id :type "start" :payload {:query query :variables variables}}]} (and websocket-supported? (:ws db)) {:db (update-in db [:ws :queue] conj [::query event-payload])} :else {:db (assoc-in db [:http :requests id] {:callback callback}) ::internals/send-http {:url (get-in db [:http :url]) :request (get-in db [:http :impl]) :payload {:query query :variables variables} :event (assoc event-payload :id id)}})))) (defn query "Execute a GraphQL query. See ::spec/query for the arguments" [opts] (re-frame/dispatch [::query (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef query :args (s/cat :opts ::spec/query)) #?(:clj (def ^{:doc "Executes a query synchronously. Options are per `query` with an additional optional `:timeout` specified in milliseconds."} query-sync (partial internals/sync-wrapper query))) (re-frame/reg-event-fx ::abort (interceptors ::spec/abort) (fn [{:keys [db]} {:keys [id]}] (merge {:db (-> db (update :subscriptions dissoc id) (update-in [:http :requests] dissoc id))} (when-let [abort-fn (get-in db [:http :requests id :abort])] {::internals/call-abort abort-fn}) ))) (defn abort "Abort a pending query or mutation. See ::spec/abort for the arguments" [opts] (re-frame/dispatch [::abort opts])) (s/fdef abort :args (s/cat :opts ::spec/abort)) (re-frame/reg-event-fx ::subscribe (interceptors ::spec/subscribe) (fn [{:keys [db]} {:keys [id query variables callback instance-id legacy?] :as event}] (cond (get-in db [:subscriptions (name id) :active?]) (get-in db [:ws :ready?]) {:db (assoc-in db [:subscriptions (name id)] {:callback callback :event [::subscribe event] :active? true :legacy? legacy?}) ::internals/send-ws [(get-in db [:ws :connection]) {:id (name id) :type "start" :payload {:query (str "subscription " (string/replace query #"^subscription\s?" "")) :variables variables}}]} (:ws db) {:db (update-in db [:ws :queue] conj [::subscribe event])} :else (log/error (str "Error creating subscription " id " on instance " instance-id ": Websocket is not enabled, subscriptions are not possible. Please check your re-graph configuration"))))) (defn subscribe "Create a GraphQL subscription. See ::spec/subscribe for the arguments" [opts] (re-frame/dispatch [::subscribe (update opts :callback (fn [f] [::internals/callback {:callback-fn f}]))])) (s/fdef subscribe :args (s/cat :opts ::spec/subscribe)) (re-frame/reg-event-fx ::unsubscribe (interceptors ::spec/unsubscribe) (fn [{:keys [db]} {:keys [id] :as event}] (if (get-in db [:ws :ready?]) {:db (update db :subscriptions dissoc (name id)) ::internals/send-ws [(get-in db [:ws :connection]) {:id (name id) :type "stop"}]} {:db (update-in db [:ws :queue] conj [::unsubscribe event])}))) (defn unsubscribe "Cancel an existing GraphQL subscription. See ::spec/unsubscribe for the arguments" [opts] (re-frame/dispatch [::unsubscribe opts])) (s/fdef unsubscribe :args (s/cat :opts ::spec/unsubscribe)) (re-frame/reg-event-fx ::init [re-frame/unwrap (internals/assert-spec ::spec/init)] (fn [{:keys [db]} {:keys [instance-id] :or {instance-id internals/default-instance-id} :as opts}] (let [{:keys [ws] :as opts} (merge opts (internals/ws-options opts) (internals/http-options opts))] (merge {:db (assoc-in db [:re-graph instance-id] opts)} (when ws {::internals/connect-ws [instance-id ws]}))))) (defn init "Initialise an instance of re-graph. See ::spec/init for the arguments" [opts] (re-frame/dispatch [::init opts])) (s/fdef init :args (s/cat :opts ::spec/init)) (re-frame/reg-event-fx ::re-init [re-frame/unwrap internals/select-instance (internals/assert-spec ::spec/re-init)] (fn [{:keys [db]} opts] (let [new-db (internals/deep-merge db opts)] (merge {:db new-db} (when (get-in new-db [:ws :ready?]) {:dispatch [::internals/connection-init opts]}))))) (defn re-init "Re-initialise an instance of re-graph. See ::spec/re-init for the arguments" [opts] (re-frame/dispatch [::re-init opts])) (s/fdef re-init :args (s/cat :opts ::spec/re-init)) (re-frame/reg-event-fx ::destroy (interceptors ::spec/destroy) (fn [{:keys [db]} {:keys [instance-id]}] (if-let [ids (not-empty (-> db :subscriptions keys))] {:dispatch-n (for [id ids] [::unsubscribe {:instance-id instance-id :id id}]) :dispatch [::destroy {:instance-id instance-id}]} (merge {:db (assoc db :destroyed? true)} (when-let [ws (get-in db [:ws :connection])] {::internals/disconnect-ws [ws]}))))) (defn destroy "Destroy an instance of re-graph. See ::spec/destroy for the arguments" [opts] (re-frame/dispatch [::destroy opts])) (s/fdef destroy :args (s/cat :opts ::spec/destroy))
eef16b870834e2b7b3e09de8239ecd188cc00f4c39b08d4febd1677b29e2e575
footprintanalytics/footprint-web
premium_features_test.clj
(ns metabase.public-settings.premium-features-test (:require [cheshire.core :as json] [clj-http.client :as http] [clj-http.fake :as http-fake] [clojure.test :refer :all] [metabase.config :as config] [metabase.models.user :refer [User]] [metabase.public-settings :as public-settings] [metabase.public-settings.premium-features :as premium-features :refer [defenterprise defenterprise-schema]] [metabase.test :as mt] [schema.core :as s] [toucan.util.test :as tt])) (defn do-with-premium-features [features f] (let [features (set (map name features))] (testing (format "\nWith premium token features = %s" (pr-str features)) (with-redefs [premium-features/token-features (constantly features)] (f))))) TODO -- move this to a shared ` metabase-enterprise.test ` namespace . Consider adding logic that will alias stuff in ;; `metabase-enterprise.test` in `metabase.test` as well *if* EE code is available (defmacro with-premium-features "Execute `body` with the allowed premium features for the Premium-Features token set to `features`. Intended for use testing feature-flagging. (with-premium-features #{:audit-app} ;; audit app will be enabled for body, but no other premium features ...)" {:style/indent 1} [features & body] `(do-with-premium-features ~features (fn [] ~@body))) (defn- token-status-response [token premium-features-response] (http-fake/with-fake-routes-in-isolation {{:address (#'premium-features/token-status-url token) :query-params {:users (str (#'premium-features/active-user-count)) :site-uuid (public-settings/site-uuid-for-premium-features-token-checks)}} (constantly premium-features-response)} (#'premium-features/fetch-token-status* token))) (def ^:private token-response-fixture (json/encode {:valid true :status "fake" :features ["test" "fixture"] :trial false})) (def random-fake-token "d7ad0b5f9ddfd1953b1b427b75d620e4ba91d38e7bcbc09d8982480863dbc611") (defn- random-token [] (let [alphabet (into [] (concat (range 0 10) (map char (range (int \a) (int \g)))))] (apply str (repeatedly 64 #(rand-nth alphabet))))) (deftest fetch-token-status-test (tt/with-temp User [_user {:email ""}] (let [print-token "d7ad...c611"] (testing "Do not log the token (#18249)" (let [logs (mt/with-log-messages-for-level :info (#'premium-features/fetch-token-status* random-fake-token)) pr-str-logs (mapv pr-str logs)] (is (every? (complement #(re-find (re-pattern random-fake-token) %)) pr-str-logs)) (is (= 1 (count (filter #(re-find (re-pattern print-token) %) pr-str-logs)))))) (testing "With the backend unavailable" (let [result (token-status-response random-fake-token {:status 500})] (is (false? (:valid result))))) (testing "On other errors" (binding [http/request (fn [& _] note originally the code caught clojure.lang . ExceptionInfo so do n't ;; throw an ex-info here (throw (Exception. "network issues")))] (is (= {:valid false :status "Unable to validate token" :error-details "network issues"} (premium-features/fetch-token-status (apply str (repeat 64 "b"))))))) (testing "Only attempt the token once" (let [call-count (atom 0)] (binding [clj-http.client/request (fn [& _] (swap! call-count inc) (throw (Exception. "no internet")))] (mt/with-temporary-raw-setting-values [:premium-embedding-token (random-token)] (doseq [premium-setting [premium-features/hide-embed-branding? premium-features/enable-whitelabeling? premium-features/enable-audit-app? premium-features/enable-sandboxes? premium-features/enable-sso? premium-features/enable-advanced-config? premium-features/enable-content-management?]] (is (false? (premium-setting)) (str (:name (meta premium-setting)) "is not false"))) (is (= @call-count 1)))))) (testing "With a valid token" (let [result (token-status-response random-fake-token {:status 200 :body token-response-fixture})] (is (:valid result)) (is (contains? (set (:features result)) "test"))))))) (deftest not-found-test (mt/with-log-level :fatal ` partial= ` here in case the Cloud API starts including extra keys ... this is a " dangerous " test since changes upstream in Cloud could break this . We probably want to catch that stuff anyway tho in tests rather than waiting ;; for bug reports to come in (is (partial= {:valid false, :status "Token does not exist."} (#'premium-features/fetch-token-status* random-fake-token))))) ;;; +----------------------------------------------------------------------------------------------------------------+ | Defenterprise Macro Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ (defenterprise greeting "Returns a greeting for a user." metabase-enterprise.util-test [username] (format "Hi %s, you're an OSS customer!" (name username))) (defenterprise greeting-with-valid-token "Returns a non-special greeting for OSS users, and EE users who don't have a valid premium token" metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (defenterprise special-greeting "Returns a non-special greeting for OSS users, and EE users who don't have the :special-greeting feature token." metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (defenterprise special-greeting-or-custom "Returns a non-special greeting for OSS users." metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (deftest defenterprise-test (when-not config/ee-available? (testing "When EE code is not available, a call to a defenterprise function calls the OSS version" (is (= "Hi rasta, you're an OSS customer!" (greeting :rasta))))) (when config/ee-available? (testing "When EE code is available" (testing "a call to a defenterprise function calls the EE version" (is (= "Hi rasta, you're running the Enterprise Edition of Metabase!" (greeting :rasta)))) (testing "if :feature = :any or nil, it will check if any feature exists, and fall back to the OSS version by default" (with-premium-features #{:some-feature} (is (= "Hi rasta, you're an EE customer with a valid token!" (greeting-with-valid-token :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're not extra special :(" (greeting-with-valid-token :rasta))))) (testing "if a specific premium feature is required, it will check for it, and fall back to the OSS version by default" (with-premium-features #{:special-greeting} (is (= "Hi rasta, you're an extra special EE customer!" (special-greeting :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're not extra special :(" (special-greeting :rasta))))) (testing "when :fallback is a function, it is run when the required token is not present" (with-premium-features #{:special-greeting} (is (= "Hi rasta, you're an extra special EE customer!" (special-greeting-or-custom :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're an EE customer but not extra special." (special-greeting-or-custom :rasta)))))))) (defenterprise-schema greeting-with-schema :- s/Str "Returns a greeting for a user." metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the argument was valid" (name username))) (defenterprise-schema greeting-with-invalid-oss-return-schema :- s/Keyword "Returns a greeting for a user. The OSS implementation has an invalid return schema" metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the return value was valid" (name username))) (defenterprise-schema greeting-with-invalid-ee-return-schema :- s/Str "Returns a greeting for a user." metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the return value was valid" (name username))) (defenterprise greeting-with-only-ee-schema "Returns a greeting for a user. Only EE version is defined with defenterprise-schema." metabase-enterprise.util-test [username] (format "Hi %s, you're an OSS customer!")) (deftest defenterprise-schema-test (when-not config/ee-available? (testing "Argument schemas are validated for OSS implementations" (is (= "Hi rasta, the argument was valid" (greeting-with-schema :rasta))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Input to greeting-with-schema does not match schema" (greeting-with-schema "rasta")))) (testing "Return schemas are validated for OSS implementations" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Output of greeting-with-invalid-oss-return-schema does not match schema" (greeting-with-invalid-oss-return-schema :rasta))))) (when config/ee-available? (testing "Argument schemas are validated for EE implementations" (is (= "Hi rasta, the schema was valid, and you're running the Enterprise Edition of Metabase!" (greeting-with-schema :rasta))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Input to greeting-with-schema does not match schema" (greeting-with-schema "rasta")))) (testing "Only EE schema is validated if EE implementation is called" (is (= "Hi rasta, the schema was valid, and you're running the Enterprise Edition of Metabase!" (greeting-with-invalid-oss-return-schema :rasta))) (with-premium-features #{:custom-feature} (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Output of greeting-with-invalid-ee-return-schema does not match schema" (greeting-with-invalid-ee-return-schema :rasta))))) (testing "EE schema is not validated if OSS fallback is called" (is (= "Hi rasta, the return value was valid" (greeting-with-invalid-ee-return-schema :rasta)))))) (deftest token-status-setting-test (testing "If a `premium-embedding-token` has been set, the `token-status` setting should return the response from the store.metabase.com endpoint for that token." (mt/with-temporary-raw-setting-values [premium-embedding-token (random-token)] (is (= {:valid false, :status "Token does not exist."} (premium-features/token-status))))) (testing "If premium-embedding-token is nil, the token-status setting should also be nil." (mt/with-temporary-setting-values [premium-embedding-token nil] (is (nil? (premium-features/token-status))))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/public_settings/premium_features_test.clj
clojure
`metabase-enterprise.test` in `metabase.test` as well *if* EE code is available audit app will be enabled for body, but no other premium features throw an ex-info here for bug reports to come in +----------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------+
(ns metabase.public-settings.premium-features-test (:require [cheshire.core :as json] [clj-http.client :as http] [clj-http.fake :as http-fake] [clojure.test :refer :all] [metabase.config :as config] [metabase.models.user :refer [User]] [metabase.public-settings :as public-settings] [metabase.public-settings.premium-features :as premium-features :refer [defenterprise defenterprise-schema]] [metabase.test :as mt] [schema.core :as s] [toucan.util.test :as tt])) (defn do-with-premium-features [features f] (let [features (set (map name features))] (testing (format "\nWith premium token features = %s" (pr-str features)) (with-redefs [premium-features/token-features (constantly features)] (f))))) TODO -- move this to a shared ` metabase-enterprise.test ` namespace . Consider adding logic that will alias stuff in (defmacro with-premium-features "Execute `body` with the allowed premium features for the Premium-Features token set to `features`. Intended for use testing feature-flagging. (with-premium-features #{:audit-app} ...)" {:style/indent 1} [features & body] `(do-with-premium-features ~features (fn [] ~@body))) (defn- token-status-response [token premium-features-response] (http-fake/with-fake-routes-in-isolation {{:address (#'premium-features/token-status-url token) :query-params {:users (str (#'premium-features/active-user-count)) :site-uuid (public-settings/site-uuid-for-premium-features-token-checks)}} (constantly premium-features-response)} (#'premium-features/fetch-token-status* token))) (def ^:private token-response-fixture (json/encode {:valid true :status "fake" :features ["test" "fixture"] :trial false})) (def random-fake-token "d7ad0b5f9ddfd1953b1b427b75d620e4ba91d38e7bcbc09d8982480863dbc611") (defn- random-token [] (let [alphabet (into [] (concat (range 0 10) (map char (range (int \a) (int \g)))))] (apply str (repeatedly 64 #(rand-nth alphabet))))) (deftest fetch-token-status-test (tt/with-temp User [_user {:email ""}] (let [print-token "d7ad...c611"] (testing "Do not log the token (#18249)" (let [logs (mt/with-log-messages-for-level :info (#'premium-features/fetch-token-status* random-fake-token)) pr-str-logs (mapv pr-str logs)] (is (every? (complement #(re-find (re-pattern random-fake-token) %)) pr-str-logs)) (is (= 1 (count (filter #(re-find (re-pattern print-token) %) pr-str-logs)))))) (testing "With the backend unavailable" (let [result (token-status-response random-fake-token {:status 500})] (is (false? (:valid result))))) (testing "On other errors" (binding [http/request (fn [& _] note originally the code caught clojure.lang . ExceptionInfo so do n't (throw (Exception. "network issues")))] (is (= {:valid false :status "Unable to validate token" :error-details "network issues"} (premium-features/fetch-token-status (apply str (repeat 64 "b"))))))) (testing "Only attempt the token once" (let [call-count (atom 0)] (binding [clj-http.client/request (fn [& _] (swap! call-count inc) (throw (Exception. "no internet")))] (mt/with-temporary-raw-setting-values [:premium-embedding-token (random-token)] (doseq [premium-setting [premium-features/hide-embed-branding? premium-features/enable-whitelabeling? premium-features/enable-audit-app? premium-features/enable-sandboxes? premium-features/enable-sso? premium-features/enable-advanced-config? premium-features/enable-content-management?]] (is (false? (premium-setting)) (str (:name (meta premium-setting)) "is not false"))) (is (= @call-count 1)))))) (testing "With a valid token" (let [result (token-status-response random-fake-token {:status 200 :body token-response-fixture})] (is (:valid result)) (is (contains? (set (:features result)) "test"))))))) (deftest not-found-test (mt/with-log-level :fatal ` partial= ` here in case the Cloud API starts including extra keys ... this is a " dangerous " test since changes upstream in Cloud could break this . We probably want to catch that stuff anyway tho in tests rather than waiting (is (partial= {:valid false, :status "Token does not exist."} (#'premium-features/fetch-token-status* random-fake-token))))) | Defenterprise Macro Tests | (defenterprise greeting "Returns a greeting for a user." metabase-enterprise.util-test [username] (format "Hi %s, you're an OSS customer!" (name username))) (defenterprise greeting-with-valid-token "Returns a non-special greeting for OSS users, and EE users who don't have a valid premium token" metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (defenterprise special-greeting "Returns a non-special greeting for OSS users, and EE users who don't have the :special-greeting feature token." metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (defenterprise special-greeting-or-custom "Returns a non-special greeting for OSS users." metabase-enterprise.util-test [username] (format "Hi %s, you're not extra special :(" (name username))) (deftest defenterprise-test (when-not config/ee-available? (testing "When EE code is not available, a call to a defenterprise function calls the OSS version" (is (= "Hi rasta, you're an OSS customer!" (greeting :rasta))))) (when config/ee-available? (testing "When EE code is available" (testing "a call to a defenterprise function calls the EE version" (is (= "Hi rasta, you're running the Enterprise Edition of Metabase!" (greeting :rasta)))) (testing "if :feature = :any or nil, it will check if any feature exists, and fall back to the OSS version by default" (with-premium-features #{:some-feature} (is (= "Hi rasta, you're an EE customer with a valid token!" (greeting-with-valid-token :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're not extra special :(" (greeting-with-valid-token :rasta))))) (testing "if a specific premium feature is required, it will check for it, and fall back to the OSS version by default" (with-premium-features #{:special-greeting} (is (= "Hi rasta, you're an extra special EE customer!" (special-greeting :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're not extra special :(" (special-greeting :rasta))))) (testing "when :fallback is a function, it is run when the required token is not present" (with-premium-features #{:special-greeting} (is (= "Hi rasta, you're an extra special EE customer!" (special-greeting-or-custom :rasta)))) (with-premium-features #{} (is (= "Hi rasta, you're an EE customer but not extra special." (special-greeting-or-custom :rasta)))))))) (defenterprise-schema greeting-with-schema :- s/Str "Returns a greeting for a user." metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the argument was valid" (name username))) (defenterprise-schema greeting-with-invalid-oss-return-schema :- s/Keyword "Returns a greeting for a user. The OSS implementation has an invalid return schema" metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the return value was valid" (name username))) (defenterprise-schema greeting-with-invalid-ee-return-schema :- s/Str "Returns a greeting for a user." metabase-enterprise.util-test [username :- s/Keyword] (format "Hi %s, the return value was valid" (name username))) (defenterprise greeting-with-only-ee-schema "Returns a greeting for a user. Only EE version is defined with defenterprise-schema." metabase-enterprise.util-test [username] (format "Hi %s, you're an OSS customer!")) (deftest defenterprise-schema-test (when-not config/ee-available? (testing "Argument schemas are validated for OSS implementations" (is (= "Hi rasta, the argument was valid" (greeting-with-schema :rasta))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Input to greeting-with-schema does not match schema" (greeting-with-schema "rasta")))) (testing "Return schemas are validated for OSS implementations" (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Output of greeting-with-invalid-oss-return-schema does not match schema" (greeting-with-invalid-oss-return-schema :rasta))))) (when config/ee-available? (testing "Argument schemas are validated for EE implementations" (is (= "Hi rasta, the schema was valid, and you're running the Enterprise Edition of Metabase!" (greeting-with-schema :rasta))) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Input to greeting-with-schema does not match schema" (greeting-with-schema "rasta")))) (testing "Only EE schema is validated if EE implementation is called" (is (= "Hi rasta, the schema was valid, and you're running the Enterprise Edition of Metabase!" (greeting-with-invalid-oss-return-schema :rasta))) (with-premium-features #{:custom-feature} (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Output of greeting-with-invalid-ee-return-schema does not match schema" (greeting-with-invalid-ee-return-schema :rasta))))) (testing "EE schema is not validated if OSS fallback is called" (is (= "Hi rasta, the return value was valid" (greeting-with-invalid-ee-return-schema :rasta)))))) (deftest token-status-setting-test (testing "If a `premium-embedding-token` has been set, the `token-status` setting should return the response from the store.metabase.com endpoint for that token." (mt/with-temporary-raw-setting-values [premium-embedding-token (random-token)] (is (= {:valid false, :status "Token does not exist."} (premium-features/token-status))))) (testing "If premium-embedding-token is nil, the token-status setting should also be nil." (mt/with-temporary-setting-values [premium-embedding-token nil] (is (nil? (premium-features/token-status))))))
6236579ab29f84827a9c1fa1554ff61ec3163a6cfddead5125c0735bdd07a345
pallet/pallet-aws
s3.clj
(ns pallet.blobstore.s3 "Amazon s3 provider for pallet" (:require [clojure.java.io :refer [input-stream]] [clojure.string :as string] [com.palletops.awaze.s3 :as s3] [com.palletops.aws.api :as aws] [pallet.blobstore :as blobstor] [pallet.blobstore.implementation :as implementation] [pallet.compute.jvm :as jvm])) (defn buckets [api credentials] "Return a sequence of maps for containers" (aws/execute api (s3/list-buckets-map credentials {}))) (defn bucket-for-name "Filter buckets for the given bucket name." [buckets bucket-name] (first (filter #(= bucket-name (:name %)) buckets))) (defn create-bucket "Create a bucket with the given bucket name." [api credentials bucket-name] (aws/execute api (s3/create-bucket-map credentials {:bucket-name bucket-name}))) (defn put-object-request []) (defmulti put-object-request "Return a partial put-object request map for the payload" type) (defmethod put-object-request :default [x] {:input-stream (input-stream x)}) (defmethod put-object-request java.io.File [file] {:file file}) (defmethod put-object-request String [s] {:input-stream (java.io.ByteArrayInputStream. (.getBytes s java.nio.charset.StandardCharsets/UTF_8))}) (defn put-object "Put a payload into a s3 container at path." [api credentials bucket-name key payload] {:pre [payload]} (aws/execute api (s3/put-object-map credentials (merge {:bucket-name bucket-name :key key} (put-object-request payload))))) (defn one-hour-from-now [] (-> (doto (java.util.Calendar/getInstance) (.setTime (java.util.Date.)) (.add java.util.Calendar/HOUR 1)) .getTime)) (defn generate-presigned-url "Return a pre-signed url." [api credentials bucket-name key request-map] (aws/execute api (s3/generate-presigned-url-map credentials {:bucket-name bucket-name :key key :expiration (one-hour-from-now) :method (-> (:method request-map :GET) name string/upper-case) :response-headers (dissoc request-map :method)}))) (deftype S3Service [credentials api] pallet.blobstore/Blobstore (sign-blob-request [blobstore container path request-map] (let [request (generate-presigned-url api credentials container path request-map)] {:endpoint request})) (put-file [blobstore container path file] (when-not (bucket-for-name (buckets api credentials) container) (create-bucket api credentials container)) (put-object api credentials container path file)) (put [blobstore container path payload] (when-not (bucket-for-name (buckets api credentials) container) (create-bucket api credentials container)) (put-object api credentials container path payload)) (containers [blobstore] (map :name (buckets api credentials))) (close [blobstore])) (defmethod implementation/service :pallet-s3 [provider {:keys [identity credential endpoint api] :or {endpoint "US_EAST_1"}}] (let [credentials {:access-key identity :secret-key credential :endpoint endpoint} api (or api (aws/start {}))] (S3Service. credentials api)))
null
https://raw.githubusercontent.com/pallet/pallet-aws/6f650ca93c853f8a574ad36875f4d164e46e8e8d/src/pallet/blobstore/s3.clj
clojure
(ns pallet.blobstore.s3 "Amazon s3 provider for pallet" (:require [clojure.java.io :refer [input-stream]] [clojure.string :as string] [com.palletops.awaze.s3 :as s3] [com.palletops.aws.api :as aws] [pallet.blobstore :as blobstor] [pallet.blobstore.implementation :as implementation] [pallet.compute.jvm :as jvm])) (defn buckets [api credentials] "Return a sequence of maps for containers" (aws/execute api (s3/list-buckets-map credentials {}))) (defn bucket-for-name "Filter buckets for the given bucket name." [buckets bucket-name] (first (filter #(= bucket-name (:name %)) buckets))) (defn create-bucket "Create a bucket with the given bucket name." [api credentials bucket-name] (aws/execute api (s3/create-bucket-map credentials {:bucket-name bucket-name}))) (defn put-object-request []) (defmulti put-object-request "Return a partial put-object request map for the payload" type) (defmethod put-object-request :default [x] {:input-stream (input-stream x)}) (defmethod put-object-request java.io.File [file] {:file file}) (defmethod put-object-request String [s] {:input-stream (java.io.ByteArrayInputStream. (.getBytes s java.nio.charset.StandardCharsets/UTF_8))}) (defn put-object "Put a payload into a s3 container at path." [api credentials bucket-name key payload] {:pre [payload]} (aws/execute api (s3/put-object-map credentials (merge {:bucket-name bucket-name :key key} (put-object-request payload))))) (defn one-hour-from-now [] (-> (doto (java.util.Calendar/getInstance) (.setTime (java.util.Date.)) (.add java.util.Calendar/HOUR 1)) .getTime)) (defn generate-presigned-url "Return a pre-signed url." [api credentials bucket-name key request-map] (aws/execute api (s3/generate-presigned-url-map credentials {:bucket-name bucket-name :key key :expiration (one-hour-from-now) :method (-> (:method request-map :GET) name string/upper-case) :response-headers (dissoc request-map :method)}))) (deftype S3Service [credentials api] pallet.blobstore/Blobstore (sign-blob-request [blobstore container path request-map] (let [request (generate-presigned-url api credentials container path request-map)] {:endpoint request})) (put-file [blobstore container path file] (when-not (bucket-for-name (buckets api credentials) container) (create-bucket api credentials container)) (put-object api credentials container path file)) (put [blobstore container path payload] (when-not (bucket-for-name (buckets api credentials) container) (create-bucket api credentials container)) (put-object api credentials container path payload)) (containers [blobstore] (map :name (buckets api credentials))) (close [blobstore])) (defmethod implementation/service :pallet-s3 [provider {:keys [identity credential endpoint api] :or {endpoint "US_EAST_1"}}] (let [credentials {:access-key identity :secret-key credential :endpoint endpoint} api (or api (aws/start {}))] (S3Service. credentials api)))
fb702e5e7f5b0c6f68e9a0f823d3fca230565a4e4621c1de7d50268ba2acd5e5
s-expressionists/Cleavir
staple.ext.lisp
(in-package #:cleavir-documentation-generation) (defmethod staple:page-type ((sys (eql (asdf:find-system :cleavir-bir-transformations)))) 'cleavir-page)
null
https://raw.githubusercontent.com/s-expressionists/Cleavir/b211c882e075867b0e18f5ccfc8d38a021df7eb8/BIR-transformations/staple.ext.lisp
lisp
(in-package #:cleavir-documentation-generation) (defmethod staple:page-type ((sys (eql (asdf:find-system :cleavir-bir-transformations)))) 'cleavir-page)
f6dbb322a8e0a56e43f83aaf96e52daff1a0558fda08caac341e2483f77192fb
malcolmsparks/up
nrepl.clj
Copyright © 2013 , . All Rights Reserved . ;; ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; ;; By using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. ;; ;; You must not remove this notice, or any other, from this software. (ns up.nrepl (:require [clojure.tools.nrepl.server :refer (start-server stop-server default-handler)]) (:import (up.start Lifecycle))) (defrecord NReplService [pctx] Lifecycle (start [_] {:pre [(number? (-> pctx :options :port))]} (start-server :host "127.0.0.1" :port (-> pctx :options :port) :handler (default-handler))))
null
https://raw.githubusercontent.com/malcolmsparks/up/4ce578f60f6d60661d32965026bf3c2a854a0d52/up-nrepl/src/up/nrepl.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright © 2013 , . All Rights Reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns up.nrepl (:require [clojure.tools.nrepl.server :refer (start-server stop-server default-handler)]) (:import (up.start Lifecycle))) (defrecord NReplService [pctx] Lifecycle (start [_] {:pre [(number? (-> pctx :options :port))]} (start-server :host "127.0.0.1" :port (-> pctx :options :port) :handler (default-handler))))
3f9da2e7b88833b06f29726ac0438ef821dbd93c1aa53fdd9e54b427bc6ccd00
TerrorJack/ghc-alter
encodingerror001.hs
import System.IO import System.IO.Error import Text.Printf import Control.Monad main = do hSetEncoding stdout latin1 forM [NoBuffering, LineBuffering, BlockBuffering Nothing, BlockBuffering (Just 3), BlockBuffering (Just 9), BlockBuffering (Just 32)] $ \b -> do hSetBuffering stdout b checkedPutStr "test 1\n" checkedPutStr "ě\n" -- nothing gets written checkedPutStr "test 2\n" checkedPutStr "Hέllo\n" -- we should write at least the 'H' checkedPutStr "test 3\n" checkedPutStr "Hello αβγ\n" -- we should write at least the "Hello " checkedPutStr str = do r <- tryIOError $ putStr str case r of Right _ -> return () Left e -> printf "Caught %s while trying to write %s\n" (show e) (show str)
null
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/IO/encodingerror001.hs
haskell
nothing gets written we should write at least the 'H' we should write at least the "Hello "
import System.IO import System.IO.Error import Text.Printf import Control.Monad main = do hSetEncoding stdout latin1 forM [NoBuffering, LineBuffering, BlockBuffering Nothing, BlockBuffering (Just 3), BlockBuffering (Just 9), BlockBuffering (Just 32)] $ \b -> do hSetBuffering stdout b checkedPutStr "test 1\n" checkedPutStr "test 2\n" checkedPutStr "test 3\n" checkedPutStr str = do r <- tryIOError $ putStr str case r of Right _ -> return () Left e -> printf "Caught %s while trying to write %s\n" (show e) (show str)
13ef26b038e582b8c3f889d55f749057a627e5927d270b86b0643032ba1bef00
Commonfare-net/secrets
webpage.clj
;; Secrets part of Decentralized Citizen Engagement Technologies ( D - CENT ) R&D funded by the European Commission ( FP7 / CAPS 610349 ) Copyright ( C ) 2015 - 2017 Dyne.org foundation designed , written and maintained by < > ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see </>. (ns secrets.webpage (:require [secrets.form_helpers :as fh] [secrets.config :refer :all] [fxc.core :as fxc] [hiccup.page :as page] [json-html.core :as present])) (declare render) (declare render-page) (declare render-head) (declare render-navbar) (declare render-footer) (declare render-error) (declare render-static) (defn show-config [session] (present/edn->html (dissoc session :salt :prime :length :entropy :type "__anti-forgery-token"))) (defn check-input [session params form-spec] (if (nil? (:total session)) (render-error "Error: no Session.") (if (nil? (:secret params)) (render-error session "Error: no Params.") (let [input (fh/validate-form (form-spec session) params)] (if (= (:status input) :error) (render-error session [:div [:h2 "form validation"] (:problems input)]) (if (empty? (get-in input [:data :secret])) (render-error session "No input.") {:config session :params (:data input)})))))) (defn check-session [request] (let [session (:session request)] (cond (not (contains? session :config)) (conj session (config-read)) (string? (:config session)) session (false? (:config session)) fxc/settings))) (defn check-params [request form-spec] (fh/validate-form (form-spec (:session request)) (:params request))) (defn render [body] {:headers {"Content-Type" "text/html; charset=utf-8"} :body (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} : src " /static / img / secret_ladies.jpg " ;; :class "pull-right img-responsive" : style " width : 16em ; border:1px solid # 010a40 " } ] ;; [:h1 "Simple Secret Sharing Service" ] body] body] (render-footer)])}) (defn render-error ([] (render-error {} "Unknown")) ([err] (render-error {} err)) ([session error] {:headers {"Content-Type" "text/html; charset=utf-8"} :session session :body (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} [:div {:class "error"} [:h1 "Error:"] [:h2 (drop 1 error)]] [:div {:class "config"} (show-config session)]]])})) ;; helper to switch including different html sections depending from run-mode ;; the atom is defined in config and changed at app start (defn ^:private mode ([m res] (if (= @run-mode m) res)) ([m res relse] (if (= @run-mode m) res relse))) (defn render-head ([] (render-head "Simple Secret Sharing" ;; default title "Decentralised Social Management of Secrets" ;; default desc (mode :web "" ;; url for web ":8080"))) ;; url for desk ([title desc url] [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, maximum-scale=1"}] ;; social stuff [:meta {:name "description" :content desc}] [:meta {:property "og:title" :content title}] [:meta {:property "og:description" :content desc}] [:meta {:property "og:type" :content "website"}] [:meta {:property "og:url" :content url}] [:meta {:property "og:image" :content (str url "/static/img/secret_ladies.jpg")}] [:meta {:name "twitter:card" :content "summary"}] [:meta {:name "twitter:site" :content "@DyneOrg"}] [:meta {:name "twitter:title" :content title}] [:meta {:name "twitter:description" :content desc}] [:meta {:name "twitter:image" :content (str url "/static/img/secret_ladies.jpg")}] [:title title] (page/include-css "/static/css/bootstrap.min.css") (page/include-css "/static/css/bootstrap-theme.min.css") (mode :web (page/include-css "/static/css/gh-fork-ribbon.css")) (mode :web (page/include-css "/static/css/webapp.css"))])) (defn render-navbar [] [:nav {:class "navbar navbar-default navbar-static-top"} (mode :web [:div {:class "github-fork-ribbon-wrapper right"} [:div {:class "github-fork-ribbon"} [:a {:href ""} "Fork me! :^)"]]]) [:div {:class "container"} [:ul {:class "nav navbar-nav"} [:li [:a {:href "/about"} "About Secrets"]] [:li {:role "separator" :class "divider"}] [:li [:a {:href "/share"} "Share Secrets" [:span {:class "sr-only"}"(current)"]]] [:li [:a {:href "/combine"} "Combine Secrets"]] [:li {:role "separator" :class "divider"}]]]]) (defn render-footer [] [:footer {:class "row" :style "margin: 20px"} [:hr] [:div {:class "footer col-sm-2" :style "float: left"} [:img {:src "/static/img/ec_logo.png" :alt "R&D funded by the European Commission" :title "The research and development on Secrets as Free and Open Source Software has been funded by the European Commission."}]] [:div {:class "footer col-sm-2" :style "float: right"} [:a {:href ""} [:img {:src "/static/img/swbydyne.png" :alt "Software by Dyne.org" :title "Software by Dyne.org"}]]] [:div {:class "footer col-sm-2" :style "float: none; margin: 0 auto; clear: none"} [:img {:src "static/img/AGPLv3.png" :alt "Affero GPLv3 License" :title "Affero GPLv3 License"}]] ]) (defn render-static [body] (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} body] (render-footer)])) (defn render-page [{:keys [section body] :as content}] (let [title "Simple Secret Sharing Service" desc "Decentralised Social Management of Secrets" url ""] (page/html5 (render-head) (render-navbar) [:div {:class "container-fluid"} [:img {:src "/static/img/secret_ladies.jpg" :class "pull-right img-responsive" :style "width: 16em; border:1px solid #010a40"}] [:h1 "Simple Secret Sharing Service"] [:h2 "Decentralised Social Management of Secrets"] [:h3 section] body] (render-footer))))
null
https://raw.githubusercontent.com/Commonfare-net/secrets/74d2a71da540cb14fa2158c45a5692e3bfa5090c/src/secrets/webpage.clj
clojure
Secrets This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. along with this program. If not, see </>. :class "pull-right img-responsive" [:h1 "Simple Secret Sharing Service" ] body] helper to switch including different html sections depending from run-mode the atom is defined in config and changed at app start default title default desc url for web url for desk social stuff
part of Decentralized Citizen Engagement Technologies ( D - CENT ) R&D funded by the European Commission ( FP7 / CAPS 610349 ) Copyright ( C ) 2015 - 2017 Dyne.org foundation designed , written and maintained by < > it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Affero General Public License (ns secrets.webpage (:require [secrets.form_helpers :as fh] [secrets.config :refer :all] [fxc.core :as fxc] [hiccup.page :as page] [json-html.core :as present])) (declare render) (declare render-page) (declare render-head) (declare render-navbar) (declare render-footer) (declare render-error) (declare render-static) (defn show-config [session] (present/edn->html (dissoc session :salt :prime :length :entropy :type "__anti-forgery-token"))) (defn check-input [session params form-spec] (if (nil? (:total session)) (render-error "Error: no Session.") (if (nil? (:secret params)) (render-error session "Error: no Params.") (let [input (fh/validate-form (form-spec session) params)] (if (= (:status input) :error) (render-error session [:div [:h2 "form validation"] (:problems input)]) (if (empty? (get-in input [:data :secret])) (render-error session "No input.") {:config session :params (:data input)})))))) (defn check-session [request] (let [session (:session request)] (cond (not (contains? session :config)) (conj session (config-read)) (string? (:config session)) session (false? (:config session)) fxc/settings))) (defn check-params [request form-spec] (fh/validate-form (form-spec (:session request)) (:params request))) (defn render [body] {:headers {"Content-Type" "text/html; charset=utf-8"} :body (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} : src " /static / img / secret_ladies.jpg " : style " width : 16em ; border:1px solid # 010a40 " } ] body] (render-footer)])}) (defn render-error ([] (render-error {} "Unknown")) ([err] (render-error {} err)) ([session error] {:headers {"Content-Type" "text/html; charset=utf-8"} :session session :body (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} [:div {:class "error"} [:h1 "Error:"] [:h2 (drop 1 error)]] [:div {:class "config"} (show-config session)]]])})) (defn ^:private mode ([m res] (if (= @run-mode m) res)) ([m res relse] (if (= @run-mode m) res relse))) (defn render-head ([] (render-head (mode :web ([title desc url] [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge,chrome=1"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1, maximum-scale=1"}] [:meta {:name "description" :content desc}] [:meta {:property "og:title" :content title}] [:meta {:property "og:description" :content desc}] [:meta {:property "og:type" :content "website"}] [:meta {:property "og:url" :content url}] [:meta {:property "og:image" :content (str url "/static/img/secret_ladies.jpg")}] [:meta {:name "twitter:card" :content "summary"}] [:meta {:name "twitter:site" :content "@DyneOrg"}] [:meta {:name "twitter:title" :content title}] [:meta {:name "twitter:description" :content desc}] [:meta {:name "twitter:image" :content (str url "/static/img/secret_ladies.jpg")}] [:title title] (page/include-css "/static/css/bootstrap.min.css") (page/include-css "/static/css/bootstrap-theme.min.css") (mode :web (page/include-css "/static/css/gh-fork-ribbon.css")) (mode :web (page/include-css "/static/css/webapp.css"))])) (defn render-navbar [] [:nav {:class "navbar navbar-default navbar-static-top"} (mode :web [:div {:class "github-fork-ribbon-wrapper right"} [:div {:class "github-fork-ribbon"} [:a {:href ""} "Fork me! :^)"]]]) [:div {:class "container"} [:ul {:class "nav navbar-nav"} [:li [:a {:href "/about"} "About Secrets"]] [:li {:role "separator" :class "divider"}] [:li [:a {:href "/share"} "Share Secrets" [:span {:class "sr-only"}"(current)"]]] [:li [:a {:href "/combine"} "Combine Secrets"]] [:li {:role "separator" :class "divider"}]]]]) (defn render-footer [] [:footer {:class "row" :style "margin: 20px"} [:hr] [:div {:class "footer col-sm-2" :style "float: left"} [:img {:src "/static/img/ec_logo.png" :alt "R&D funded by the European Commission" :title "The research and development on Secrets as Free and Open Source Software has been funded by the European Commission."}]] [:div {:class "footer col-sm-2" :style "float: right"} [:a {:href ""} [:img {:src "/static/img/swbydyne.png" :alt "Software by Dyne.org" :title "Software by Dyne.org"}]]] [:div {:class "footer col-sm-2" :style "float: none; margin: 0 auto; clear: none"} [:img {:src "static/img/AGPLv3.png" :alt "Affero GPLv3 License" :title "Affero GPLv3 License"}]] ]) (defn render-static [body] (page/html5 (render-head) [:body {:class "fxc static"} (render-navbar) [:div {:class "container"} body] (render-footer)])) (defn render-page [{:keys [section body] :as content}] (let [title "Simple Secret Sharing Service" desc "Decentralised Social Management of Secrets" url ""] (page/html5 (render-head) (render-navbar) [:div {:class "container-fluid"} [:img {:src "/static/img/secret_ladies.jpg" :class "pull-right img-responsive" :style "width: 16em; border:1px solid #010a40"}] [:h1 "Simple Secret Sharing Service"] [:h2 "Decentralised Social Management of Secrets"] [:h3 section] body] (render-footer))))
9147cd654e82cd2d29f15616c6b819d4894292fad2c74e0d09dbcd819b495d7c
racket/web-server
dir.rkt
#lang racket/base (require web-server/servlet) (provide (all-defined-out)) (define interface-version 'v1) (define timeout +inf.0) (define (start initial-request) (send/back (response/xexpr `(html (head (title "Current Directory Page")) (body (h1 "Current Directory Page") (p "The current directory is: " (em ,(path->string (current-directory)))))))))
null
https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-lib/web-server/default-web-root/htdocs/servlets/examples/dir.rkt
racket
#lang racket/base (require web-server/servlet) (provide (all-defined-out)) (define interface-version 'v1) (define timeout +inf.0) (define (start initial-request) (send/back (response/xexpr `(html (head (title "Current Directory Page")) (body (h1 "Current Directory Page") (p "The current directory is: " (em ,(path->string (current-directory)))))))))
9bc40d1645a2ae17635bc55bcb8193bb154cc69bd395c4c837bde44b185d9cac
buildsome/buildsome
Meddling.hs
{-# LANGUAGE DeriveDataTypeable #-} module Buildsome.Meddling ( ThirdPartyMeddlingError(..), assertFileMTime, assertSameMTime ) where import Prelude.Compat hiding (FilePath) import Control.Monad import Data.Typeable (Typeable) import Lib.FileDesc (fileStatDescOfStat) import Lib.FilePath (FilePath) import qualified Control.Exception as E import qualified Lib.Directory as Dir import qualified System.Posix.ByteString as Posix data ThirdPartyMeddlingError = ThirdPartyMeddlingError FilePath String deriving (Show, Typeable) instance E.Exception ThirdPartyMeddlingError TODO : Rename MTime to something else , it tests more than assertFileMTime :: String -> FilePath -> Maybe Posix.FileStatus -> IO () assertFileMTime msgPrefix path oldMStat = do newMStat <- Dir.getMFileStatus path assertSameMTime msgPrefix path oldMStat newMStat assertSameMTime :: String -> FilePath -> Maybe Posix.FileStatus -> Maybe Posix.FileStatus -> IO () assertSameMTime msgPrefix path oldMStat newMStat = case (oldMStat, newMStat) of (Nothing, Just _) -> fileErr "created" (Just _, Nothing) -> fileErr "deleted" (Nothing, Nothing) -> pure () (Just oldStat, Just newStat) | Posix.isDirectory newStat -> unless (fileStatDescOfStat oldStat == fileStatDescOfStat newStat) $ err "Directory modified" | Posix.modificationTimeHiRes oldStat /= Posix.modificationTimeHiRes newStat -> fileErr "changed" | otherwise -> pure () where err msg = E.throwIO $ ThirdPartyMeddlingError path (msgPrefix ++ ": " ++ msg) fileErr verb = err $ "File " ++ verb ++ " during build!"
null
https://raw.githubusercontent.com/buildsome/buildsome/479b92bb74a474a5f0c3292b79202cc850bd8653/src/Buildsome/Meddling.hs
haskell
# LANGUAGE DeriveDataTypeable #
module Buildsome.Meddling ( ThirdPartyMeddlingError(..), assertFileMTime, assertSameMTime ) where import Prelude.Compat hiding (FilePath) import Control.Monad import Data.Typeable (Typeable) import Lib.FileDesc (fileStatDescOfStat) import Lib.FilePath (FilePath) import qualified Control.Exception as E import qualified Lib.Directory as Dir import qualified System.Posix.ByteString as Posix data ThirdPartyMeddlingError = ThirdPartyMeddlingError FilePath String deriving (Show, Typeable) instance E.Exception ThirdPartyMeddlingError TODO : Rename MTime to something else , it tests more than assertFileMTime :: String -> FilePath -> Maybe Posix.FileStatus -> IO () assertFileMTime msgPrefix path oldMStat = do newMStat <- Dir.getMFileStatus path assertSameMTime msgPrefix path oldMStat newMStat assertSameMTime :: String -> FilePath -> Maybe Posix.FileStatus -> Maybe Posix.FileStatus -> IO () assertSameMTime msgPrefix path oldMStat newMStat = case (oldMStat, newMStat) of (Nothing, Just _) -> fileErr "created" (Just _, Nothing) -> fileErr "deleted" (Nothing, Nothing) -> pure () (Just oldStat, Just newStat) | Posix.isDirectory newStat -> unless (fileStatDescOfStat oldStat == fileStatDescOfStat newStat) $ err "Directory modified" | Posix.modificationTimeHiRes oldStat /= Posix.modificationTimeHiRes newStat -> fileErr "changed" | otherwise -> pure () where err msg = E.throwIO $ ThirdPartyMeddlingError path (msgPrefix ++ ": " ++ msg) fileErr verb = err $ "File " ++ verb ++ " during build!"