_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
2f60305f483e93e1af34a231626671d05ea84128242b179aba326a8820ec3a7c
jarohen/phoenix
plugin.clj
(ns phoenix.plugin (:require [clojure.java.io :as io])) (defn project-deps [{:keys [dependencies] :as project}] (set (map first dependencies))) (defn with-runtime-dep [project] (cond-> project (not (contains? (project-deps project) 'jarohen/phoenix.runtime)) (update-in [:dependencies] conj ['jarohen/phoenix.runtime (slurp (io/resource "phoenix-version"))]))) (defn select-project-keys [project] (select-keys project [:phoenix/config :target-path :repl-options])) (defn middleware [project] (-> project with-runtime-dep (update-in [:injections] concat `[(require '~'phoenix) (phoenix/init-phoenix! (clojure.java.io/resource ~(:phoenix/config project)))])))
null
https://raw.githubusercontent.com/jarohen/phoenix/f828bf144154f110f0a73f54645f5696e2c8bdab/plugin/src/phoenix/plugin.clj
clojure
(ns phoenix.plugin (:require [clojure.java.io :as io])) (defn project-deps [{:keys [dependencies] :as project}] (set (map first dependencies))) (defn with-runtime-dep [project] (cond-> project (not (contains? (project-deps project) 'jarohen/phoenix.runtime)) (update-in [:dependencies] conj ['jarohen/phoenix.runtime (slurp (io/resource "phoenix-version"))]))) (defn select-project-keys [project] (select-keys project [:phoenix/config :target-path :repl-options])) (defn middleware [project] (-> project with-runtime-dep (update-in [:injections] concat `[(require '~'phoenix) (phoenix/init-phoenix! (clojure.java.io/resource ~(:phoenix/config project)))])))
11a69722fe9f213ad559f11f908bf1b4ed1f27cd5d84526d434bed078c4c1925
mbg/hoop
Spec.hs
-------------------------------------------------------------------------------- import Test.Hspec import Language.Hoop import qualified Counter as C import qualified Expr as E import qualified Expr2 as E2 import qualified List as L import qualified Stack as S -------------------------------------------------------------------------------- main :: IO () main = hspec $ do describe "Counter" $ do describe "Counter" $ do it "c.!next is 0" $ result (C.c.!C.next) `shouldBe` 0 it "(object (c.!next)).!next is 1" $ result ((object (C.c.!C.next)).!C.next) `shouldBe` 1 describe "NameGen" $ do it "ng.!newName is \"var0\"" $ result (C.ng.!C.newName) `shouldBe` "var0" describe "Expr" $ do it "v is 5" $ result (E.v.!E.eval) `shouldBe` 5 it "e is 5" $ result (E.e.!E.eval) `shouldBe` 5 it "a is 10" $ result (E.a.!E.eval) `shouldBe` 10 it "bar is 20" $ E.bar `shouldBe` 20 describe "Expr2" $ do it "v is 5" $ result (E2.v.!E2.eval) `shouldBe` 5 it "e is 5" $ result (E2.e.!E2.eval) `shouldBe` 5 it "a is 10" $ result (E2.a.!E2.eval) `shouldBe` 10 it "b is 10" $ result (E2.b.!E2.eval) `shouldBe` 10 it "bar is 30" $ E2.bar `shouldBe` 30 describe "List" $ do it "should build lists" $ L.test (new Nothing) `shouldBe` [23,16,42,24] it "should sort lists" $ L.test (upcast (new (Nothing,(>)) :: L.SList Int)) `shouldBe` [16,23,24,42] describe "Stack" $ do it "pattern synonyms are working" $ (S.emptyStack :: S.Stack Int) `shouldSatisfy` S.isEmptyStack
null
https://raw.githubusercontent.com/mbg/hoop/98a53bb1db66b06f9b5d3e5242eed336f908ad18/test/Spec.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
import Test.Hspec import Language.Hoop import qualified Counter as C import qualified Expr as E import qualified Expr2 as E2 import qualified List as L import qualified Stack as S main :: IO () main = hspec $ do describe "Counter" $ do describe "Counter" $ do it "c.!next is 0" $ result (C.c.!C.next) `shouldBe` 0 it "(object (c.!next)).!next is 1" $ result ((object (C.c.!C.next)).!C.next) `shouldBe` 1 describe "NameGen" $ do it "ng.!newName is \"var0\"" $ result (C.ng.!C.newName) `shouldBe` "var0" describe "Expr" $ do it "v is 5" $ result (E.v.!E.eval) `shouldBe` 5 it "e is 5" $ result (E.e.!E.eval) `shouldBe` 5 it "a is 10" $ result (E.a.!E.eval) `shouldBe` 10 it "bar is 20" $ E.bar `shouldBe` 20 describe "Expr2" $ do it "v is 5" $ result (E2.v.!E2.eval) `shouldBe` 5 it "e is 5" $ result (E2.e.!E2.eval) `shouldBe` 5 it "a is 10" $ result (E2.a.!E2.eval) `shouldBe` 10 it "b is 10" $ result (E2.b.!E2.eval) `shouldBe` 10 it "bar is 30" $ E2.bar `shouldBe` 30 describe "List" $ do it "should build lists" $ L.test (new Nothing) `shouldBe` [23,16,42,24] it "should sort lists" $ L.test (upcast (new (Nothing,(>)) :: L.SList Int)) `shouldBe` [16,23,24,42] describe "Stack" $ do it "pattern synonyms are working" $ (S.emptyStack :: S.Stack Int) `shouldSatisfy` S.isEmptyStack
c0098b229ccac3c1c1af6332a4986c2bc9d856083ebebb253bb24924f3cb5dc9
pirapira/coq2rust
output.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Cdglobals open Index (*s Low level output *) let output_char c = Pervasives.output_char !out_channel c let output_string s = Pervasives.output_string !out_channel s let printf s = Printf.fprintf !out_channel s let sprintf = Printf.sprintf (*s Coq keywords *) let build_table l = let h = Hashtbl.create 101 in List.iter (fun key ->Hashtbl.add h key ()) l; function s -> try Hashtbl.find h s; true with Not_found -> false let is_keyword = build_table [ "About"; "AddPath"; "Axiom"; "Abort"; "Chapter"; "Check"; "Coercion"; "Compute"; "CoFixpoint"; "CoInductive"; "Corollary"; "Defined"; "Definition"; "End"; "Eval"; "Example"; "Export"; "Fact"; "Fix"; "Fixpoint"; "Function"; "Generalizable"; "Global"; "Grammar"; "Guarded"; "Goal"; "Hint"; "Debug"; "On"; "Hypothesis"; "Hypotheses"; "Resolve"; "Unfold"; "Immediate"; "Extern"; "Constructors"; "Rewrite"; "Implicit"; "Import"; "Inductive"; "Infix"; "Lemma"; "Let"; "Load"; "Local"; "Ltac"; "Module"; "Module Type"; "Declare Module"; "Include"; "Mutual"; "Parameter"; "Parameters"; "Print"; "Printing"; "All"; "Proof"; "Proof with"; "Qed"; "Record"; "Recursive"; "Remark"; "Require"; "Save"; "Scheme"; "Assumptions"; "Axioms"; "Universes"; "Induction"; "for"; "Sort"; "Section"; "Show"; "Structure"; "Syntactic"; "Syntax"; "Tactic"; "Theorem"; "Search"; "SearchAbout"; "SearchHead"; "SearchPattern"; "SearchRewrite"; "Set"; "Types"; "Undo"; "Unset"; "Variable"; "Variables"; "Context"; "Notation"; "Reserved Notation"; "Tactic Notation"; "Delimit"; "Bind"; "Open"; "Scope"; "Inline"; "Implicit Arguments"; "Add"; "Strict"; "Typeclasses"; "Instance"; "Global Instance"; "Class"; "Instantiation"; "subgoal"; "subgoals"; "vm_compute"; "Opaque"; "Transparent"; "Time"; "Extraction"; "Extract"; "Variant"; Program "Program Definition"; "Program Example"; "Program Fixpoint"; "Program Lemma"; "Obligation"; "Obligations"; "Solve"; "using"; "Next Obligation"; "Next"; "Program Instance"; "Equations"; "Equations_nocomp"; (*i (* coq terms *) *) "forall"; "match"; "as"; "in"; "return"; "with"; "end"; "let"; "fun"; "if"; "then"; "else"; "Prop"; "Set"; "Type"; ":="; "where"; "struct"; "wf"; "measure"; "fix"; "cofix"; (* Ltac *) "before"; "after"; "constr"; "ltac"; "goal"; "context"; "beta"; "delta"; "iota"; "zeta"; "lazymatch"; (* Notations *) "level"; "associativity"; "no" ] let is_tactic = build_table [ "intro"; "intros"; "apply"; "rewrite"; "refine"; "case"; "clear"; "injection"; "elimtype"; "progress"; "setoid_rewrite"; "left"; "right"; "constructor"; "econstructor"; "decide equality"; "abstract"; "exists"; "cbv"; "simple destruct"; "info"; "fourier"; "field"; "specialize"; "evar"; "solve"; "instanciate"; "quote"; "eexact"; "autorewrite"; "destruct"; "destruction"; "destruct_call"; "dependent"; "elim"; "extensionality"; "f_equal"; "generalize"; "generalize_eqs"; "generalize_eqs_vars"; "induction"; "rename"; "move"; "omega"; "set"; "assert"; "do"; "repeat"; "cut"; "assumption"; "exact"; "split"; "subst"; "try"; "discriminate"; "simpl"; "unfold"; "red"; "compute"; "at"; "in"; "by"; "reflexivity"; "symmetry"; "transitivity"; "replace"; "setoid_replace"; "inversion"; "inversion_clear"; "pattern"; "intuition"; "congruence"; "fail"; "fresh"; "trivial"; "tauto"; "firstorder"; "ring"; "clapply"; "program_simpl"; "program_simplify"; "eapply"; "auto"; "eauto"; "change"; "fold"; "hnf"; "lazy"; "simple"; "eexists"; "debug"; "idtac"; "first"; "type of"; "pose"; "eval"; "instantiate"; "until" ] (*s Current Coq module *) let current_module : (string * string option) ref = ref ("",None) let get_module withsub = let (m,sub) = !current_module in if withsub then match sub with | None -> m | Some sub -> m ^ ": " ^ sub else m let set_module m sub = current_module := (m,sub); page_title := get_module true s Common to both LaTeX and HTML let item_level = ref 0 let in_doc = ref false (*s Customized and predefined pretty-print *) let initialize_texmacs () = let ensuremath x = sprintf "<with|mode|math|\\<%s\\>>" x in List.fold_right (fun (s,t) tt -> Tokens.ttree_add tt s t) [ "*", ensuremath "times"; "->", ensuremath "rightarrow"; "<-", ensuremath "leftarrow"; "<->", ensuremath "leftrightarrow"; "=>", ensuremath "Rightarrow"; "<=", ensuremath "le"; ">=", ensuremath "ge"; "<>", ensuremath "noteq"; "~", ensuremath "lnot"; "/\\", ensuremath "land"; "\\/", ensuremath "lor"; "|-", ensuremath "vdash" ] Tokens.empty_ttree let token_tree_texmacs = ref (initialize_texmacs ()) let token_tree_latex = ref Tokens.empty_ttree let token_tree_html = ref Tokens.empty_ttree let initialize_tex_html () = let if_utf8 = if !Cdglobals.utf8 then fun x -> Some x else fun _ -> None in let (tree_latex, tree_html) = List.fold_right (fun (s,l,l') (tt,tt') -> (Tokens.ttree_add tt s l, match l' with None -> tt' | Some l' -> Tokens.ttree_add tt' s l')) [ "*" , "\\ensuremath{\\times}", if_utf8 "×"; "|", "\\ensuremath{|}", None; "->", "\\ensuremath{\\rightarrow}", if_utf8 "→"; "->~", "\\ensuremath{\\rightarrow\\lnot}", None; "->~~", "\\ensuremath{\\rightarrow\\lnot\\lnot}", None; "<-", "\\ensuremath{\\leftarrow}", None; "<->", "\\ensuremath{\\leftrightarrow}", if_utf8 "↔"; "=>", "\\ensuremath{\\Rightarrow}", if_utf8 "⇒"; "<=", "\\ensuremath{\\le}", if_utf8 "≤"; ">=", "\\ensuremath{\\ge}", if_utf8 "≥"; "<>", "\\ensuremath{\\not=}", if_utf8 "≠"; "~", "\\ensuremath{\\lnot}", if_utf8 "¬"; "/\\", "\\ensuremath{\\land}", if_utf8 "∧"; "\\/", "\\ensuremath{\\lor}", if_utf8 "∨"; "|-", "\\ensuremath{\\vdash}", None; "forall", "\\ensuremath{\\forall}", if_utf8 "∀"; "exists", "\\ensuremath{\\exists}", if_utf8 "∃"; "Π", "\\ensuremath{\\Pi}", if_utf8 "Π"; "λ", "\\ensuremath{\\lambda}", if_utf8 "λ"; (* "fun", "\\ensuremath{\\lambda}" ? *) ] (Tokens.empty_ttree,Tokens.empty_ttree) in token_tree_latex := tree_latex; token_tree_html := tree_html let add_printing_token s (t1,t2) = (match t1 with None -> () | Some t1 -> token_tree_latex := Tokens.ttree_add !token_tree_latex s t1); (match t2 with None -> () | Some t2 -> token_tree_html := Tokens.ttree_add !token_tree_html s t2) let remove_printing_token s = token_tree_latex := Tokens.ttree_remove !token_tree_latex s; token_tree_html := Tokens.ttree_remove !token_tree_html s (*s Table of contents *) type toc_entry = | Toc_library of string * string option | Toc_section of int * (unit -> unit) * string let (toc_q : toc_entry Queue.t) = Queue.create () let add_toc_entry e = Queue.add e toc_q let new_label = let r = ref 0 in fun () -> incr r; "lab" ^ string_of_int !r (*s LaTeX output *) module Latex = struct let in_title = ref false (*s Latex preamble *) let (preamble : string Queue.t) = Queue.create () let push_in_preamble s = Queue.add s preamble let utf8x_extra_support () = printf "\n"; printf "%%Warning: tipa declares many non-standard macros used by utf8x to\n"; printf "%%interpret utf8 characters but extra packages might have to be added\n"; printf "%%(e.g. \"textgreek\" for Greek letters not already in tipa).\n"; printf "%%Use coqdoc's option -p to add new packages.\n"; printf "\\usepackage{tipa}\n"; printf "\n" let header () = if !header_trailer then begin printf "\\documentclass[12pt]{report}\n"; if !inputenc != "" then printf "\\usepackage[%s]{inputenc}\n" !inputenc; if !inputenc = "utf8x" then utf8x_extra_support (); printf "\\usepackage[T1]{fontenc}\n"; printf "\\usepackage{fullpage}\n"; printf "\\usepackage{coqdoc}\n"; printf "\\usepackage{amsmath,amssymb}\n"; printf "\\usepackage{url}\n"; (match !toc_depth with | None -> () | Some n -> printf "\\setcounter{tocdepth}{%i}\n" n); Queue.iter (fun s -> printf "%s\n" s) preamble; printf "\\begin{document}\n" end; output_string "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; output_string "%% This file has been automatically generated with the command\n"; output_string "%% "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf "\n"; output_string "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" let trailer () = if !header_trailer then begin printf "\\end{document}\n" end (*s Latex low-level translation *) let nbsp () = output_char '~' let char c = match c with | '\\' -> printf "\\symbol{92}" | '$' | '#' | '%' | '&' | '{' | '}' | '_' -> output_char '\\'; output_char c | '^' | '~' -> output_char '\\'; output_char c; printf "{}" | _ -> output_char c let label_char c = match c with | '_' -> output_char ' ' | '\\' | '$' | '#' | '%' | '&' | '{' | '}' | '^' | '~' -> printf "x%X" (Char.code c) | _ -> if c >= '\x80' then printf "x%X" (Char.code c) else output_char c let label_ident s = for i = 0 to String.length s - 1 do label_char s.[i] done let latex_char = output_char let latex_string = output_string let html_char _ = () let html_string _ = () (*s Latex char escaping *) let escaped = let buff = Buffer.create 5 in fun s -> Buffer.clear buff; for i = 0 to String.length s - 1 do match s.[i] with | '\\' -> Buffer.add_string buff "\\symbol{92}" | '$' | '#' | '%' | '&' | '{' | '}' | '_' as c -> Buffer.add_char buff '\\'; Buffer.add_char buff c | '^' | '~' as c -> Buffer.add_char buff '\\'; Buffer.add_char buff c; Buffer.add_string buff "{}" | '\'' -> if i < String.length s - 1 && s.[i+1] = '\'' then begin Buffer.add_char buff '\''; Buffer.add_char buff '{'; Buffer.add_char buff '}' end else Buffer.add_char buff '\'' | c -> Buffer.add_char buff c done; Buffer.contents buff (*s Latex reference and symbol translation *) let start_module () = let ln = !lib_name in if not !short then begin printf "\\coqlibrary{"; label_ident (get_module false); printf "}{"; if ln <> "" then printf "%s " ln; printf "}{%s}\n\n" (escaped (get_module true)) end let start_latex_math () = output_char '$' let stop_latex_math () = output_char '$' let start_quote () = output_char '`'; output_char '`' let stop_quote () = output_char '\''; output_char '\'' let start_verbatim inline = if inline then printf "\\texttt{" else printf "\\begin{verbatim}" let stop_verbatim inline = if inline then printf "}" else printf "\\end{verbatim}\n" let url addr name = printf "%s\\footnote{\\url{%s}}" (match name with | None -> "" | Some n -> n) addr let indentation n = if n == 0 then printf "\\coqdocnoindent\n" else let space = 0.5 *. (float n) in printf "\\coqdocindent{%2.2fem}\n" space let ident_ref m fid typ s = let id = if fid <> "" then (m ^ "." ^ fid) else m in match find_module m with | Local -> if typ = Variable then printf "\\coqdoc%s{%s}" (type_name typ) s else (printf "\\coqref{"; label_ident id; printf "}{\\coqdoc%s{%s}}" (type_name typ) s) | External m when !externals -> printf "\\coqexternalref{"; label_ident fid; printf "}{%s}{\\coqdoc%s{%s}}" (escaped m) (type_name typ) s | External _ | Unknown -> printf "\\coqdoc%s{%s}" (type_name typ) s let defref m id ty s = if ty <> Notation then (printf "\\coqdef{"; label_ident (m ^ "." ^ id); printf "}{%s}{\\coqdoc%s{%s}}" s (type_name ty) s) else Glob file still not able to say the exact extent of the definition (* so we currently renounce to highlight the notation location *) (printf "\\coqdef{"; label_ident (m ^ "." ^ id); printf "}{%s}{%s}" s s) let reference s = function | Def (fullid,typ) -> defref (get_module false) fullid typ s | Ref (m,fullid,typ) -> ident_ref m fullid typ s s The sublexer buffers symbol characters and attached uninterpreted ident and try to apply special translation such as , predefined , translation " - > " to " \ensuremath{\rightarrow } " or , virtually , a user - level translation from " = _ h " to " \ensuremath{=_{h } } " uninterpreted ident and try to apply special translation such as, predefined, translation "->" to "\ensuremath{\rightarrow}" or, virtually, a user-level translation from "=_h" to "\ensuremath{=_{h}}" *) let output_sublexer_string doescape issymbchar tag s = let s = if doescape then escaped s else s in match tag with | Some ref -> reference s ref | None -> if issymbchar then output_string s else printf "\\coqdocvar{%s}" s let last_was_in = ref false let sublexer c loc = if c = '*' && !last_was_in then begin Tokens.flush_sublexer (); output_char '*' end else begin let tag = try Some (Index.find (get_module false) loc) with Not_found -> None in Tokens.output_tagged_symbol_char tag c end; last_was_in := false let sublexer_in_doc c = if c = '*' && !last_was_in then begin Tokens.flush_sublexer (); output_char '*' end else Tokens.output_tagged_symbol_char None c; last_was_in := false let initialize () = initialize_tex_html (); Tokens.token_tree := token_tree_latex; Tokens.outfun := output_sublexer_string (*s Interpreting ident with fallback on sublexer if unknown ident *) let translate s = match Tokens.translate s with Some s -> s | None -> escaped s let keyword s loc = printf "\\coqdockw{%s}" (translate s) let ident s loc = last_was_in := s = "in"; try match loc with | None -> raise Not_found | Some loc -> let tag = Index.find (get_module false) loc in reference (translate s) tag with Not_found -> if is_tactic s then printf "\\coqdoctac{%s}" (translate s) else if is_keyword s then printf "\\coqdockw{%s}" (translate s) else if !Cdglobals.interpolate && !in_doc (* always a var otherwise *) then try let tag = Index.find_string (get_module false) s in reference (translate s) tag with _ -> Tokens.output_tagged_ident_string s else Tokens.output_tagged_ident_string s let ident s l = if !in_title then ( printf "\\texorpdfstring{\\protect"; ident s l; printf "}{%s}" (translate s)) else ident s l (*s Translating structure *) let proofbox () = printf "\\ensuremath{\\Box}" let rec reach_item_level n = if !item_level < n then begin printf "\n\\begin{itemize}\n\\item "; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n\\end{itemize}\n"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n\\item " let stop_item () = reach_item_level 0 let start_doc () = in_doc := true let end_doc () = in_doc := false; stop_item () (* This is broken if we are in math mode, but coqdoc currently isn't tracking that *) let start_emph () = printf "\\textit{" let stop_emph () = printf "}" let start_comment () = printf "\\begin{coqdoccomment}\n" let end_comment () = printf "\\end{coqdoccomment}\n" let start_coq () = printf "\\begin{coqdoccode}\n" let end_coq () = printf "\\end{coqdoccode}\n" let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let section_kind = function | 1 -> "\\section{" | 2 -> "\\subsection{" | 3 -> "\\subsubsection{" | 4 -> "\\paragraph{" | _ -> assert false let section lev f = stop_item (); output_string (section_kind lev); in_title := true; f (); in_title := false; printf "}\n\n" let rule () = printf "\\par\n\\noindent\\hrulefill\\par\n\\noindent{}" let paragraph () = printf "\n\n" let line_break () = printf "\\coqdoceol\n" let empty_line_of_code () = printf "\\coqdocemptyline\n" let start_inline_coq_block () = line_break (); empty_line_of_code () let end_inline_coq_block () = empty_line_of_code () let start_inline_coq () = () let end_inline_coq () = () let make_multi_index () = () let make_index () = () let make_toc () = printf "\\tableofcontents\n" end (*s HTML output *) module Html = struct let header () = if !header_trailer then if !header_file_spec then let cin = Pervasives.open_in !header_file in try while true do let s = Pervasives.input_line cin in printf "%s\n" s done with End_of_file -> Pervasives.close_in cin else begin printf "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"; printf "\"-strict.dtd\">\n"; printf "<html xmlns=\"\">\n<head>\n"; printf "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\" />\n" !charset; printf "<link href=\"coqdoc.css\" rel=\"stylesheet\" type=\"text/css\" />\n"; printf "<title>%s</title>\n</head>\n\n" !page_title; printf "<body>\n\n<div id=\"page\">\n\n<div id=\"header\">\n</div>\n\n"; printf "<div id=\"main\">\n\n" end let trailer () = if !header_trailer && !footer_file_spec then let cin = Pervasives.open_in !footer_file in try while true do let s = Pervasives.input_line cin in printf "%s\n" s done with End_of_file -> Pervasives.close_in cin else begin if !index && (get_module false) <> "Index" then printf "</div>\n\n<div id=\"footer\">\n<hr/><a href=\"%s.html\">Index</a>" !index_name; printf "<hr/>This page has been generated by "; printf "<a href=\"%s\">coqdoc</a>\n" Coq_config.wwwcoq; printf "</div>\n\n</div>\n\n</body>\n</html>" end let start_module () = let ln = !lib_name in if not !short then begin let (m,sub) = !current_module in add_toc_entry (Toc_library (m,sub)); if ln = "" then printf "<h1 class=\"libtitle\">%s</h1>\n\n" (get_module true) else printf "<h1 class=\"libtitle\">%s %s</h1>\n\n" ln (get_module true) end let indentation n = for _i = 1 to n do printf "&nbsp;" done let line_break () = printf "<br/>\n" let empty_line_of_code () = printf "\n<br/>\n" let nbsp () = printf "&nbsp;" let char = function | '<' -> printf "&lt;" | '>' -> printf "&gt;" | '&' -> printf "&amp;" | c -> output_char c let escaped = let buff = Buffer.create 5 in fun s -> Buffer.clear buff; for i = 0 to String.length s - 1 do match s.[i] with | '<' -> Buffer.add_string buff "&lt;" | '>' -> Buffer.add_string buff "&gt;" | '&' -> Buffer.add_string buff "&amp;" | '\'' -> Buffer.add_string buff "&acute;" | '\"' -> Buffer.add_string buff "&quot;" | c -> Buffer.add_char buff c done; Buffer.contents buff let sanitize_name s = let rec loop esc i = if i < 0 then if esc then escaped s else s else match s.[i] with | 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '_' -> loop esc (i-1) | '<' | '>' | '&' | '\'' | '\"' -> loop true (i-1) | _ -> (* This name contains complex characters: this is probably a notation string, we simply hash it. *) Digest.to_hex (Digest.string s) in loop false (String.length s - 1) let latex_char _ = () let latex_string _ = () let html_char = output_char let html_string = output_string let start_latex_math () = () let stop_latex_math () = () let start_quote () = char '"' let stop_quote () = start_quote () let start_verbatim inline = if inline then printf "<tt>" else printf "<pre>" let stop_verbatim inline = if inline then printf "</tt>" else printf "</pre>\n" let url addr name = printf "<a href=\"%s\">%s</a>" addr (match name with | Some n -> n | None -> addr) let ident_ref m fid typ s = match find_module m with | Local -> printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s | External m when !externals -> printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s | External _ | Unknown -> printf "<span class=\"id\" title=\"%s\">%s</span>" typ s let reference s r = match r with | Def (fullid,ty) -> printf "<a name=\"%s\">" (sanitize_name fullid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" (type_name ty) s | Ref (m,fullid,ty) -> ident_ref m fullid (type_name ty) s let output_sublexer_string doescape issymbchar tag s = let s = if doescape then escaped s else s in match tag with | Some ref -> reference s ref | None -> if issymbchar then output_string s else printf "<span class=\"id\" title=\"var\">%s</span>" s let sublexer c loc = let tag = try Some (Index.find (get_module false) loc) with Not_found -> None in Tokens.output_tagged_symbol_char tag c let sublexer_in_doc c = Tokens.output_tagged_symbol_char None c let initialize () = initialize_tex_html(); Tokens.token_tree := token_tree_html; Tokens.outfun := output_sublexer_string let translate s = match Tokens.translate s with Some s -> s | None -> escaped s let keyword s loc = printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s) let ident s loc = if is_keyword s then begin printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s) end else begin try match loc with | None -> raise Not_found | Some loc -> reference (translate s) (Index.find (get_module false) loc) with Not_found -> if is_tactic s then printf "<span class=\"id\" title=\"tactic\">%s</span>" (translate s) else if !Cdglobals.interpolate && !in_doc (* always a var otherwise *) then try reference (translate s) (Index.find_string (get_module false) s) with _ -> Tokens.output_tagged_ident_string s else Tokens.output_tagged_ident_string s end let proofbox () = printf "<font size=-2>&#9744;</font>" let rec reach_item_level n = if !item_level < n then begin printf "<ul class=\"doclist\">\n<li>"; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n</li>\n</ul>\n"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n</li>\n<li>" let stop_item () = reach_item_level 0 let start_coq () = if not !raw_comments then printf "<div class=\"code\">\n" let end_coq () = if not !raw_comments then printf "</div>\n" let start_doc () = in_doc := true; if not !raw_comments then printf "\n<div class=\"doc\">\n" let end_doc () = in_doc := false; stop_item (); if not !raw_comments then printf "\n</div>\n" let start_emph () = printf "<i>" let stop_emph () = printf "</i>" let start_comment () = printf "<span class=\"comment\">(*" let end_comment () = printf "*)</span>" let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let start_inline_coq () = if !inline_notmono then printf "<span class=\"inlinecodenm\">" else printf "<span class=\"inlinecode\">" let end_inline_coq () = printf "</span>" let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let paragraph () = printf "\n<div class=\"paragraph\"> </div>\n\n" (* inference rules *) let inf_rule assumptions (_,_,midnm) conclusions = this first function replaces any occurance of 3 or more spaces in a row with " & nbsp;"s . We do this to the assumptions so that people can put multiple rules on a line with nice formatting in a row with "&nbsp;"s. We do this to the assumptions so that people can put multiple rules on a line with nice formatting *) let replace_spaces str = let rec copy a n = match n with 0 -> [] | n -> (a :: copy a (n - 1)) in let results = Str.full_split (Str.regexp "[' '][' '][' ']+") str in let strs = List.map (fun r -> match r with | Str.Text s -> [s] | Str.Delim s -> copy "&nbsp;" (String.length s)) results in String.concat "" (List.concat strs) in let start_assumption line = (printf "<tr class=\"infruleassumption\">\n"; printf " <td class=\"infrule\">%s</td>\n" (replace_spaces line)) in let end_assumption () = (printf " <td></td>\n"; printf "</td>\n") in let rec print_assumptions hyps = match hyps with | [] -> start_assumption "&nbsp;&nbsp;" | [(_,hyp)] -> start_assumption hyp | ((_,hyp) :: hyps') -> (start_assumption hyp; end_assumption (); print_assumptions hyps') in printf "<center><table class=\"infrule\">\n"; print_assumptions assumptions; printf " <td class=\"infrulenamecol\" rowspan=\"3\">\n"; (match midnm with | None -> printf " &nbsp;\n </td>" | Some s -> printf " %s &nbsp;\n </td>" s); printf "</tr>\n"; printf "<tr class=\"infrulemiddle\">\n"; printf " <td class=\"infrule\"><hr /></td>\n"; printf "</tr>\n"; print_assumptions conclusions; end_assumption (); printf "</table></center>" let section lev f = let lab = new_label () in let r = sprintf "%s.html#%s" (get_module false) lab in (match !toc_depth with | None -> add_toc_entry (Toc_section (lev, f, r)) | Some n -> if lev <= n then add_toc_entry (Toc_section (lev, f, r)) else ()); stop_item (); printf "<a name=\"%s\"></a><h%d class=\"section\">" lab lev; f (); printf "</h%d>\n" lev let rule () = printf "<hr/>\n" (* make a HTML index from a list of triples (name,text,link) *) let index_ref i c = let idxc = sprintf "%s_%c" i.idx_name c in !index_name ^ (if !multi_index then "_" ^ idxc ^ ".html" else ".html#" ^ idxc) let letter_index category idx (c,l) = if l <> [] then begin let cat = if category && idx <> "global" then "(" ^ idx ^ ")" else "" in printf "<a name=\"%s_%c\"></a><h2>%s %s</h2>\n" idx c (display_letter c) cat; List.iter (fun (id,(text,link,t)) -> let id' = prepare_entry id t in printf "<a href=\"%s\">%s</a> %s<br/>\n" link id' text) l; printf "<br/><br/>" end let all_letters i = List.iter (letter_index false i.idx_name) i.idx_entries Construction d'une liste des index ( 1 index global , puis 1 index par catégorie ) index par catégorie) *) let format_global_index = Index.map (fun s (m,t) -> if t = Library then let ln = !lib_name in if ln <> "" then "[" ^ String.lowercase ln ^ "]", m ^ ".html", t else "[library]", m ^ ".html", t else sprintf "[%s, in <a href=\"%s.html\">%s</a>]" (type_name t) m m , sprintf "%s.html#%s" m (sanitize_name s), t) let format_bytype_index = function | Library, idx -> Index.map (fun id m -> "", m ^ ".html", Library) idx | (t,idx) -> Index.map (fun s m -> let text = sprintf "[in <a href=\"%s.html\">%s</a>]" m m in (text, sprintf "%s.html#%s" m (sanitize_name s), t)) idx Impression de la table d'index let print_index_table_item i = printf "<tr>\n<td>%s Index</td>\n" (String.capitalize i.idx_name); List.iter (fun (c,l) -> if l <> [] then printf "<td><a href=\"%s\">%s</a></td>\n" (index_ref i c) (display_letter c) else printf "<td>%s</td>\n" (display_letter c)) i.idx_entries; let n = i.idx_size in printf "<td>(%d %s)</td>\n" n (if n > 1 then "entries" else "entry"); printf "</tr>\n" let print_index_table idxl = printf "<table>\n"; List.iter print_index_table_item idxl; printf "</table>\n" let make_one_multi_index prt_tbl i = Attn : make_one_multi_index ... let idx = i.idx_name in let one_letter ((c,l) as cl) = open_out_file (sprintf "%s_%s_%c.html" !index_name idx c); if (!header_trailer) then header (); prt_tbl (); printf "<hr/>"; letter_index true idx cl; if List.length l > 30 then begin printf "<hr/>"; prt_tbl () end; if (!header_trailer) then trailer (); close_out_file () in List.iter one_letter i.idx_entries let make_multi_index () = let all_index = let glob,bt = Index.all_entries () in (format_global_index glob) :: (List.map format_bytype_index bt) in let print_table () = print_index_table all_index in List.iter (make_one_multi_index print_table) all_index let make_index () = let all_index = let glob,bt = Index.all_entries () in (format_global_index glob) :: (List.map format_bytype_index bt) in let print_table () = print_index_table all_index in let print_one_index i = if i.idx_size > 0 then begin printf "<hr/>\n<h1>%s Index</h1>\n" (String.capitalize i.idx_name); all_letters i end in set_module "Index" None; if !title <> "" then printf "<h1>%s</h1>\n" !title; print_table (); if not (!multi_index) then begin List.iter print_one_index all_index; printf "<hr/>"; print_table () end let make_toc () = let ln = !lib_name in let make_toc_entry = function | Toc_library (m,sub) -> stop_item (); let ms = match sub with | None -> m | Some s -> m ^ ": " ^ s in if ln = "" then printf "<a href=\"%s.html\"><h2>%s</h2></a>\n" m ms else printf "<a href=\"%s.html\"><h2>%s %s</h2></a>\n" m ln ms | Toc_section (n, f, r) -> item n; printf "<a href=\"%s\">" r; f (); printf "</a>\n" in printf "<div id=\"toc\">\n"; Queue.iter make_toc_entry toc_q; stop_item (); printf "</div>\n" end (*s TeXmacs-aware output *) module TeXmacs = struct (*s Latex preamble *) let (preamble : string Queue.t) = in_doc := false; Queue.create () let header () = output_string "(*i This file has been automatically generated with the command \n"; output_string " "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf " *)\n" let trailer () = () let nbsp () = output_char ' ' let char_true c = match c with | '\\' -> printf "\\\\" | '<' -> printf "\\<" | '|' -> printf "\\|" | '>' -> printf "\\>" | _ -> output_char c let char c = if !in_doc then char_true c else output_char c let latex_char = char_true let latex_string = String.iter latex_char let html_char _ = () let html_string _ = () let raw_ident s = for i = 0 to String.length s - 1 do char s.[i] done let start_module () = () let start_latex_math () = printf "<with|mode|math|" let stop_latex_math () = output_char '>' let start_verbatim inline = in_doc := true; printf "<\\verbatim>" let stop_verbatim inline = in_doc := false; printf "</verbatim>" let url addr name = printf "%s<\\footnote><\\url>%s</url></footnote>" addr (match name with | None -> "" | Some n -> n) let start_quote () = output_char '`'; output_char '`' let stop_quote () = output_char '\''; output_char '\'' let indentation n = () let keyword s = printf "<kw|"; raw_ident s; printf ">" let ident_true s = if is_keyword s then keyword s else raw_ident s let keyword s loc = keyword s let ident s _ = if !in_doc then ident_true s else raw_ident s let output_sublexer_string doescape issymbchar tag s = if doescape then raw_ident s else output_string s let sublexer c l = if !in_doc then Tokens.output_tagged_symbol_char None c else char c let sublexer_in_doc c = char c let initialize () = Tokens.token_tree := token_tree_texmacs; Tokens.outfun := output_sublexer_string let proofbox () = printf "QED" let rec reach_item_level n = if !item_level < n then begin printf "\n<\\itemize>\n<item>"; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n</itemize>"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n\n<item>" let stop_item () = reach_item_level 0 let start_doc () = in_doc := true; printf "(** texmacs: " let end_doc () = stop_item (); in_doc := false; printf " *)" let start_coq () = () let end_coq () = () let start_emph () = printf "<with|font shape|italic|" let stop_emph () = printf ">" let start_comment () = () let end_comment () = () let start_code () = in_doc := true; printf "<\\code>\n" let end_code () = in_doc := false; printf "\n</code>" let section_kind = function | 1 -> "section" | 2 -> "subsection" | 3 -> "subsubsection" | 4 -> "paragraph" | _ -> assert false let section lev f = stop_item (); printf "<"; output_string (section_kind lev); printf "|"; f (); printf ">\n\n" let rule () = printf "\n<hrule>\n" let paragraph () = printf "\n\n" let line_break () = printf "\n" let empty_line_of_code () = printf "\n" let start_inline_coq () = printf "<verbatim|[" let end_inline_coq () = printf "]>" let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let make_multi_index () = () let make_index () = () let make_toc () = () end (*s Raw output *) module Raw = struct let header () = () let trailer () = () let nbsp () = output_char ' ' let char = output_char let latex_char = output_char let latex_string = output_string let html_char _ = () let html_string _ = () let raw_ident s = for i = 0 to String.length s - 1 do char s.[i] done let start_module () = () let end_module () = () let start_latex_math () = () let stop_latex_math () = () let start_verbatim inline = () let stop_verbatim inline = () let url addr name = match name with | Some n -> printf "%s (%s)" n addr | None -> printf "%s" addr let start_quote () = printf "\"" let stop_quote () = printf "\"" let indentation n = for _i = 1 to n do printf " " done let keyword s loc = raw_ident s let ident s loc = raw_ident s let sublexer c l = char c let sublexer_in_doc c = char c let initialize () = Tokens.token_tree := ref Tokens.empty_ttree; Tokens.outfun := (fun _ _ _ _ -> failwith "Useless") let proofbox () = printf "[]" let item n = printf "- " let stop_item () = () let reach_item_level _ = () let start_doc () = printf "(** " let end_doc () = printf " *)\n" let start_emph () = printf "_" let stop_emph () = printf "_" let start_comment () = printf "(*" let end_comment () = printf "*)" let start_coq () = () let end_coq () = () let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let section_kind = function | 1 -> "* " | 2 -> "** " | 3 -> "*** " | 4 -> "**** " | _ -> assert false let section lev f = output_string (section_kind lev); f () let rule () = () let paragraph () = printf "\n\n" let line_break () = printf "\n" let empty_line_of_code () = printf "\n" let start_inline_coq () = () let end_inline_coq () = () let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let make_multi_index () = () let make_index () = () let make_toc () = () end (*s Generic output *) let select f1 f2 f3 f4 x = match !target_language with LaTeX -> f1 x | HTML -> f2 x | TeXmacs -> f3 x | Raw -> f4 x let push_in_preamble = Latex.push_in_preamble let header = select Latex.header Html.header TeXmacs.header Raw.header let trailer = select Latex.trailer Html.trailer TeXmacs.trailer Raw.trailer let start_module = select Latex.start_module Html.start_module TeXmacs.start_module Raw.start_module let start_doc = select Latex.start_doc Html.start_doc TeXmacs.start_doc Raw.start_doc let end_doc = select Latex.end_doc Html.end_doc TeXmacs.end_doc Raw.end_doc let start_comment = select Latex.start_comment Html.start_comment TeXmacs.start_comment Raw.start_comment let end_comment = select Latex.end_comment Html.end_comment TeXmacs.end_comment Raw.end_comment let start_coq = select Latex.start_coq Html.start_coq TeXmacs.start_coq Raw.start_coq let end_coq = select Latex.end_coq Html.end_coq TeXmacs.end_coq Raw.end_coq let start_code = select Latex.start_code Html.start_code TeXmacs.start_code Raw.start_code let end_code = select Latex.end_code Html.end_code TeXmacs.end_code Raw.end_code let start_inline_coq = select Latex.start_inline_coq Html.start_inline_coq TeXmacs.start_inline_coq Raw.start_inline_coq let end_inline_coq = select Latex.end_inline_coq Html.end_inline_coq TeXmacs.end_inline_coq Raw.end_inline_coq let start_inline_coq_block = select Latex.start_inline_coq_block Html.start_inline_coq_block TeXmacs.start_inline_coq_block Raw.start_inline_coq_block let end_inline_coq_block = select Latex.end_inline_coq_block Html.end_inline_coq_block TeXmacs.end_inline_coq_block Raw.end_inline_coq_block let indentation = select Latex.indentation Html.indentation TeXmacs.indentation Raw.indentation let paragraph = select Latex.paragraph Html.paragraph TeXmacs.paragraph Raw.paragraph let line_break = select Latex.line_break Html.line_break TeXmacs.line_break Raw.line_break let empty_line_of_code = select Latex.empty_line_of_code Html.empty_line_of_code TeXmacs.empty_line_of_code Raw.empty_line_of_code let section = select Latex.section Html.section TeXmacs.section Raw.section let item = select Latex.item Html.item TeXmacs.item Raw.item let stop_item = select Latex.stop_item Html.stop_item TeXmacs.stop_item Raw.stop_item let reach_item_level = select Latex.reach_item_level Html.reach_item_level TeXmacs.reach_item_level Raw.reach_item_level let rule = select Latex.rule Html.rule TeXmacs.rule Raw.rule let nbsp = select Latex.nbsp Html.nbsp TeXmacs.nbsp Raw.nbsp let char = select Latex.char Html.char TeXmacs.char Raw.char let keyword = select Latex.keyword Html.keyword TeXmacs.keyword Raw.keyword let ident = select Latex.ident Html.ident TeXmacs.ident Raw.ident let sublexer = select Latex.sublexer Html.sublexer TeXmacs.sublexer Raw.sublexer let sublexer_in_doc = select Latex.sublexer_in_doc Html.sublexer_in_doc TeXmacs.sublexer_in_doc Raw.sublexer_in_doc let initialize = select Latex.initialize Html.initialize TeXmacs.initialize Raw.initialize let proofbox = select Latex.proofbox Html.proofbox TeXmacs.proofbox Raw.proofbox let latex_char = select Latex.latex_char Html.latex_char TeXmacs.latex_char Raw.latex_char let latex_string = select Latex.latex_string Html.latex_string TeXmacs.latex_string Raw.latex_string let html_char = select Latex.html_char Html.html_char TeXmacs.html_char Raw.html_char let html_string = select Latex.html_string Html.html_string TeXmacs.html_string Raw.html_string let start_emph = select Latex.start_emph Html.start_emph TeXmacs.start_emph Raw.start_emph let stop_emph = select Latex.stop_emph Html.stop_emph TeXmacs.stop_emph Raw.stop_emph let start_latex_math = select Latex.start_latex_math Html.start_latex_math TeXmacs.start_latex_math Raw.start_latex_math let stop_latex_math = select Latex.stop_latex_math Html.stop_latex_math TeXmacs.stop_latex_math Raw.stop_latex_math let start_verbatim = select Latex.start_verbatim Html.start_verbatim TeXmacs.start_verbatim Raw.start_verbatim let stop_verbatim = select Latex.stop_verbatim Html.stop_verbatim TeXmacs.stop_verbatim Raw.stop_verbatim let verbatim_char inline = select (if inline then Latex.char else output_char) Html.char TeXmacs.char Raw.char let hard_verbatim_char = output_char let url = select Latex.url Html.url TeXmacs.url Raw.url let start_quote = select Latex.start_quote Html.start_quote TeXmacs.start_quote Raw.start_quote let stop_quote = select Latex.stop_quote Html.stop_quote TeXmacs.stop_quote Raw.stop_quote let inf_rule_dumb assumptions (midsp,midln,midnm) conclusions = start_verbatim false; let dumb_line = function (sp,ln) -> (String.iter char ((String.make sp ' ') ^ ln); char '\n') in (List.iter dumb_line assumptions; dumb_line (midsp, midln ^ (match midnm with | Some s -> " " ^ s | None -> "")); List.iter dumb_line conclusions); stop_verbatim false let inf_rule = select inf_rule_dumb Html.inf_rule inf_rule_dumb inf_rule_dumb let make_multi_index = select Latex.make_multi_index Html.make_multi_index TeXmacs.make_multi_index Raw.make_multi_index let make_index = select Latex.make_index Html.make_index TeXmacs.make_index Raw.make_index let make_toc = select Latex.make_toc Html.make_toc TeXmacs.make_toc Raw.make_toc
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/tools/coqdoc/output.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** s Low level output s Coq keywords i (* coq terms Ltac Notations s Current Coq module s Customized and predefined pretty-print "fun", "\\ensuremath{\\lambda}" ? s Table of contents s LaTeX output s Latex preamble s Latex low-level translation s Latex char escaping s Latex reference and symbol translation so we currently renounce to highlight the notation location s Interpreting ident with fallback on sublexer if unknown ident always a var otherwise s Translating structure This is broken if we are in math mode, but coqdoc currently isn't tracking that s HTML output This name contains complex characters: this is probably a notation string, we simply hash it. always a var otherwise inference rules make a HTML index from a list of triples (name,text,link) s TeXmacs-aware output s Latex preamble s Raw output s Generic output
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Cdglobals open Index let output_char c = Pervasives.output_char !out_channel c let output_string s = Pervasives.output_string !out_channel s let printf s = Printf.fprintf !out_channel s let sprintf = Printf.sprintf let build_table l = let h = Hashtbl.create 101 in List.iter (fun key ->Hashtbl.add h key ()) l; function s -> try Hashtbl.find h s; true with Not_found -> false let is_keyword = build_table [ "About"; "AddPath"; "Axiom"; "Abort"; "Chapter"; "Check"; "Coercion"; "Compute"; "CoFixpoint"; "CoInductive"; "Corollary"; "Defined"; "Definition"; "End"; "Eval"; "Example"; "Export"; "Fact"; "Fix"; "Fixpoint"; "Function"; "Generalizable"; "Global"; "Grammar"; "Guarded"; "Goal"; "Hint"; "Debug"; "On"; "Hypothesis"; "Hypotheses"; "Resolve"; "Unfold"; "Immediate"; "Extern"; "Constructors"; "Rewrite"; "Implicit"; "Import"; "Inductive"; "Infix"; "Lemma"; "Let"; "Load"; "Local"; "Ltac"; "Module"; "Module Type"; "Declare Module"; "Include"; "Mutual"; "Parameter"; "Parameters"; "Print"; "Printing"; "All"; "Proof"; "Proof with"; "Qed"; "Record"; "Recursive"; "Remark"; "Require"; "Save"; "Scheme"; "Assumptions"; "Axioms"; "Universes"; "Induction"; "for"; "Sort"; "Section"; "Show"; "Structure"; "Syntactic"; "Syntax"; "Tactic"; "Theorem"; "Search"; "SearchAbout"; "SearchHead"; "SearchPattern"; "SearchRewrite"; "Set"; "Types"; "Undo"; "Unset"; "Variable"; "Variables"; "Context"; "Notation"; "Reserved Notation"; "Tactic Notation"; "Delimit"; "Bind"; "Open"; "Scope"; "Inline"; "Implicit Arguments"; "Add"; "Strict"; "Typeclasses"; "Instance"; "Global Instance"; "Class"; "Instantiation"; "subgoal"; "subgoals"; "vm_compute"; "Opaque"; "Transparent"; "Time"; "Extraction"; "Extract"; "Variant"; Program "Program Definition"; "Program Example"; "Program Fixpoint"; "Program Lemma"; "Obligation"; "Obligations"; "Solve"; "using"; "Next Obligation"; "Next"; "Program Instance"; "Equations"; "Equations_nocomp"; "forall"; "match"; "as"; "in"; "return"; "with"; "end"; "let"; "fun"; "if"; "then"; "else"; "Prop"; "Set"; "Type"; ":="; "where"; "struct"; "wf"; "measure"; "fix"; "cofix"; "before"; "after"; "constr"; "ltac"; "goal"; "context"; "beta"; "delta"; "iota"; "zeta"; "lazymatch"; "level"; "associativity"; "no" ] let is_tactic = build_table [ "intro"; "intros"; "apply"; "rewrite"; "refine"; "case"; "clear"; "injection"; "elimtype"; "progress"; "setoid_rewrite"; "left"; "right"; "constructor"; "econstructor"; "decide equality"; "abstract"; "exists"; "cbv"; "simple destruct"; "info"; "fourier"; "field"; "specialize"; "evar"; "solve"; "instanciate"; "quote"; "eexact"; "autorewrite"; "destruct"; "destruction"; "destruct_call"; "dependent"; "elim"; "extensionality"; "f_equal"; "generalize"; "generalize_eqs"; "generalize_eqs_vars"; "induction"; "rename"; "move"; "omega"; "set"; "assert"; "do"; "repeat"; "cut"; "assumption"; "exact"; "split"; "subst"; "try"; "discriminate"; "simpl"; "unfold"; "red"; "compute"; "at"; "in"; "by"; "reflexivity"; "symmetry"; "transitivity"; "replace"; "setoid_replace"; "inversion"; "inversion_clear"; "pattern"; "intuition"; "congruence"; "fail"; "fresh"; "trivial"; "tauto"; "firstorder"; "ring"; "clapply"; "program_simpl"; "program_simplify"; "eapply"; "auto"; "eauto"; "change"; "fold"; "hnf"; "lazy"; "simple"; "eexists"; "debug"; "idtac"; "first"; "type of"; "pose"; "eval"; "instantiate"; "until" ] let current_module : (string * string option) ref = ref ("",None) let get_module withsub = let (m,sub) = !current_module in if withsub then match sub with | None -> m | Some sub -> m ^ ": " ^ sub else m let set_module m sub = current_module := (m,sub); page_title := get_module true s Common to both LaTeX and HTML let item_level = ref 0 let in_doc = ref false let initialize_texmacs () = let ensuremath x = sprintf "<with|mode|math|\\<%s\\>>" x in List.fold_right (fun (s,t) tt -> Tokens.ttree_add tt s t) [ "*", ensuremath "times"; "->", ensuremath "rightarrow"; "<-", ensuremath "leftarrow"; "<->", ensuremath "leftrightarrow"; "=>", ensuremath "Rightarrow"; "<=", ensuremath "le"; ">=", ensuremath "ge"; "<>", ensuremath "noteq"; "~", ensuremath "lnot"; "/\\", ensuremath "land"; "\\/", ensuremath "lor"; "|-", ensuremath "vdash" ] Tokens.empty_ttree let token_tree_texmacs = ref (initialize_texmacs ()) let token_tree_latex = ref Tokens.empty_ttree let token_tree_html = ref Tokens.empty_ttree let initialize_tex_html () = let if_utf8 = if !Cdglobals.utf8 then fun x -> Some x else fun _ -> None in let (tree_latex, tree_html) = List.fold_right (fun (s,l,l') (tt,tt') -> (Tokens.ttree_add tt s l, match l' with None -> tt' | Some l' -> Tokens.ttree_add tt' s l')) [ "*" , "\\ensuremath{\\times}", if_utf8 "×"; "|", "\\ensuremath{|}", None; "->", "\\ensuremath{\\rightarrow}", if_utf8 "→"; "->~", "\\ensuremath{\\rightarrow\\lnot}", None; "->~~", "\\ensuremath{\\rightarrow\\lnot\\lnot}", None; "<-", "\\ensuremath{\\leftarrow}", None; "<->", "\\ensuremath{\\leftrightarrow}", if_utf8 "↔"; "=>", "\\ensuremath{\\Rightarrow}", if_utf8 "⇒"; "<=", "\\ensuremath{\\le}", if_utf8 "≤"; ">=", "\\ensuremath{\\ge}", if_utf8 "≥"; "<>", "\\ensuremath{\\not=}", if_utf8 "≠"; "~", "\\ensuremath{\\lnot}", if_utf8 "¬"; "/\\", "\\ensuremath{\\land}", if_utf8 "∧"; "\\/", "\\ensuremath{\\lor}", if_utf8 "∨"; "|-", "\\ensuremath{\\vdash}", None; "forall", "\\ensuremath{\\forall}", if_utf8 "∀"; "exists", "\\ensuremath{\\exists}", if_utf8 "∃"; "Π", "\\ensuremath{\\Pi}", if_utf8 "Π"; "λ", "\\ensuremath{\\lambda}", if_utf8 "λ"; ] (Tokens.empty_ttree,Tokens.empty_ttree) in token_tree_latex := tree_latex; token_tree_html := tree_html let add_printing_token s (t1,t2) = (match t1 with None -> () | Some t1 -> token_tree_latex := Tokens.ttree_add !token_tree_latex s t1); (match t2 with None -> () | Some t2 -> token_tree_html := Tokens.ttree_add !token_tree_html s t2) let remove_printing_token s = token_tree_latex := Tokens.ttree_remove !token_tree_latex s; token_tree_html := Tokens.ttree_remove !token_tree_html s type toc_entry = | Toc_library of string * string option | Toc_section of int * (unit -> unit) * string let (toc_q : toc_entry Queue.t) = Queue.create () let add_toc_entry e = Queue.add e toc_q let new_label = let r = ref 0 in fun () -> incr r; "lab" ^ string_of_int !r module Latex = struct let in_title = ref false let (preamble : string Queue.t) = Queue.create () let push_in_preamble s = Queue.add s preamble let utf8x_extra_support () = printf "\n"; printf "%%Warning: tipa declares many non-standard macros used by utf8x to\n"; printf "%%interpret utf8 characters but extra packages might have to be added\n"; printf "%%(e.g. \"textgreek\" for Greek letters not already in tipa).\n"; printf "%%Use coqdoc's option -p to add new packages.\n"; printf "\\usepackage{tipa}\n"; printf "\n" let header () = if !header_trailer then begin printf "\\documentclass[12pt]{report}\n"; if !inputenc != "" then printf "\\usepackage[%s]{inputenc}\n" !inputenc; if !inputenc = "utf8x" then utf8x_extra_support (); printf "\\usepackage[T1]{fontenc}\n"; printf "\\usepackage{fullpage}\n"; printf "\\usepackage{coqdoc}\n"; printf "\\usepackage{amsmath,amssymb}\n"; printf "\\usepackage{url}\n"; (match !toc_depth with | None -> () | Some n -> printf "\\setcounter{tocdepth}{%i}\n" n); Queue.iter (fun s -> printf "%s\n" s) preamble; printf "\\begin{document}\n" end; output_string "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; output_string "%% This file has been automatically generated with the command\n"; output_string "%% "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf "\n"; output_string "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" let trailer () = if !header_trailer then begin printf "\\end{document}\n" end let nbsp () = output_char '~' let char c = match c with | '\\' -> printf "\\symbol{92}" | '$' | '#' | '%' | '&' | '{' | '}' | '_' -> output_char '\\'; output_char c | '^' | '~' -> output_char '\\'; output_char c; printf "{}" | _ -> output_char c let label_char c = match c with | '_' -> output_char ' ' | '\\' | '$' | '#' | '%' | '&' | '{' | '}' | '^' | '~' -> printf "x%X" (Char.code c) | _ -> if c >= '\x80' then printf "x%X" (Char.code c) else output_char c let label_ident s = for i = 0 to String.length s - 1 do label_char s.[i] done let latex_char = output_char let latex_string = output_string let html_char _ = () let html_string _ = () let escaped = let buff = Buffer.create 5 in fun s -> Buffer.clear buff; for i = 0 to String.length s - 1 do match s.[i] with | '\\' -> Buffer.add_string buff "\\symbol{92}" | '$' | '#' | '%' | '&' | '{' | '}' | '_' as c -> Buffer.add_char buff '\\'; Buffer.add_char buff c | '^' | '~' as c -> Buffer.add_char buff '\\'; Buffer.add_char buff c; Buffer.add_string buff "{}" | '\'' -> if i < String.length s - 1 && s.[i+1] = '\'' then begin Buffer.add_char buff '\''; Buffer.add_char buff '{'; Buffer.add_char buff '}' end else Buffer.add_char buff '\'' | c -> Buffer.add_char buff c done; Buffer.contents buff let start_module () = let ln = !lib_name in if not !short then begin printf "\\coqlibrary{"; label_ident (get_module false); printf "}{"; if ln <> "" then printf "%s " ln; printf "}{%s}\n\n" (escaped (get_module true)) end let start_latex_math () = output_char '$' let stop_latex_math () = output_char '$' let start_quote () = output_char '`'; output_char '`' let stop_quote () = output_char '\''; output_char '\'' let start_verbatim inline = if inline then printf "\\texttt{" else printf "\\begin{verbatim}" let stop_verbatim inline = if inline then printf "}" else printf "\\end{verbatim}\n" let url addr name = printf "%s\\footnote{\\url{%s}}" (match name with | None -> "" | Some n -> n) addr let indentation n = if n == 0 then printf "\\coqdocnoindent\n" else let space = 0.5 *. (float n) in printf "\\coqdocindent{%2.2fem}\n" space let ident_ref m fid typ s = let id = if fid <> "" then (m ^ "." ^ fid) else m in match find_module m with | Local -> if typ = Variable then printf "\\coqdoc%s{%s}" (type_name typ) s else (printf "\\coqref{"; label_ident id; printf "}{\\coqdoc%s{%s}}" (type_name typ) s) | External m when !externals -> printf "\\coqexternalref{"; label_ident fid; printf "}{%s}{\\coqdoc%s{%s}}" (escaped m) (type_name typ) s | External _ | Unknown -> printf "\\coqdoc%s{%s}" (type_name typ) s let defref m id ty s = if ty <> Notation then (printf "\\coqdef{"; label_ident (m ^ "." ^ id); printf "}{%s}{\\coqdoc%s{%s}}" s (type_name ty) s) else Glob file still not able to say the exact extent of the definition (printf "\\coqdef{"; label_ident (m ^ "." ^ id); printf "}{%s}{%s}" s s) let reference s = function | Def (fullid,typ) -> defref (get_module false) fullid typ s | Ref (m,fullid,typ) -> ident_ref m fullid typ s s The sublexer buffers symbol characters and attached uninterpreted ident and try to apply special translation such as , predefined , translation " - > " to " \ensuremath{\rightarrow } " or , virtually , a user - level translation from " = _ h " to " \ensuremath{=_{h } } " uninterpreted ident and try to apply special translation such as, predefined, translation "->" to "\ensuremath{\rightarrow}" or, virtually, a user-level translation from "=_h" to "\ensuremath{=_{h}}" *) let output_sublexer_string doescape issymbchar tag s = let s = if doescape then escaped s else s in match tag with | Some ref -> reference s ref | None -> if issymbchar then output_string s else printf "\\coqdocvar{%s}" s let last_was_in = ref false let sublexer c loc = if c = '*' && !last_was_in then begin Tokens.flush_sublexer (); output_char '*' end else begin let tag = try Some (Index.find (get_module false) loc) with Not_found -> None in Tokens.output_tagged_symbol_char tag c end; last_was_in := false let sublexer_in_doc c = if c = '*' && !last_was_in then begin Tokens.flush_sublexer (); output_char '*' end else Tokens.output_tagged_symbol_char None c; last_was_in := false let initialize () = initialize_tex_html (); Tokens.token_tree := token_tree_latex; Tokens.outfun := output_sublexer_string let translate s = match Tokens.translate s with Some s -> s | None -> escaped s let keyword s loc = printf "\\coqdockw{%s}" (translate s) let ident s loc = last_was_in := s = "in"; try match loc with | None -> raise Not_found | Some loc -> let tag = Index.find (get_module false) loc in reference (translate s) tag with Not_found -> if is_tactic s then printf "\\coqdoctac{%s}" (translate s) else if is_keyword s then printf "\\coqdockw{%s}" (translate s) then try let tag = Index.find_string (get_module false) s in reference (translate s) tag with _ -> Tokens.output_tagged_ident_string s else Tokens.output_tagged_ident_string s let ident s l = if !in_title then ( printf "\\texorpdfstring{\\protect"; ident s l; printf "}{%s}" (translate s)) else ident s l let proofbox () = printf "\\ensuremath{\\Box}" let rec reach_item_level n = if !item_level < n then begin printf "\n\\begin{itemize}\n\\item "; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n\\end{itemize}\n"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n\\item " let stop_item () = reach_item_level 0 let start_doc () = in_doc := true let end_doc () = in_doc := false; stop_item () let start_emph () = printf "\\textit{" let stop_emph () = printf "}" let start_comment () = printf "\\begin{coqdoccomment}\n" let end_comment () = printf "\\end{coqdoccomment}\n" let start_coq () = printf "\\begin{coqdoccode}\n" let end_coq () = printf "\\end{coqdoccode}\n" let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let section_kind = function | 1 -> "\\section{" | 2 -> "\\subsection{" | 3 -> "\\subsubsection{" | 4 -> "\\paragraph{" | _ -> assert false let section lev f = stop_item (); output_string (section_kind lev); in_title := true; f (); in_title := false; printf "}\n\n" let rule () = printf "\\par\n\\noindent\\hrulefill\\par\n\\noindent{}" let paragraph () = printf "\n\n" let line_break () = printf "\\coqdoceol\n" let empty_line_of_code () = printf "\\coqdocemptyline\n" let start_inline_coq_block () = line_break (); empty_line_of_code () let end_inline_coq_block () = empty_line_of_code () let start_inline_coq () = () let end_inline_coq () = () let make_multi_index () = () let make_index () = () let make_toc () = printf "\\tableofcontents\n" end module Html = struct let header () = if !header_trailer then if !header_file_spec then let cin = Pervasives.open_in !header_file in try while true do let s = Pervasives.input_line cin in printf "%s\n" s done with End_of_file -> Pervasives.close_in cin else begin printf "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"; printf "\"-strict.dtd\">\n"; printf "<html xmlns=\"\">\n<head>\n"; printf "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\" />\n" !charset; printf "<link href=\"coqdoc.css\" rel=\"stylesheet\" type=\"text/css\" />\n"; printf "<title>%s</title>\n</head>\n\n" !page_title; printf "<body>\n\n<div id=\"page\">\n\n<div id=\"header\">\n</div>\n\n"; printf "<div id=\"main\">\n\n" end let trailer () = if !header_trailer && !footer_file_spec then let cin = Pervasives.open_in !footer_file in try while true do let s = Pervasives.input_line cin in printf "%s\n" s done with End_of_file -> Pervasives.close_in cin else begin if !index && (get_module false) <> "Index" then printf "</div>\n\n<div id=\"footer\">\n<hr/><a href=\"%s.html\">Index</a>" !index_name; printf "<hr/>This page has been generated by "; printf "<a href=\"%s\">coqdoc</a>\n" Coq_config.wwwcoq; printf "</div>\n\n</div>\n\n</body>\n</html>" end let start_module () = let ln = !lib_name in if not !short then begin let (m,sub) = !current_module in add_toc_entry (Toc_library (m,sub)); if ln = "" then printf "<h1 class=\"libtitle\">%s</h1>\n\n" (get_module true) else printf "<h1 class=\"libtitle\">%s %s</h1>\n\n" ln (get_module true) end let indentation n = for _i = 1 to n do printf "&nbsp;" done let line_break () = printf "<br/>\n" let empty_line_of_code () = printf "\n<br/>\n" let nbsp () = printf "&nbsp;" let char = function | '<' -> printf "&lt;" | '>' -> printf "&gt;" | '&' -> printf "&amp;" | c -> output_char c let escaped = let buff = Buffer.create 5 in fun s -> Buffer.clear buff; for i = 0 to String.length s - 1 do match s.[i] with | '<' -> Buffer.add_string buff "&lt;" | '>' -> Buffer.add_string buff "&gt;" | '&' -> Buffer.add_string buff "&amp;" | '\'' -> Buffer.add_string buff "&acute;" | '\"' -> Buffer.add_string buff "&quot;" | c -> Buffer.add_char buff c done; Buffer.contents buff let sanitize_name s = let rec loop esc i = if i < 0 then if esc then escaped s else s else match s.[i] with | 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '_' -> loop esc (i-1) | '<' | '>' | '&' | '\'' | '\"' -> loop true (i-1) | _ -> Digest.to_hex (Digest.string s) in loop false (String.length s - 1) let latex_char _ = () let latex_string _ = () let html_char = output_char let html_string = output_string let start_latex_math () = () let stop_latex_math () = () let start_quote () = char '"' let stop_quote () = start_quote () let start_verbatim inline = if inline then printf "<tt>" else printf "<pre>" let stop_verbatim inline = if inline then printf "</tt>" else printf "</pre>\n" let url addr name = printf "<a href=\"%s\">%s</a>" addr (match name with | Some n -> n | None -> addr) let ident_ref m fid typ s = match find_module m with | Local -> printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s | External m when !externals -> printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s | External _ | Unknown -> printf "<span class=\"id\" title=\"%s\">%s</span>" typ s let reference s r = match r with | Def (fullid,ty) -> printf "<a name=\"%s\">" (sanitize_name fullid); printf "<span class=\"id\" title=\"%s\">%s</span></a>" (type_name ty) s | Ref (m,fullid,ty) -> ident_ref m fullid (type_name ty) s let output_sublexer_string doescape issymbchar tag s = let s = if doescape then escaped s else s in match tag with | Some ref -> reference s ref | None -> if issymbchar then output_string s else printf "<span class=\"id\" title=\"var\">%s</span>" s let sublexer c loc = let tag = try Some (Index.find (get_module false) loc) with Not_found -> None in Tokens.output_tagged_symbol_char tag c let sublexer_in_doc c = Tokens.output_tagged_symbol_char None c let initialize () = initialize_tex_html(); Tokens.token_tree := token_tree_html; Tokens.outfun := output_sublexer_string let translate s = match Tokens.translate s with Some s -> s | None -> escaped s let keyword s loc = printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s) let ident s loc = if is_keyword s then begin printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s) end else begin try match loc with | None -> raise Not_found | Some loc -> reference (translate s) (Index.find (get_module false) loc) with Not_found -> if is_tactic s then printf "<span class=\"id\" title=\"tactic\">%s</span>" (translate s) else then try reference (translate s) (Index.find_string (get_module false) s) with _ -> Tokens.output_tagged_ident_string s else Tokens.output_tagged_ident_string s end let proofbox () = printf "<font size=-2>&#9744;</font>" let rec reach_item_level n = if !item_level < n then begin printf "<ul class=\"doclist\">\n<li>"; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n</li>\n</ul>\n"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n</li>\n<li>" let stop_item () = reach_item_level 0 let start_coq () = if not !raw_comments then printf "<div class=\"code\">\n" let end_coq () = if not !raw_comments then printf "</div>\n" let start_doc () = in_doc := true; if not !raw_comments then printf "\n<div class=\"doc\">\n" let end_doc () = in_doc := false; stop_item (); if not !raw_comments then printf "\n</div>\n" let start_emph () = printf "<i>" let stop_emph () = printf "</i>" let start_comment () = printf "<span class=\"comment\">(*" let end_comment () = printf "*)</span>" let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let start_inline_coq () = if !inline_notmono then printf "<span class=\"inlinecodenm\">" else printf "<span class=\"inlinecode\">" let end_inline_coq () = printf "</span>" let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let paragraph () = printf "\n<div class=\"paragraph\"> </div>\n\n" let inf_rule assumptions (_,_,midnm) conclusions = this first function replaces any occurance of 3 or more spaces in a row with " & nbsp;"s . We do this to the assumptions so that people can put multiple rules on a line with nice formatting in a row with "&nbsp;"s. We do this to the assumptions so that people can put multiple rules on a line with nice formatting *) let replace_spaces str = let rec copy a n = match n with 0 -> [] | n -> (a :: copy a (n - 1)) in let results = Str.full_split (Str.regexp "[' '][' '][' ']+") str in let strs = List.map (fun r -> match r with | Str.Text s -> [s] | Str.Delim s -> copy "&nbsp;" (String.length s)) results in String.concat "" (List.concat strs) in let start_assumption line = (printf "<tr class=\"infruleassumption\">\n"; printf " <td class=\"infrule\">%s</td>\n" (replace_spaces line)) in let end_assumption () = (printf " <td></td>\n"; printf "</td>\n") in let rec print_assumptions hyps = match hyps with | [] -> start_assumption "&nbsp;&nbsp;" | [(_,hyp)] -> start_assumption hyp | ((_,hyp) :: hyps') -> (start_assumption hyp; end_assumption (); print_assumptions hyps') in printf "<center><table class=\"infrule\">\n"; print_assumptions assumptions; printf " <td class=\"infrulenamecol\" rowspan=\"3\">\n"; (match midnm with | None -> printf " &nbsp;\n </td>" | Some s -> printf " %s &nbsp;\n </td>" s); printf "</tr>\n"; printf "<tr class=\"infrulemiddle\">\n"; printf " <td class=\"infrule\"><hr /></td>\n"; printf "</tr>\n"; print_assumptions conclusions; end_assumption (); printf "</table></center>" let section lev f = let lab = new_label () in let r = sprintf "%s.html#%s" (get_module false) lab in (match !toc_depth with | None -> add_toc_entry (Toc_section (lev, f, r)) | Some n -> if lev <= n then add_toc_entry (Toc_section (lev, f, r)) else ()); stop_item (); printf "<a name=\"%s\"></a><h%d class=\"section\">" lab lev; f (); printf "</h%d>\n" lev let rule () = printf "<hr/>\n" let index_ref i c = let idxc = sprintf "%s_%c" i.idx_name c in !index_name ^ (if !multi_index then "_" ^ idxc ^ ".html" else ".html#" ^ idxc) let letter_index category idx (c,l) = if l <> [] then begin let cat = if category && idx <> "global" then "(" ^ idx ^ ")" else "" in printf "<a name=\"%s_%c\"></a><h2>%s %s</h2>\n" idx c (display_letter c) cat; List.iter (fun (id,(text,link,t)) -> let id' = prepare_entry id t in printf "<a href=\"%s\">%s</a> %s<br/>\n" link id' text) l; printf "<br/><br/>" end let all_letters i = List.iter (letter_index false i.idx_name) i.idx_entries Construction d'une liste des index ( 1 index global , puis 1 index par catégorie ) index par catégorie) *) let format_global_index = Index.map (fun s (m,t) -> if t = Library then let ln = !lib_name in if ln <> "" then "[" ^ String.lowercase ln ^ "]", m ^ ".html", t else "[library]", m ^ ".html", t else sprintf "[%s, in <a href=\"%s.html\">%s</a>]" (type_name t) m m , sprintf "%s.html#%s" m (sanitize_name s), t) let format_bytype_index = function | Library, idx -> Index.map (fun id m -> "", m ^ ".html", Library) idx | (t,idx) -> Index.map (fun s m -> let text = sprintf "[in <a href=\"%s.html\">%s</a>]" m m in (text, sprintf "%s.html#%s" m (sanitize_name s), t)) idx Impression de la table d'index let print_index_table_item i = printf "<tr>\n<td>%s Index</td>\n" (String.capitalize i.idx_name); List.iter (fun (c,l) -> if l <> [] then printf "<td><a href=\"%s\">%s</a></td>\n" (index_ref i c) (display_letter c) else printf "<td>%s</td>\n" (display_letter c)) i.idx_entries; let n = i.idx_size in printf "<td>(%d %s)</td>\n" n (if n > 1 then "entries" else "entry"); printf "</tr>\n" let print_index_table idxl = printf "<table>\n"; List.iter print_index_table_item idxl; printf "</table>\n" let make_one_multi_index prt_tbl i = Attn : make_one_multi_index ... let idx = i.idx_name in let one_letter ((c,l) as cl) = open_out_file (sprintf "%s_%s_%c.html" !index_name idx c); if (!header_trailer) then header (); prt_tbl (); printf "<hr/>"; letter_index true idx cl; if List.length l > 30 then begin printf "<hr/>"; prt_tbl () end; if (!header_trailer) then trailer (); close_out_file () in List.iter one_letter i.idx_entries let make_multi_index () = let all_index = let glob,bt = Index.all_entries () in (format_global_index glob) :: (List.map format_bytype_index bt) in let print_table () = print_index_table all_index in List.iter (make_one_multi_index print_table) all_index let make_index () = let all_index = let glob,bt = Index.all_entries () in (format_global_index glob) :: (List.map format_bytype_index bt) in let print_table () = print_index_table all_index in let print_one_index i = if i.idx_size > 0 then begin printf "<hr/>\n<h1>%s Index</h1>\n" (String.capitalize i.idx_name); all_letters i end in set_module "Index" None; if !title <> "" then printf "<h1>%s</h1>\n" !title; print_table (); if not (!multi_index) then begin List.iter print_one_index all_index; printf "<hr/>"; print_table () end let make_toc () = let ln = !lib_name in let make_toc_entry = function | Toc_library (m,sub) -> stop_item (); let ms = match sub with | None -> m | Some s -> m ^ ": " ^ s in if ln = "" then printf "<a href=\"%s.html\"><h2>%s</h2></a>\n" m ms else printf "<a href=\"%s.html\"><h2>%s %s</h2></a>\n" m ln ms | Toc_section (n, f, r) -> item n; printf "<a href=\"%s\">" r; f (); printf "</a>\n" in printf "<div id=\"toc\">\n"; Queue.iter make_toc_entry toc_q; stop_item (); printf "</div>\n" end module TeXmacs = struct let (preamble : string Queue.t) = in_doc := false; Queue.create () let header () = output_string "(*i This file has been automatically generated with the command \n"; output_string " "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf " *)\n" let trailer () = () let nbsp () = output_char ' ' let char_true c = match c with | '\\' -> printf "\\\\" | '<' -> printf "\\<" | '|' -> printf "\\|" | '>' -> printf "\\>" | _ -> output_char c let char c = if !in_doc then char_true c else output_char c let latex_char = char_true let latex_string = String.iter latex_char let html_char _ = () let html_string _ = () let raw_ident s = for i = 0 to String.length s - 1 do char s.[i] done let start_module () = () let start_latex_math () = printf "<with|mode|math|" let stop_latex_math () = output_char '>' let start_verbatim inline = in_doc := true; printf "<\\verbatim>" let stop_verbatim inline = in_doc := false; printf "</verbatim>" let url addr name = printf "%s<\\footnote><\\url>%s</url></footnote>" addr (match name with | None -> "" | Some n -> n) let start_quote () = output_char '`'; output_char '`' let stop_quote () = output_char '\''; output_char '\'' let indentation n = () let keyword s = printf "<kw|"; raw_ident s; printf ">" let ident_true s = if is_keyword s then keyword s else raw_ident s let keyword s loc = keyword s let ident s _ = if !in_doc then ident_true s else raw_ident s let output_sublexer_string doescape issymbchar tag s = if doescape then raw_ident s else output_string s let sublexer c l = if !in_doc then Tokens.output_tagged_symbol_char None c else char c let sublexer_in_doc c = char c let initialize () = Tokens.token_tree := token_tree_texmacs; Tokens.outfun := output_sublexer_string let proofbox () = printf "QED" let rec reach_item_level n = if !item_level < n then begin printf "\n<\\itemize>\n<item>"; incr item_level; reach_item_level n end else if !item_level > n then begin printf "\n</itemize>"; decr item_level; reach_item_level n end let item n = let old_level = !item_level in reach_item_level n; if n <= old_level then printf "\n\n<item>" let stop_item () = reach_item_level 0 let start_doc () = in_doc := true; printf "(** texmacs: " let end_doc () = stop_item (); in_doc := false; printf " *)" let start_coq () = () let end_coq () = () let start_emph () = printf "<with|font shape|italic|" let stop_emph () = printf ">" let start_comment () = () let end_comment () = () let start_code () = in_doc := true; printf "<\\code>\n" let end_code () = in_doc := false; printf "\n</code>" let section_kind = function | 1 -> "section" | 2 -> "subsection" | 3 -> "subsubsection" | 4 -> "paragraph" | _ -> assert false let section lev f = stop_item (); printf "<"; output_string (section_kind lev); printf "|"; f (); printf ">\n\n" let rule () = printf "\n<hrule>\n" let paragraph () = printf "\n\n" let line_break () = printf "\n" let empty_line_of_code () = printf "\n" let start_inline_coq () = printf "<verbatim|[" let end_inline_coq () = printf "]>" let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let make_multi_index () = () let make_index () = () let make_toc () = () end module Raw = struct let header () = () let trailer () = () let nbsp () = output_char ' ' let char = output_char let latex_char = output_char let latex_string = output_string let html_char _ = () let html_string _ = () let raw_ident s = for i = 0 to String.length s - 1 do char s.[i] done let start_module () = () let end_module () = () let start_latex_math () = () let stop_latex_math () = () let start_verbatim inline = () let stop_verbatim inline = () let url addr name = match name with | Some n -> printf "%s (%s)" n addr | None -> printf "%s" addr let start_quote () = printf "\"" let stop_quote () = printf "\"" let indentation n = for _i = 1 to n do printf " " done let keyword s loc = raw_ident s let ident s loc = raw_ident s let sublexer c l = char c let sublexer_in_doc c = char c let initialize () = Tokens.token_tree := ref Tokens.empty_ttree; Tokens.outfun := (fun _ _ _ _ -> failwith "Useless") let proofbox () = printf "[]" let item n = printf "- " let stop_item () = () let reach_item_level _ = () let start_doc () = printf "(** " let end_doc () = printf " *)\n" let start_emph () = printf "_" let stop_emph () = printf "_" let start_comment () = printf "(*" let end_comment () = printf "*)" let start_coq () = () let end_coq () = () let start_code () = end_doc (); start_coq () let end_code () = end_coq (); start_doc () let section_kind = function | 1 -> "* " | 2 -> "** " | 3 -> "*** " | 4 -> "**** " | _ -> assert false let section lev f = output_string (section_kind lev); f () let rule () = () let paragraph () = printf "\n\n" let line_break () = printf "\n" let empty_line_of_code () = printf "\n" let start_inline_coq () = () let end_inline_coq () = () let start_inline_coq_block () = line_break (); start_inline_coq () let end_inline_coq_block () = end_inline_coq () let make_multi_index () = () let make_index () = () let make_toc () = () end let select f1 f2 f3 f4 x = match !target_language with LaTeX -> f1 x | HTML -> f2 x | TeXmacs -> f3 x | Raw -> f4 x let push_in_preamble = Latex.push_in_preamble let header = select Latex.header Html.header TeXmacs.header Raw.header let trailer = select Latex.trailer Html.trailer TeXmacs.trailer Raw.trailer let start_module = select Latex.start_module Html.start_module TeXmacs.start_module Raw.start_module let start_doc = select Latex.start_doc Html.start_doc TeXmacs.start_doc Raw.start_doc let end_doc = select Latex.end_doc Html.end_doc TeXmacs.end_doc Raw.end_doc let start_comment = select Latex.start_comment Html.start_comment TeXmacs.start_comment Raw.start_comment let end_comment = select Latex.end_comment Html.end_comment TeXmacs.end_comment Raw.end_comment let start_coq = select Latex.start_coq Html.start_coq TeXmacs.start_coq Raw.start_coq let end_coq = select Latex.end_coq Html.end_coq TeXmacs.end_coq Raw.end_coq let start_code = select Latex.start_code Html.start_code TeXmacs.start_code Raw.start_code let end_code = select Latex.end_code Html.end_code TeXmacs.end_code Raw.end_code let start_inline_coq = select Latex.start_inline_coq Html.start_inline_coq TeXmacs.start_inline_coq Raw.start_inline_coq let end_inline_coq = select Latex.end_inline_coq Html.end_inline_coq TeXmacs.end_inline_coq Raw.end_inline_coq let start_inline_coq_block = select Latex.start_inline_coq_block Html.start_inline_coq_block TeXmacs.start_inline_coq_block Raw.start_inline_coq_block let end_inline_coq_block = select Latex.end_inline_coq_block Html.end_inline_coq_block TeXmacs.end_inline_coq_block Raw.end_inline_coq_block let indentation = select Latex.indentation Html.indentation TeXmacs.indentation Raw.indentation let paragraph = select Latex.paragraph Html.paragraph TeXmacs.paragraph Raw.paragraph let line_break = select Latex.line_break Html.line_break TeXmacs.line_break Raw.line_break let empty_line_of_code = select Latex.empty_line_of_code Html.empty_line_of_code TeXmacs.empty_line_of_code Raw.empty_line_of_code let section = select Latex.section Html.section TeXmacs.section Raw.section let item = select Latex.item Html.item TeXmacs.item Raw.item let stop_item = select Latex.stop_item Html.stop_item TeXmacs.stop_item Raw.stop_item let reach_item_level = select Latex.reach_item_level Html.reach_item_level TeXmacs.reach_item_level Raw.reach_item_level let rule = select Latex.rule Html.rule TeXmacs.rule Raw.rule let nbsp = select Latex.nbsp Html.nbsp TeXmacs.nbsp Raw.nbsp let char = select Latex.char Html.char TeXmacs.char Raw.char let keyword = select Latex.keyword Html.keyword TeXmacs.keyword Raw.keyword let ident = select Latex.ident Html.ident TeXmacs.ident Raw.ident let sublexer = select Latex.sublexer Html.sublexer TeXmacs.sublexer Raw.sublexer let sublexer_in_doc = select Latex.sublexer_in_doc Html.sublexer_in_doc TeXmacs.sublexer_in_doc Raw.sublexer_in_doc let initialize = select Latex.initialize Html.initialize TeXmacs.initialize Raw.initialize let proofbox = select Latex.proofbox Html.proofbox TeXmacs.proofbox Raw.proofbox let latex_char = select Latex.latex_char Html.latex_char TeXmacs.latex_char Raw.latex_char let latex_string = select Latex.latex_string Html.latex_string TeXmacs.latex_string Raw.latex_string let html_char = select Latex.html_char Html.html_char TeXmacs.html_char Raw.html_char let html_string = select Latex.html_string Html.html_string TeXmacs.html_string Raw.html_string let start_emph = select Latex.start_emph Html.start_emph TeXmacs.start_emph Raw.start_emph let stop_emph = select Latex.stop_emph Html.stop_emph TeXmacs.stop_emph Raw.stop_emph let start_latex_math = select Latex.start_latex_math Html.start_latex_math TeXmacs.start_latex_math Raw.start_latex_math let stop_latex_math = select Latex.stop_latex_math Html.stop_latex_math TeXmacs.stop_latex_math Raw.stop_latex_math let start_verbatim = select Latex.start_verbatim Html.start_verbatim TeXmacs.start_verbatim Raw.start_verbatim let stop_verbatim = select Latex.stop_verbatim Html.stop_verbatim TeXmacs.stop_verbatim Raw.stop_verbatim let verbatim_char inline = select (if inline then Latex.char else output_char) Html.char TeXmacs.char Raw.char let hard_verbatim_char = output_char let url = select Latex.url Html.url TeXmacs.url Raw.url let start_quote = select Latex.start_quote Html.start_quote TeXmacs.start_quote Raw.start_quote let stop_quote = select Latex.stop_quote Html.stop_quote TeXmacs.stop_quote Raw.stop_quote let inf_rule_dumb assumptions (midsp,midln,midnm) conclusions = start_verbatim false; let dumb_line = function (sp,ln) -> (String.iter char ((String.make sp ' ') ^ ln); char '\n') in (List.iter dumb_line assumptions; dumb_line (midsp, midln ^ (match midnm with | Some s -> " " ^ s | None -> "")); List.iter dumb_line conclusions); stop_verbatim false let inf_rule = select inf_rule_dumb Html.inf_rule inf_rule_dumb inf_rule_dumb let make_multi_index = select Latex.make_multi_index Html.make_multi_index TeXmacs.make_multi_index Raw.make_multi_index let make_index = select Latex.make_index Html.make_index TeXmacs.make_index Raw.make_index let make_toc = select Latex.make_toc Html.make_toc TeXmacs.make_toc Raw.make_toc
6737a66b50ed8502d48a3a9ee80f7c4ef6b5d2409cabe51534b9a1e7a2b62e76
oshyshko/uio
xz.clj
(ns uio.codecs.xz (:require [uio.impl :refer [ext->is->is ext->os->os]]) (:import (org.apache.commons.compress.compressors CompressorStreamFactory))) (defmethod ext->is->is :xz [_] #(.createCompressorInputStream (CompressorStreamFactory.) CompressorStreamFactory/XZ %)) (defmethod ext->os->os :xz [_] #(.createCompressorOutputStream (CompressorStreamFactory.) CompressorStreamFactory/XZ %))
null
https://raw.githubusercontent.com/oshyshko/uio/4e73ec5da0be1764e449ccc86e567ec701862332/src/uio/codecs/xz.clj
clojure
(ns uio.codecs.xz (:require [uio.impl :refer [ext->is->is ext->os->os]]) (:import (org.apache.commons.compress.compressors CompressorStreamFactory))) (defmethod ext->is->is :xz [_] #(.createCompressorInputStream (CompressorStreamFactory.) CompressorStreamFactory/XZ %)) (defmethod ext->os->os :xz [_] #(.createCompressorOutputStream (CompressorStreamFactory.) CompressorStreamFactory/XZ %))
eaf6b58cf56f732c32d04e9e58a913d6a6b016749188fbf9a0f0f9e95a461ae6
fyquah/hardcaml_zprize
stream.ml
open Base open Hardcaml open Stream_intf open Signal module type S = S module Make (X : Config.S) = struct open X let tkeep_bits = data_bits / 8 let tstrb_bits = data_bits / 8 module Source = struct type 'a t = { tvalid : 'a ; tdata : 'a [@bits data_bits] ; tkeep : 'a [@bits tkeep_bits] ; tstrb : 'a [@bits tstrb_bits] ; tlast : 'a } [@@deriving sexp_of, hardcaml] let assign_all_but_tvalid { tvalid = _; tdata; tkeep; tstrb; tlast } src = let open Always in proc [ tdata <-- src.tdata ; tkeep <-- src.tkeep ; tstrb <-- src.tstrb ; tlast <-- src.tlast ] ;; end module Dest = struct type 'a t = { tready : 'a } [@@deriving sexp_of, hardcaml] end (* This is a port of the skid buffer as per * -axis/blob/master/rtl/axis_register.v#L91 *) module Register = struct module I = struct type 'a t = { clock : 'a ; clear : 'a ; up : 'a Source.t [@rtlprefix "up$"] ; dn_dest : 'a Dest.t [@rtlprefix "dn$"] } [@@deriving sexp_of, hardcaml] end module O = struct type 'a t = { dn : 'a Source.t [@rtlprefix "dn$"] ; up_dest : 'a Dest.t [@rtlprefix "up$"] } [@@deriving sexp_of, hardcaml] end let create _scope { I.clock; clear; up; dn_dest } = let spec = Reg_spec.create ~clock ~clear () in let s_axis = up in let m_axis_dest = dn_dest in let temp_m_axis_tvalid_reg = Always.Variable.reg ~width:1 spec in let m_axis_reg = Source.Of_always.reg spec in let s_axis_tready_reg = Always.Variable.reg ~width:1 spec in let temp_m_axis_reg = Source.Of_always.reg spec in let m_axis_tvalid_next = Always.Variable.wire ~default:m_axis_reg.tvalid.value in let temp_m_axis_tvalid_next = Always.Variable.wire ~default:temp_m_axis_tvalid_reg.value in let store_axis_input_to_output = Always.Variable.wire ~default:gnd in let store_axis_input_to_temp = Always.Variable.wire ~default:gnd in let store_axis_temp_to_output = Always.Variable.wire ~default:gnd in let s_axis_tready_early = m_axis_dest.tready |: (~:(temp_m_axis_tvalid_reg.value) &: ~:(m_axis_reg.tvalid.value)) in (* Combinational updates. *) Always.( compile [ if_ s_axis_tready_reg.value [ if_ (m_axis_dest.tready |: ~:(m_axis_reg.tvalid.value)) [ m_axis_tvalid_next <-- s_axis.tvalid ; store_axis_input_to_output <--. 1 ] @@ [ temp_m_axis_tvalid_next <-- s_axis.tvalid ; store_axis_input_to_temp <--. 1 ] ] @@ elif m_axis_dest.tready [ m_axis_tvalid_next <-- temp_m_axis_tvalid_reg.value ; temp_m_axis_tvalid_next <--. 0 ; store_axis_temp_to_output <--. 1 ] @@ [ (* Do nothing *) ] ]); Register updates . Always.( compile [ s_axis_tready_reg <-- s_axis_tready_early ; m_axis_reg.tvalid <-- m_axis_tvalid_next.value ; temp_m_axis_tvalid_reg <-- temp_m_axis_tvalid_next.value ; if_ store_axis_input_to_output.value [ Source.assign_all_but_tvalid m_axis_reg s_axis ] @@ elif store_axis_temp_to_output.value [ Source.assign_all_but_tvalid m_axis_reg (Source.Of_always.value temp_m_axis_reg) ] @@ [ (* Do nothing *) ] ; when_ store_axis_input_to_temp.value [ Source.Of_always.assign temp_m_axis_reg s_axis ] ]); { O.dn = Source.Of_always.value m_axis_reg ; up_dest = { tready = s_axis_tready_reg.value } } ;; let hierarchical scope i = let module H = Hierarchy.In_scope (I) (O) in H.hierarchical ~name:"axis_register" ~scope create i ;; end end
null
https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/hardcaml_axi/src/stream.ml
ocaml
This is a port of the skid buffer as per * -axis/blob/master/rtl/axis_register.v#L91 Combinational updates. Do nothing Do nothing
open Base open Hardcaml open Stream_intf open Signal module type S = S module Make (X : Config.S) = struct open X let tkeep_bits = data_bits / 8 let tstrb_bits = data_bits / 8 module Source = struct type 'a t = { tvalid : 'a ; tdata : 'a [@bits data_bits] ; tkeep : 'a [@bits tkeep_bits] ; tstrb : 'a [@bits tstrb_bits] ; tlast : 'a } [@@deriving sexp_of, hardcaml] let assign_all_but_tvalid { tvalid = _; tdata; tkeep; tstrb; tlast } src = let open Always in proc [ tdata <-- src.tdata ; tkeep <-- src.tkeep ; tstrb <-- src.tstrb ; tlast <-- src.tlast ] ;; end module Dest = struct type 'a t = { tready : 'a } [@@deriving sexp_of, hardcaml] end module Register = struct module I = struct type 'a t = { clock : 'a ; clear : 'a ; up : 'a Source.t [@rtlprefix "up$"] ; dn_dest : 'a Dest.t [@rtlprefix "dn$"] } [@@deriving sexp_of, hardcaml] end module O = struct type 'a t = { dn : 'a Source.t [@rtlprefix "dn$"] ; up_dest : 'a Dest.t [@rtlprefix "up$"] } [@@deriving sexp_of, hardcaml] end let create _scope { I.clock; clear; up; dn_dest } = let spec = Reg_spec.create ~clock ~clear () in let s_axis = up in let m_axis_dest = dn_dest in let temp_m_axis_tvalid_reg = Always.Variable.reg ~width:1 spec in let m_axis_reg = Source.Of_always.reg spec in let s_axis_tready_reg = Always.Variable.reg ~width:1 spec in let temp_m_axis_reg = Source.Of_always.reg spec in let m_axis_tvalid_next = Always.Variable.wire ~default:m_axis_reg.tvalid.value in let temp_m_axis_tvalid_next = Always.Variable.wire ~default:temp_m_axis_tvalid_reg.value in let store_axis_input_to_output = Always.Variable.wire ~default:gnd in let store_axis_input_to_temp = Always.Variable.wire ~default:gnd in let store_axis_temp_to_output = Always.Variable.wire ~default:gnd in let s_axis_tready_early = m_axis_dest.tready |: (~:(temp_m_axis_tvalid_reg.value) &: ~:(m_axis_reg.tvalid.value)) in Always.( compile [ if_ s_axis_tready_reg.value [ if_ (m_axis_dest.tready |: ~:(m_axis_reg.tvalid.value)) [ m_axis_tvalid_next <-- s_axis.tvalid ; store_axis_input_to_output <--. 1 ] @@ [ temp_m_axis_tvalid_next <-- s_axis.tvalid ; store_axis_input_to_temp <--. 1 ] ] @@ elif m_axis_dest.tready [ m_axis_tvalid_next <-- temp_m_axis_tvalid_reg.value ; temp_m_axis_tvalid_next <--. 0 ; store_axis_temp_to_output <--. 1 ] ]); Register updates . Always.( compile [ s_axis_tready_reg <-- s_axis_tready_early ; m_axis_reg.tvalid <-- m_axis_tvalid_next.value ; temp_m_axis_tvalid_reg <-- temp_m_axis_tvalid_next.value ; if_ store_axis_input_to_output.value [ Source.assign_all_but_tvalid m_axis_reg s_axis ] @@ elif store_axis_temp_to_output.value [ Source.assign_all_but_tvalid m_axis_reg (Source.Of_always.value temp_m_axis_reg) ] ; when_ store_axis_input_to_temp.value [ Source.Of_always.assign temp_m_axis_reg s_axis ] ]); { O.dn = Source.Of_always.value m_axis_reg ; up_dest = { tready = s_axis_tready_reg.value } } ;; let hierarchical scope i = let module H = Hierarchy.In_scope (I) (O) in H.hierarchical ~name:"axis_register" ~scope create i ;; end end
e4197ac4e3353a167d44558432cc28e600ad4908c6b09687dad59f6d60524cae
aumouvantsillage/Virgule-CPU-Racket
virgule.rkt
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 /. #lang racket (require "signal.rkt" "datapath-components.rkt") (provide virgule) An implementation of a minimal RISC - V ( RV32I ) core . ; The interface is inspired by the PicoRV32 ; The sequencer is a state machine. (define (virgule #:reset reset #:rdata rdata #:ready ready #:irq irq) ; ; Sequencer. ; (define state-reg (register/r 'state-fetch reset (for/signal (instr ready [state this-reg]) (match state ['state-fetch (if ready 'state-decode state)] ['state-decode 'state-execute] ['state-execute (cond [(instruction-load? instr) 'state-load] [(instruction-store? instr) 'state-store] [(instruction-has-rd? instr) 'state-writeback] [else 'state-fetch])] ['state-load (if ready 'state-writeback state)] ['state-store (if ready 'state-fetch state)] ['state-writeback 'state-fetch])))) (define (state-equal? sym) (for/signal (state-reg) (equal? state-reg sym))) (define fetch-en (state-equal? 'state-fetch)) (define decode-en (state-equal? 'state-decode)) (define execute-en (state-equal? 'state-execute)) (define load-en (state-equal? 'state-load)) (define store-en (state-equal? 'state-store)) (define writeback-en (state-equal? 'state-writeback)) ; ; Instruction decoding: ; decode, read registers, select ALU operands. ; (define instr (decoder (signal-defer rdata-reg))) (define instr-reg (register/e instr-nop decode-en instr)) (define-values (xs1 xs2) (register-unit #:reset reset #:enable writeback-en #:src-instr instr #:dest-instr instr-reg #:xd (signal-defer xd))) (define xs1-reg (register/e 0 decode-en xs1)) (define xs2-reg (register/e 0 decode-en xs2)) (define alu-a-reg (register/e 0 decode-en (for/signal (instr xs1 pc-reg) (if (instruction-use-pc? instr) pc-reg xs1)))) (define alu-b-reg (register/e 0 decode-en (for/signal (instr xs2) (if (instruction-use-imm? instr) (instruction-imm instr) xs2)))) ; ; Instruction execution: ; compute ALU and comparator results, compute branch address, ; update program counter. ; (define alu-result (arith-logic-unit instr-reg alu-a-reg alu-b-reg)) (define alu-result-reg (register/e 0 execute-en alu-result)) (define pc+4 (>> add4 pc-reg)) (define pc-reg (register/re 0 reset execute-en (branch-unit #:reset reset #:enable execute-en #:irq irq #:instr instr-reg #:xs1 xs1-reg #:xs2 xs2-reg #:address alu-result #:pc+4 pc+4))) (define pc+4-reg (register/e 0 execute-en pc+4)) ; ; Memory access: ; align data to/from memory, drive control outputs. ; (define rdata-reg (register/e 0 (>> and valid ready) rdata)) (define valid (>> or fetch-en store-en load-en)) (define address (>> if fetch-en pc-reg alu-result-reg)) (define-values (wstrobe wdata load-data) (load-store-unit #:instr instr-reg #:address alu-result-reg #:store-enable store-en #:store-data xs2-reg #:rdata rdata-reg)) ; ; Register update. ; (define xd (for/signal (instr-reg load-data pc+4-reg alu-result-reg) (cond [(instruction-load? instr-reg) load-data] [(instruction-jump? instr-reg) pc+4-reg] [else alu-result-reg]))) (values valid address wstrobe wdata)) (module+ test (require rackunit) (require "tests/virgule.rkt") (define (fake-asm data) (if (procedure? data) (data #f #f) (word data))) (define test-count (length test-cases)) (define lst-rdata (map fake-asm (map first test-cases))) (define lst-ready (map second test-cases)) (define lst-irq (map third test-cases)) (define lst-expected (for/list ([c (in-list test-cases)]) (drop c 3))) (define-values (sig-valid sig-address sig-wstrobe sig-wdata) (virgule #:reset (signal #f) #:rdata (list->signal lst-rdata) #:ready (list->signal lst-ready) #:irq (list->signal lst-irq))) (define lst-result (map list (signal-take sig-valid test-count) (signal-take sig-address test-count) (signal-take sig-wstrobe test-count) (signal-take sig-wdata test-count))) (define labels '(valid address wstrobe wdata)) (for ([n test-count] [r (in-list lst-result)] [x (in-list lst-expected)]) (for ([l (in-list labels)] [rv (in-list r)] [xv (in-list x)] #:when (not (equal? 'any xv))) (test-equal? (format "Virgule #~a: ~a" n l) rv xv))))
null
https://raw.githubusercontent.com/aumouvantsillage/Virgule-CPU-Racket/3df9656c48f04fb9488952ededccee38d3c527c7/src/virgule.rkt
racket
The interface is inspired by the PicoRV32 The sequencer is a state machine. Sequencer. Instruction decoding: decode, read registers, select ALU operands. Instruction execution: compute ALU and comparator results, compute branch address, update program counter. Memory access: align data to/from memory, drive control outputs. Register update.
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 /. #lang racket (require "signal.rkt" "datapath-components.rkt") (provide virgule) An implementation of a minimal RISC - V ( RV32I ) core . (define (virgule #:reset reset #:rdata rdata #:ready ready #:irq irq) (define state-reg (register/r 'state-fetch reset (for/signal (instr ready [state this-reg]) (match state ['state-fetch (if ready 'state-decode state)] ['state-decode 'state-execute] ['state-execute (cond [(instruction-load? instr) 'state-load] [(instruction-store? instr) 'state-store] [(instruction-has-rd? instr) 'state-writeback] [else 'state-fetch])] ['state-load (if ready 'state-writeback state)] ['state-store (if ready 'state-fetch state)] ['state-writeback 'state-fetch])))) (define (state-equal? sym) (for/signal (state-reg) (equal? state-reg sym))) (define fetch-en (state-equal? 'state-fetch)) (define decode-en (state-equal? 'state-decode)) (define execute-en (state-equal? 'state-execute)) (define load-en (state-equal? 'state-load)) (define store-en (state-equal? 'state-store)) (define writeback-en (state-equal? 'state-writeback)) (define instr (decoder (signal-defer rdata-reg))) (define instr-reg (register/e instr-nop decode-en instr)) (define-values (xs1 xs2) (register-unit #:reset reset #:enable writeback-en #:src-instr instr #:dest-instr instr-reg #:xd (signal-defer xd))) (define xs1-reg (register/e 0 decode-en xs1)) (define xs2-reg (register/e 0 decode-en xs2)) (define alu-a-reg (register/e 0 decode-en (for/signal (instr xs1 pc-reg) (if (instruction-use-pc? instr) pc-reg xs1)))) (define alu-b-reg (register/e 0 decode-en (for/signal (instr xs2) (if (instruction-use-imm? instr) (instruction-imm instr) xs2)))) (define alu-result (arith-logic-unit instr-reg alu-a-reg alu-b-reg)) (define alu-result-reg (register/e 0 execute-en alu-result)) (define pc+4 (>> add4 pc-reg)) (define pc-reg (register/re 0 reset execute-en (branch-unit #:reset reset #:enable execute-en #:irq irq #:instr instr-reg #:xs1 xs1-reg #:xs2 xs2-reg #:address alu-result #:pc+4 pc+4))) (define pc+4-reg (register/e 0 execute-en pc+4)) (define rdata-reg (register/e 0 (>> and valid ready) rdata)) (define valid (>> or fetch-en store-en load-en)) (define address (>> if fetch-en pc-reg alu-result-reg)) (define-values (wstrobe wdata load-data) (load-store-unit #:instr instr-reg #:address alu-result-reg #:store-enable store-en #:store-data xs2-reg #:rdata rdata-reg)) (define xd (for/signal (instr-reg load-data pc+4-reg alu-result-reg) (cond [(instruction-load? instr-reg) load-data] [(instruction-jump? instr-reg) pc+4-reg] [else alu-result-reg]))) (values valid address wstrobe wdata)) (module+ test (require rackunit) (require "tests/virgule.rkt") (define (fake-asm data) (if (procedure? data) (data #f #f) (word data))) (define test-count (length test-cases)) (define lst-rdata (map fake-asm (map first test-cases))) (define lst-ready (map second test-cases)) (define lst-irq (map third test-cases)) (define lst-expected (for/list ([c (in-list test-cases)]) (drop c 3))) (define-values (sig-valid sig-address sig-wstrobe sig-wdata) (virgule #:reset (signal #f) #:rdata (list->signal lst-rdata) #:ready (list->signal lst-ready) #:irq (list->signal lst-irq))) (define lst-result (map list (signal-take sig-valid test-count) (signal-take sig-address test-count) (signal-take sig-wstrobe test-count) (signal-take sig-wdata test-count))) (define labels '(valid address wstrobe wdata)) (for ([n test-count] [r (in-list lst-result)] [x (in-list lst-expected)]) (for ([l (in-list labels)] [rv (in-list r)] [xv (in-list x)] #:when (not (equal? 'any xv))) (test-equal? (format "Virgule #~a: ~a" n l) rv xv))))
3a26638e622a1e51d277045b952f61a09b21d105d23cffccc72504327da3b1ca
jvf/scalaris
lease_checker2.erl
2012 - 2015 Zuse Institute Berlin , 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. @author < > %% @doc check ring. %% @end %% @version $Id$ -module(lease_checker2). -author(''). -include("scalaris.hrl"). -include("record_helpers.hrl"). -record(leases_state_t, { last_check = ?required(lease_state_t, last_check) :: erlang:timestamp(), node_infos = ?required(lease_state_t, node_infos) :: node_list(), last_failed = ?required(lease_state_t, last_faile) :: boolean() }). -record(node_info_t, { lease_list = ?required(lease_state_t, lease_list) :: lease_list:lease_list(), my_range = ?required(lease_state_t, my_range) :: intervals:interval() }). -type node_list() :: gb_trees:tree(comm:mypid(), node_info() | empty). -type leases_state() :: #leases_state_t{}. -type node_info() :: #node_info_t{}. -export_type([leases_state/0]). -export([wait_for_clean_leases/1, wait_for_clean_leases/2]). -export([get_kv_db/0, get_kv_db/1]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % public api % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec wait_for_clean_leases(WaitTimeInMs::pos_integer(), TargetSize::pos_integer()) -> ok. wait_for_clean_leases(WaitTimeInMs, TargetSize) -> ?ASSERT(not gen_component:is_gen_component(self())), wait_for_clean_leases(WaitTimeInMs, TargetSize, true, create_new_state()). -spec wait_for_clean_leases(WaitTimeInMs::pos_integer()) -> ok. wait_for_clean_leases(WaitTimeInMs) -> ?ASSERT(not gen_component:is_gen_component(self())), wait_for_clean_leases(WaitTimeInMs, admin:number_of_nodes(), true, create_new_state()). -spec get_kv_db() -> ok. get_kv_db() -> KVDBs = [ get_dht_node_state(Pid, kv_db) || Pid <- all_dht_nodes()], Data = [prbr:tab2list(DB) || {true, DB} <- KVDBs, DB =/= false], FlattenedData = lists:flatten(Data), io:format("kv-pairs: ~p~n", [length(FlattenedData)]), Empties = [ DB || DB <- KVDBs, DB =:= false], Bottoms = [Value || {_Key, Value} <- FlattenedData, Value =:= prbr_bottom], io:format("falses: ~p~n", [length(Empties)]), io:format("prbr_bottoms: ~p~n", [length(Bottoms)]), %% io:format("data: ~p~n", [FlattenedData]), ok. -spec get_kv_db(term()) -> ok. get_kv_db(Pid) -> io:format("~p~n", [Pid]), {true, DB} = get_dht_node_state(comm:make_global(Pid), kv_db), io:format("kv-pairs: ~p~n", [length(prbr:tab2list(DB))]), ok. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % internal api % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec wait_for_clean_leases(WaitTimeInMs::pos_integer(), TargetSize::pos_integer(), First::boolean(), State::leases_state()) -> ok. wait_for_clean_leases(WaitTimeInMs, TargetSize, First, State) -> case check_leases(State, TargetSize, First) of {true, _} -> ok; {false, NewState} -> WaitID = uid:get_pids_uid(), comm:send_local_after(WaitTimeInMs, self(), {continue_wait, WaitID}), trace_mpath:thread_yield(), receive ?SCALARIS_RECV({continue_wait, WaitID},% -> wait_for_clean_leases(WaitTimeInMs, TargetSize, false, NewState)) end end. -spec check_leases(OldState::leases_state(), TargetSize::pos_integer(), First::boolean()) -> {boolean(), leases_state()}. check_leases(OldState, TargetSize, First) -> LastFailed = OldState#leases_state_t.last_failed, NewState = create_new_state(), case {gb_trees:size(OldState#leases_state_t.node_infos), gb_trees:size(NewState#leases_state_t.node_infos)} of {Old, Old} -> io:format("================= check leases (~p of ~p) ====================~n", [Old, TargetSize]); {Old, New} -> io:format("================= check leases ((~p -> ~p) of ~p) ====================~n", [Old, New, TargetSize]) end, case First of true -> io:format("begin existing nodes~n"), describe_nodes(OldState#leases_state_t.node_infos), io:format("end existing nodes~n"); false -> ok end, Changed = case compare_node_lists(OldState#leases_state_t.node_infos, NewState#leases_state_t.node_infos) of true -> false; false -> io:format("begin diff~n"), describe_lease_states_diff(OldState, NewState), io:format("end diff~n"), true end, Verbose = First orelse not LastFailed orelse Changed, Res = check_state(NewState, Verbose, TargetSize), io:format("check_state returned(verbose=~p) ~p~n", [Verbose, Res]), {Res, NewState#leases_state_t{last_failed=not Res}}. -spec check_state(State::leases_state(), Verbose::boolean(), TargetSize::pos_integer()) -> boolean(). check_state(State, Verbose, TargetSize) -> case check_leases_locally(State, Verbose) of true -> case check_leases_globally(State, Verbose, TargetSize) of true -> true; false -> io:format("check_leases_globally failed~n"), false end; false -> io:format("check_leases_locally failed~n"), false end. check_leases_locally(State , Verbose ) andalso check_leases_globally(State , Verbose , TargetSize ) . -spec check_leases_locally(leases_state(), boolean()) -> boolean(). check_leases_locally(#leases_state_t{node_infos=Nodes}, Verbose) -> lists:foldl(fun ({Pid, Node}, Acc) -> Acc and check_local_leases(Pid, Node, Verbose) end, true, gb_trees:to_list(Nodes)). -spec check_leases_globally(leases_state(), boolean(), pos_integer()) -> boolean(). check_leases_globally(State, Verbose, TargetSize) -> lease_checker(State, Verbose, TargetSize). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % compare functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc returns true iff the lists are equal -spec compare_node_lists(node_list(), node_list()) -> boolean(). compare_node_lists(Old, New) -> OldPids = ordsets:from_list(gb_trees:keys(Old)), NewPids = ordsets:from_list(gb_trees:keys(New)), case OldPids =:= NewPids of false -> false; true -> lists:foldl(fun (Pid, Acc) -> Acc andalso compare_node_infos(gb_trees:get(Pid, Old), gb_trees:get(Pid, New)) end, true, ordsets:to_list(NewPids)) end. -spec compare_node_infos(node_info() | empty, node_info() | empty) -> boolean(). compare_node_infos(Old, New) -> case {Old, New} of {empty, empty} -> true; {empty, New} -> false; {Old, empty} -> false; {Old, New} -> Old#node_info_t.my_range =:= New#node_info_t.my_range andalso compare_lease_lists(Old#node_info_t.lease_list, New#node_info_t.lease_list) end. -spec compare_lease_lists(L1::lease_list:lease_list(), L2::lease_list:lease_list()) -> boolean(). compare_lease_lists(L1, L2) -> compare_leases(lease_list:get_active_lease(L1), lease_list:get_active_lease(L2)) andalso compare_passive_leases(lease_list:get_passive_leases(L1), lease_list:get_passive_leases(L2)). -spec compare_passive_leases(L1::[l_on_cseq:lease_t()], L2::[l_on_cseq:lease_t()]) -> boolean(). compare_passive_leases(L1, L2) -> Ids1 = [l_on_cseq:get_id(L) || L <- L1], Ids2 = [l_on_cseq:get_id(L) || L <- L2], SetOfIds1 = ordsets:from_list(Ids1), SetOfIds2 = ordsets:from_list(Ids2), case SetOfIds1 =:= SetOfIds2 of true -> @todo use lists : foldl lists:all(fun (Bool) -> Bool end, lists:zipwith(fun (Lease1, Lease2) -> compare_leases(Lease1, Lease2) end, L1, L2)); false -> false end. -spec compare_leases(L1::l_on_cseq:lease_t() | empty, L2::l_on_cseq:lease_t() | empty) -> boolean(). compare_leases(L1, L2) -> case {L1, L2} of {empty, empty} -> true; {empty, L2} -> false; {L1, empty} -> false; _ -> l_on_cseq:get_id(L1) =:= l_on_cseq:get_id(L2) andalso l_on_cseq:get_owner(L1) =:= l_on_cseq:get_owner(L2) andalso l_on_cseq:get_range(L1) =:= l_on_cseq:get_range(L2) andalso l_on_cseq:get_aux(L1) =:= l_on_cseq:get_aux(L2) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % describe things functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec describe_nodes(node_list()) -> ok. describe_nodes(Nodes) -> _ = [ describe_node(Pid, Node) || {Pid, Node} <- gb_trees:to_list(Nodes) ], ok. -spec describe_list_of_leases(Leases::[l_on_cseq:lease_t()], active | passive) -> ok. describe_list_of_leases(Leases, Type) -> _ = [ describe_lease(L, Type) || L <- Leases ], ok. -spec describe_lease(L1::l_on_cseq:lease_t(), active | passive) -> ok. describe_lease(Lease, _Type) -> @todo use type parameter Interval = l_on_cseq:get_range(Lease), RelRange = get_relative_range(Interval), Owner = l_on_cseq:get_owner(Lease), Aux = l_on_cseq:get_aux(Lease), io:format(" range:~p~n rel_range:~p~n owner:~p~n aux:~p~n", [Interval, RelRange, Owner, Aux]), ok. @todo change to /1 with | empty -spec describe_node(Node::comm:mypid(), node_info() | empty) -> ok. describe_node(Pid, NodeInfo) -> case NodeInfo of empty -> ok; _ -> LeaseList = NodeInfo#node_info_t.lease_list, MyRange = NodeInfo#node_info_t.my_range, ActiveLease = lease_list:get_active_lease(LeaseList), PassiveLeases = lease_list:get_passive_leases(LeaseList), ActiveInterval = case ActiveLease of empty -> intervals:empty(); _ -> l_on_cseq:get_range(ActiveLease) end, RelRange = get_relative_range(ActiveInterval), Aux = case ActiveLease of empty -> no_lease; _ -> l_on_cseq:get_aux(ActiveLease) end, LocalCorrect = MyRange =:= ActiveInterval, io:format(" ~p~n", [Pid]), io:format(" rm =:= leases -> ~w~n", [LocalCorrect]), io:format(" active lease=~p~n", [ActiveInterval]), io:format(" my_range =~p~n", [MyRange]), io:format(" rel_range =~p~n", [RelRange]), io:format(" aux =~p~n", [Aux]), io:format(" passive =~p~n", [PassiveLeases]), ok end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % describe differences functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec describe_lease_states_diff(leases_state(), leases_state()) -> ok. describe_lease_states_diff(Old, New) -> %% PRE they differ describe_nodes_diff(Old#leases_state_t.node_infos, New#leases_state_t.node_infos). -spec describe_nodes_diff(node_list(), node_list()) -> ok. describe_nodes_diff(OldNodeInfos, NewNodeInfos) -> %% PRE they differ OldPids = ordsets:from_list(gb_trees:keys(OldNodeInfos)), NewPids = ordsets:from_list(gb_trees:keys(NewNodeInfos)), Unchanged = ordsets:intersection(OldPids, NewPids), FoundPids = ordsets:subtract(NewPids, OldPids), LostPids = ordsets:subtract(OldPids, NewPids), %% lost _ = case ordsets:size(LostPids) of 0 -> ok; N -> Old = ordsets:to_list(LostPids), io:format("lost ~p nodes: ~p~n", [N, Old]), describe_nodes(gb_trees_filter(fun (Pid, _Node) -> ordsets:is_element(Pid, LostPids) end, OldNodeInfos)) end, %% found _ = case ordsets:size(FoundPids) of 0 -> ok; N2 -> New = ordsets:to_list(FoundPids), io:format("found ~p new nodes: ~p~n", [N2, New]), describe_nodes(gb_trees_filter(fun (Pid, _Node) -> ordsets:is_element(Pid, FoundPids) end, NewNodeInfos)), io:format("end found~n", []) end, _ = case ordsets:size(Unchanged) of 0 -> ok; _ -> [ describe_node_diff(Pid, gb_trees:get(Pid, OldNodeInfos), gb_trees:get(Pid, NewNodeInfos)) || Pid <- ordsets:to_list(Unchanged)] end, ok. -spec describe_node_diff(Node::comm:mypid(), OldNodeInfo::node_info() | empty, NewNodeInfo::node_info() | empty) -> ok. describe_node_diff(Node, OldNodeInfo, NewNodeInfo) -> case {OldNodeInfo, NewNodeInfo} of {empty, empty} -> ok; {empty, NewNodeInfo} -> io:format("the node ~p has changed~n", [Node]), io:format("node info changed from empty to~n"), describe_node(Node, NewNodeInfo); {OldNodeInfo, empty} -> io:format("the node ~p has changed~n", [Node]), io:format("node info changed to empty from~n"), describe_node(Node, OldNodeInfo); {OldNodeInfo, NewNodeInfo} -> OldLeaseList = OldNodeInfo#node_info_t.lease_list, NewLeaseList = NewNodeInfo#node_info_t.lease_list, LeasesDiffer = not compare_lease_lists(OldLeaseList, NewLeaseList), OldRange = OldNodeInfo#node_info_t.my_range, NewRange = NewNodeInfo#node_info_t.my_range, RangesDiffer = OldRange =/= NewRange, case LeasesDiffer orelse RangesDiffer of true -> io:format("the node ~p has changed~n", [Node]), _ = case LeasesDiffer of true -> describe_lease_list_diff(OldLeaseList, NewLeaseList); false -> ok end, _ = case RangesDiffer of true -> io:format(" the nodes' range changed~n ~p~n ~p~n", [OldRange, NewRange]); false -> ok end, ok; false -> ok end end. -spec describe_lease_list_diff(lease_list:lease_list(), lease_list:lease_list()) -> ok. describe_lease_list_diff(OldLeaseList, NewLeaseList) -> describe_lease_diff(lease_list:get_active_lease(OldLeaseList), lease_list:get_active_lease(NewLeaseList), active), describe_list_of_leases_diff(lease_list:get_passive_leases(OldLeaseList), lease_list:get_passive_leases(NewLeaseList), passive), ok. -spec describe_lease_diff(l_on_cseq:lease_t() | empty, l_on_cseq:lease_t() | empty, active | passive) -> ok. describe_lease_diff(OldLease, NewLease, Type) -> case {OldLease, NewLease} of {empty, empty} -> ok; {empty, NewLease} -> io:format("nyi3~n"); {OldLease, empty} -> io:format("nyi4~n"); {_, _} -> case compare_leases(OldLease, NewLease) of true -> ok; false -> io:format(" an ~p lease has changed~n", [Type]), case l_on_cseq:get_id(OldLease) =:= l_on_cseq:get_id(NewLease) of true -> ok; false -> io:format(" the id has changed~n ~p~n ~p~n", [l_on_cseq:get_id(OldLease), l_on_cseq:get_id(NewLease)]) end, case l_on_cseq:get_owner(OldLease) =:= l_on_cseq:get_owner(NewLease) of true -> ok; false -> io:format(" the owner has changed~n ~p~n ~p~n", [l_on_cseq:get_owner(OldLease), l_on_cseq:get_owner(NewLease)]) end, case l_on_cseq:get_range(OldLease) =:= l_on_cseq:get_range(NewLease) of true -> ok; false -> io:format(" the range has changed from~n ~p~n ->~n ~p~n", [l_on_cseq:get_range(OldLease), l_on_cseq:get_range(NewLease)]) end, case l_on_cseq:get_aux(OldLease) =:= l_on_cseq:get_aux(NewLease) of true -> ok; false -> io:format(" the aux has changed~n ~p~n ->~n ~p~n", [l_on_cseq:get_aux(OldLease), l_on_cseq:get_aux(NewLease)]) end end end, ok. -spec describe_list_of_leases_diff([l_on_cseq:lease_t()], [l_on_cseq:lease_t()], active | passive) -> ok. describe_list_of_leases_diff(OldLeases, NewLeases, Type) -> OldIds = ordsets:from_list([l_on_cseq:get_id(L) || L <- OldLeases]), NewIds = ordsets:from_list([l_on_cseq:get_id(L) || L <- NewLeases]), Unchanged = ordsets:intersection(OldIds, NewIds), FoundIds = ordsets:subtract(NewIds, OldIds), LostIds = ordsets:subtract(OldIds, NewIds), %% lost _ = case ordsets:size(LostIds) of 0 -> ok; N -> io:format(" lost ~p passive leases: ~p~n", [N, ordsets:to_list(LostIds)]), describe_list_of_leases(lists:filter(fun (L) -> ordsets:is_element(l_on_cseq:get_id(L), LostIds) end, OldLeases), Type) end, %% found _ = case ordsets:size(FoundIds) of 0 -> ok; N2 -> io:format(" found ~p new passive leases: ~p~n", [N2, ordsets:to_list(FoundIds)]), describe_list_of_leases(lists:filter(fun (L) -> ordsets:is_element(l_on_cseq:get_id(L), FoundIds) end, NewLeases), Type) end, _ = case ordsets:size(Unchanged) of 0 -> ok; _ -> OL = lists:sort(fun (L1, L2) -> l_on_cseq:get_id(L1) < l_on_cseq:get_id(L2) end, OldLeases), NL = lists:sort(fun (L1, L2) -> l_on_cseq:get_id(L1) < l_on_cseq:get_id(L2) end, NewLeases), [ describe_lease_diff(L1,L2, Type) || L1 <- OL, L2 <- NL, ordsets:is_element(l_on_cseq:get_id(L1), Unchanged)] end, ok. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % state handling % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec create_new_state() -> leases_state(). create_new_state() -> Nodes = lists:foldl(fun (DHTNode, Tree) -> Info = create_node_info(DHTNode), gb_trees:insert(DHTNode, Info, Tree) end, gb_trees:empty(), all_dht_nodes()), #leases_state_t{last_check = os:timestamp(), node_infos=Nodes, last_failed=false}. -spec create_node_info(comm:mypid()) -> node_info() | empty. create_node_info(DHTNode) -> case get_dht_node_state(DHTNode, [lease_list, my_range]) of false -> empty; {true, [{lease_list, LeaseList}, {my_range, MyRange}]} -> #node_info_t{lease_list = LeaseList, my_range = MyRange} end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % check leases % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec check_local_leases(comm:mypid(), node_info(), boolean()) -> boolean(). check_local_leases(Pid, NodeInfo, Verbose) -> case NodeInfo of empty -> false; #node_info_t{lease_list=LeaseList, my_range=MyRange} -> ActiveLease = lease_list:get_active_lease(LeaseList), PassiveLeases = lease_list:get_passive_leases(LeaseList), ActiveInterval = case ActiveLease of empty -> intervals:empty(); _ -> l_on_cseq:get_range(ActiveLease) end, LocalCorrect = MyRange =:= ActiveInterval, RelRange = get_relative_range(ActiveInterval), case length(PassiveLeases) == 0 andalso LocalCorrect of true -> true; false -> case Verbose of true -> case ActiveLease of empty -> io:format("the active lease is empty~n"); _ -> Aux = l_on_cseq:get_aux(ActiveLease), io:format(" ~p~n", [Pid]), io:format(" rm =:= leases -> ~w~n", [LocalCorrect]), io:format(" active lease=~p~n", [ActiveInterval]), io:format(" my_range =~p~n", [MyRange]), io:format(" rel_range =~p~n", [RelRange]), io:format(" aux =~p~n", [Aux]), io:format(" passive =~p~n", [PassiveLeases]) end; false -> ok end, false end end. -spec lease_checker(State::leases_state(), Verbose::boolean(), TargetSize::pos_integer()) -> boolean(). lease_checker(#leases_state_t{node_infos=NodeInfos}, Verbose, TargetSize) -> LeaseLists = [Node#node_info_t.lease_list || Node <- gb_trees:values(NodeInfos)], ActiveLeases = [lease_list:get_active_lease(LL) || LL <- LeaseLists], PassiveLeases = lists:flatmap(fun lease_list:get_passive_leases/1, LeaseLists), ActiveIntervals = [l_on_cseq:get_range(Lease) || Lease <- ActiveLeases, Lease =/= empty], NormalizedActiveIntervals = intervals:union(ActiveIntervals), io : format("Lease - Checker : ~w ~w ~w " , [ ActiveLeases , ActiveIntervals , PassiveLeases ] ) , %ct:pal("ActiveIntervals: ~p", [ActiveIntervals]), %ct:pal("PassiveLeases: ~p", [PassiveLeases]), IsAll = intervals:is_all(NormalizedActiveIntervals), IsDisjoint = is_disjoint(ActiveIntervals), HaveAllActiveLeases = length(ActiveLeases) == TargetSize, HaveNoPassiveLeases = length(PassiveLeases) == 0, HaveAllAuxEmpty = lists:all(fun(L) -> L =/= empty andalso l_on_cseq:get_aux(L) =:= empty end, ActiveLeases), ct : pal("lease checker : ~w ~w ~w ~w ~ n ~ w ~ n ~ w ~ n " , [ IsAll , IsDisjoint , HaveAllActiveLeases , HaveNoPassiveLeases , PassiveLeases , NormalizedActiveIntervals ] ) , case IsAll of false -> %print_all_active_leases(), ok; true -> ok end, case IsAll andalso HaveAllAuxEmpty andalso IsDisjoint andalso HaveAllActiveLeases andalso HaveNoPassiveLeases of true -> ok; false -> case Verbose of true -> io:format("complete ring covered by leases: ~w~n", [IsAll]), io:format("all aux-fields are empty : ~w~n", [HaveAllAuxEmpty]), io:format("no leases overlap : ~w~n", [IsDisjoint]), io:format("each node has one active lease : ~w~n", [HaveAllActiveLeases]), io:format("no passive leases : ~w~n", [HaveNoPassiveLeases]), case HaveAllAuxEmpty of false -> io:format("aux fields: ~w~n", [[ l_on_cseq:get_aux(L) || L <- ActiveLeases, L =/= empty ]]); true -> ok end; false -> ok end end, IsAll andalso HaveAllAuxEmpty andalso IsDisjoint andalso @todo enable after garbage collection is implemented HaveNoPassiveLeases. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % utility functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec is_disjoint([intervals:interval()]) -> boolean(). is_disjoint([]) -> true; is_disjoint([H | T]) -> is_disjoint(H, T) andalso is_disjoint(T). is_disjoint(_I, []) -> true; is_disjoint(I, [H|T]) -> intervals:is_empty(intervals:intersection(I,H)) andalso is_disjoint(I, T). -spec get_relative_range(intervals:interval()) -> float(). get_relative_range(ActiveInterval) -> case intervals:empty() of ActiveInterval -> 0.0 / ?RT:n(); _ -> {_, Begin, End, _} = intervals:get_bounds(ActiveInterval), ?RT:get_range(Begin, End) / ?RT:n() end. -spec get_dht_node_state(comm:mypid(), atom() | list(atom())) -> term() | list(term()). get_dht_node_state(Pid, What) -> case proto_sched:infected() of true -> Cookie = {os:timestamp(), randoms:getRandomInt()}, This = comm:reply_as(comm:this(), 2, {get_dht_node_state_response, '_', Cookie}), comm:send(Pid, {get_state, This, What}), trace_mpath:thread_yield(), receive ?SCALARIS_RECV({get_dht_node_state_response, {get_state_response, Data}, Cookie},% -> {true, Data}) end; false -> false = trace_mpath:infected(), Cookie = {os:timestamp(), randoms:getRandomInt()}, This = comm:reply_as(comm:this(), 2, {get_dht_node_state_response, '_', Cookie}), comm:send(Pid, {get_state, This, What}), Result = receive ?SCALARIS_RECV({get_dht_node_state_response, {get_state_response, Data}, Cookie},% -> {true, Data}) after 50 -> false end, %% drain message queue drain_message_queue(), Result end. drain_message_queue() -> false = trace_mpath:infected(), trace_mpath:thread_yield(), receive ?SCALARIS_RECV({get_dht_state_response, _Data, _Cookie},% -> ok) after 0 -> ok end. -spec all_dht_nodes() -> list(comm:mypid()). all_dht_nodes() -> mgmt_server:node_list(), trace_mpath:thread_yield(), receive ?SCALARIS_RECV({get_list_response, Nodes},% -> Nodes) end. %% @doc keep alle elements of Tree for which F(K,V) is true -spec gb_trees_filter(F::fun((K, V) -> boolean()), Tree::gb_trees:tree(K,V)) -> gb_trees:tree(K,V). gb_trees_filter(F, Tree) -> gb_trees_filter(F, gb_trees:empty(), gb_trees:iterator(Tree)). -spec gb_trees_filter(F::fun((K, V) -> boolean()), Acc::gb_trees:tree(K, V), Iter::gb_trees:iter(K,V)) -> gb_trees:tree(K, V). gb_trees_filter(F, Acc, Iter) -> case gb_trees:next(Iter) of none -> Acc; {Key, Value, Iter2} -> case F(Key,Value) of true -> gb_trees_filter(F, gb_trees:enter(Key, Value, Acc), Iter2); false -> gb_trees_filter(F, Acc, Iter2) end end.
null
https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/cp/lease_checker2.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. @doc check ring. @end @version $Id$ public api io:format("data: ~p~n", [FlattenedData]), internal api -> compare functions @doc returns true iff the lists are equal describe things functions describe differences functions PRE they differ PRE they differ lost found lost found state handling check leases ct:pal("ActiveIntervals: ~p", [ActiveIntervals]), ct:pal("PassiveLeases: ~p", [PassiveLeases]), print_all_active_leases(), utility functions -> -> drain message queue -> -> @doc keep alle elements of Tree for which F(K,V) is true
2012 - 2015 Zuse Institute Berlin , Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(lease_checker2). -author(''). -include("scalaris.hrl"). -include("record_helpers.hrl"). -record(leases_state_t, { last_check = ?required(lease_state_t, last_check) :: erlang:timestamp(), node_infos = ?required(lease_state_t, node_infos) :: node_list(), last_failed = ?required(lease_state_t, last_faile) :: boolean() }). -record(node_info_t, { lease_list = ?required(lease_state_t, lease_list) :: lease_list:lease_list(), my_range = ?required(lease_state_t, my_range) :: intervals:interval() }). -type node_list() :: gb_trees:tree(comm:mypid(), node_info() | empty). -type leases_state() :: #leases_state_t{}. -type node_info() :: #node_info_t{}. -export_type([leases_state/0]). -export([wait_for_clean_leases/1, wait_for_clean_leases/2]). -export([get_kv_db/0, get_kv_db/1]). -spec wait_for_clean_leases(WaitTimeInMs::pos_integer(), TargetSize::pos_integer()) -> ok. wait_for_clean_leases(WaitTimeInMs, TargetSize) -> ?ASSERT(not gen_component:is_gen_component(self())), wait_for_clean_leases(WaitTimeInMs, TargetSize, true, create_new_state()). -spec wait_for_clean_leases(WaitTimeInMs::pos_integer()) -> ok. wait_for_clean_leases(WaitTimeInMs) -> ?ASSERT(not gen_component:is_gen_component(self())), wait_for_clean_leases(WaitTimeInMs, admin:number_of_nodes(), true, create_new_state()). -spec get_kv_db() -> ok. get_kv_db() -> KVDBs = [ get_dht_node_state(Pid, kv_db) || Pid <- all_dht_nodes()], Data = [prbr:tab2list(DB) || {true, DB} <- KVDBs, DB =/= false], FlattenedData = lists:flatten(Data), io:format("kv-pairs: ~p~n", [length(FlattenedData)]), Empties = [ DB || DB <- KVDBs, DB =:= false], Bottoms = [Value || {_Key, Value} <- FlattenedData, Value =:= prbr_bottom], io:format("falses: ~p~n", [length(Empties)]), io:format("prbr_bottoms: ~p~n", [length(Bottoms)]), ok. -spec get_kv_db(term()) -> ok. get_kv_db(Pid) -> io:format("~p~n", [Pid]), {true, DB} = get_dht_node_state(comm:make_global(Pid), kv_db), io:format("kv-pairs: ~p~n", [length(prbr:tab2list(DB))]), ok. -spec wait_for_clean_leases(WaitTimeInMs::pos_integer(), TargetSize::pos_integer(), First::boolean(), State::leases_state()) -> ok. wait_for_clean_leases(WaitTimeInMs, TargetSize, First, State) -> case check_leases(State, TargetSize, First) of {true, _} -> ok; {false, NewState} -> WaitID = uid:get_pids_uid(), comm:send_local_after(WaitTimeInMs, self(), {continue_wait, WaitID}), trace_mpath:thread_yield(), receive wait_for_clean_leases(WaitTimeInMs, TargetSize, false, NewState)) end end. -spec check_leases(OldState::leases_state(), TargetSize::pos_integer(), First::boolean()) -> {boolean(), leases_state()}. check_leases(OldState, TargetSize, First) -> LastFailed = OldState#leases_state_t.last_failed, NewState = create_new_state(), case {gb_trees:size(OldState#leases_state_t.node_infos), gb_trees:size(NewState#leases_state_t.node_infos)} of {Old, Old} -> io:format("================= check leases (~p of ~p) ====================~n", [Old, TargetSize]); {Old, New} -> io:format("================= check leases ((~p -> ~p) of ~p) ====================~n", [Old, New, TargetSize]) end, case First of true -> io:format("begin existing nodes~n"), describe_nodes(OldState#leases_state_t.node_infos), io:format("end existing nodes~n"); false -> ok end, Changed = case compare_node_lists(OldState#leases_state_t.node_infos, NewState#leases_state_t.node_infos) of true -> false; false -> io:format("begin diff~n"), describe_lease_states_diff(OldState, NewState), io:format("end diff~n"), true end, Verbose = First orelse not LastFailed orelse Changed, Res = check_state(NewState, Verbose, TargetSize), io:format("check_state returned(verbose=~p) ~p~n", [Verbose, Res]), {Res, NewState#leases_state_t{last_failed=not Res}}. -spec check_state(State::leases_state(), Verbose::boolean(), TargetSize::pos_integer()) -> boolean(). check_state(State, Verbose, TargetSize) -> case check_leases_locally(State, Verbose) of true -> case check_leases_globally(State, Verbose, TargetSize) of true -> true; false -> io:format("check_leases_globally failed~n"), false end; false -> io:format("check_leases_locally failed~n"), false end. check_leases_locally(State , Verbose ) andalso check_leases_globally(State , Verbose , TargetSize ) . -spec check_leases_locally(leases_state(), boolean()) -> boolean(). check_leases_locally(#leases_state_t{node_infos=Nodes}, Verbose) -> lists:foldl(fun ({Pid, Node}, Acc) -> Acc and check_local_leases(Pid, Node, Verbose) end, true, gb_trees:to_list(Nodes)). -spec check_leases_globally(leases_state(), boolean(), pos_integer()) -> boolean(). check_leases_globally(State, Verbose, TargetSize) -> lease_checker(State, Verbose, TargetSize). -spec compare_node_lists(node_list(), node_list()) -> boolean(). compare_node_lists(Old, New) -> OldPids = ordsets:from_list(gb_trees:keys(Old)), NewPids = ordsets:from_list(gb_trees:keys(New)), case OldPids =:= NewPids of false -> false; true -> lists:foldl(fun (Pid, Acc) -> Acc andalso compare_node_infos(gb_trees:get(Pid, Old), gb_trees:get(Pid, New)) end, true, ordsets:to_list(NewPids)) end. -spec compare_node_infos(node_info() | empty, node_info() | empty) -> boolean(). compare_node_infos(Old, New) -> case {Old, New} of {empty, empty} -> true; {empty, New} -> false; {Old, empty} -> false; {Old, New} -> Old#node_info_t.my_range =:= New#node_info_t.my_range andalso compare_lease_lists(Old#node_info_t.lease_list, New#node_info_t.lease_list) end. -spec compare_lease_lists(L1::lease_list:lease_list(), L2::lease_list:lease_list()) -> boolean(). compare_lease_lists(L1, L2) -> compare_leases(lease_list:get_active_lease(L1), lease_list:get_active_lease(L2)) andalso compare_passive_leases(lease_list:get_passive_leases(L1), lease_list:get_passive_leases(L2)). -spec compare_passive_leases(L1::[l_on_cseq:lease_t()], L2::[l_on_cseq:lease_t()]) -> boolean(). compare_passive_leases(L1, L2) -> Ids1 = [l_on_cseq:get_id(L) || L <- L1], Ids2 = [l_on_cseq:get_id(L) || L <- L2], SetOfIds1 = ordsets:from_list(Ids1), SetOfIds2 = ordsets:from_list(Ids2), case SetOfIds1 =:= SetOfIds2 of true -> @todo use lists : foldl lists:all(fun (Bool) -> Bool end, lists:zipwith(fun (Lease1, Lease2) -> compare_leases(Lease1, Lease2) end, L1, L2)); false -> false end. -spec compare_leases(L1::l_on_cseq:lease_t() | empty, L2::l_on_cseq:lease_t() | empty) -> boolean(). compare_leases(L1, L2) -> case {L1, L2} of {empty, empty} -> true; {empty, L2} -> false; {L1, empty} -> false; _ -> l_on_cseq:get_id(L1) =:= l_on_cseq:get_id(L2) andalso l_on_cseq:get_owner(L1) =:= l_on_cseq:get_owner(L2) andalso l_on_cseq:get_range(L1) =:= l_on_cseq:get_range(L2) andalso l_on_cseq:get_aux(L1) =:= l_on_cseq:get_aux(L2) end. -spec describe_nodes(node_list()) -> ok. describe_nodes(Nodes) -> _ = [ describe_node(Pid, Node) || {Pid, Node} <- gb_trees:to_list(Nodes) ], ok. -spec describe_list_of_leases(Leases::[l_on_cseq:lease_t()], active | passive) -> ok. describe_list_of_leases(Leases, Type) -> _ = [ describe_lease(L, Type) || L <- Leases ], ok. -spec describe_lease(L1::l_on_cseq:lease_t(), active | passive) -> ok. describe_lease(Lease, _Type) -> @todo use type parameter Interval = l_on_cseq:get_range(Lease), RelRange = get_relative_range(Interval), Owner = l_on_cseq:get_owner(Lease), Aux = l_on_cseq:get_aux(Lease), io:format(" range:~p~n rel_range:~p~n owner:~p~n aux:~p~n", [Interval, RelRange, Owner, Aux]), ok. @todo change to /1 with | empty -spec describe_node(Node::comm:mypid(), node_info() | empty) -> ok. describe_node(Pid, NodeInfo) -> case NodeInfo of empty -> ok; _ -> LeaseList = NodeInfo#node_info_t.lease_list, MyRange = NodeInfo#node_info_t.my_range, ActiveLease = lease_list:get_active_lease(LeaseList), PassiveLeases = lease_list:get_passive_leases(LeaseList), ActiveInterval = case ActiveLease of empty -> intervals:empty(); _ -> l_on_cseq:get_range(ActiveLease) end, RelRange = get_relative_range(ActiveInterval), Aux = case ActiveLease of empty -> no_lease; _ -> l_on_cseq:get_aux(ActiveLease) end, LocalCorrect = MyRange =:= ActiveInterval, io:format(" ~p~n", [Pid]), io:format(" rm =:= leases -> ~w~n", [LocalCorrect]), io:format(" active lease=~p~n", [ActiveInterval]), io:format(" my_range =~p~n", [MyRange]), io:format(" rel_range =~p~n", [RelRange]), io:format(" aux =~p~n", [Aux]), io:format(" passive =~p~n", [PassiveLeases]), ok end. -spec describe_lease_states_diff(leases_state(), leases_state()) -> ok. describe_lease_states_diff(Old, New) -> describe_nodes_diff(Old#leases_state_t.node_infos, New#leases_state_t.node_infos). -spec describe_nodes_diff(node_list(), node_list()) -> ok. describe_nodes_diff(OldNodeInfos, NewNodeInfos) -> OldPids = ordsets:from_list(gb_trees:keys(OldNodeInfos)), NewPids = ordsets:from_list(gb_trees:keys(NewNodeInfos)), Unchanged = ordsets:intersection(OldPids, NewPids), FoundPids = ordsets:subtract(NewPids, OldPids), LostPids = ordsets:subtract(OldPids, NewPids), _ = case ordsets:size(LostPids) of 0 -> ok; N -> Old = ordsets:to_list(LostPids), io:format("lost ~p nodes: ~p~n", [N, Old]), describe_nodes(gb_trees_filter(fun (Pid, _Node) -> ordsets:is_element(Pid, LostPids) end, OldNodeInfos)) end, _ = case ordsets:size(FoundPids) of 0 -> ok; N2 -> New = ordsets:to_list(FoundPids), io:format("found ~p new nodes: ~p~n", [N2, New]), describe_nodes(gb_trees_filter(fun (Pid, _Node) -> ordsets:is_element(Pid, FoundPids) end, NewNodeInfos)), io:format("end found~n", []) end, _ = case ordsets:size(Unchanged) of 0 -> ok; _ -> [ describe_node_diff(Pid, gb_trees:get(Pid, OldNodeInfos), gb_trees:get(Pid, NewNodeInfos)) || Pid <- ordsets:to_list(Unchanged)] end, ok. -spec describe_node_diff(Node::comm:mypid(), OldNodeInfo::node_info() | empty, NewNodeInfo::node_info() | empty) -> ok. describe_node_diff(Node, OldNodeInfo, NewNodeInfo) -> case {OldNodeInfo, NewNodeInfo} of {empty, empty} -> ok; {empty, NewNodeInfo} -> io:format("the node ~p has changed~n", [Node]), io:format("node info changed from empty to~n"), describe_node(Node, NewNodeInfo); {OldNodeInfo, empty} -> io:format("the node ~p has changed~n", [Node]), io:format("node info changed to empty from~n"), describe_node(Node, OldNodeInfo); {OldNodeInfo, NewNodeInfo} -> OldLeaseList = OldNodeInfo#node_info_t.lease_list, NewLeaseList = NewNodeInfo#node_info_t.lease_list, LeasesDiffer = not compare_lease_lists(OldLeaseList, NewLeaseList), OldRange = OldNodeInfo#node_info_t.my_range, NewRange = NewNodeInfo#node_info_t.my_range, RangesDiffer = OldRange =/= NewRange, case LeasesDiffer orelse RangesDiffer of true -> io:format("the node ~p has changed~n", [Node]), _ = case LeasesDiffer of true -> describe_lease_list_diff(OldLeaseList, NewLeaseList); false -> ok end, _ = case RangesDiffer of true -> io:format(" the nodes' range changed~n ~p~n ~p~n", [OldRange, NewRange]); false -> ok end, ok; false -> ok end end. -spec describe_lease_list_diff(lease_list:lease_list(), lease_list:lease_list()) -> ok. describe_lease_list_diff(OldLeaseList, NewLeaseList) -> describe_lease_diff(lease_list:get_active_lease(OldLeaseList), lease_list:get_active_lease(NewLeaseList), active), describe_list_of_leases_diff(lease_list:get_passive_leases(OldLeaseList), lease_list:get_passive_leases(NewLeaseList), passive), ok. -spec describe_lease_diff(l_on_cseq:lease_t() | empty, l_on_cseq:lease_t() | empty, active | passive) -> ok. describe_lease_diff(OldLease, NewLease, Type) -> case {OldLease, NewLease} of {empty, empty} -> ok; {empty, NewLease} -> io:format("nyi3~n"); {OldLease, empty} -> io:format("nyi4~n"); {_, _} -> case compare_leases(OldLease, NewLease) of true -> ok; false -> io:format(" an ~p lease has changed~n", [Type]), case l_on_cseq:get_id(OldLease) =:= l_on_cseq:get_id(NewLease) of true -> ok; false -> io:format(" the id has changed~n ~p~n ~p~n", [l_on_cseq:get_id(OldLease), l_on_cseq:get_id(NewLease)]) end, case l_on_cseq:get_owner(OldLease) =:= l_on_cseq:get_owner(NewLease) of true -> ok; false -> io:format(" the owner has changed~n ~p~n ~p~n", [l_on_cseq:get_owner(OldLease), l_on_cseq:get_owner(NewLease)]) end, case l_on_cseq:get_range(OldLease) =:= l_on_cseq:get_range(NewLease) of true -> ok; false -> io:format(" the range has changed from~n ~p~n ->~n ~p~n", [l_on_cseq:get_range(OldLease), l_on_cseq:get_range(NewLease)]) end, case l_on_cseq:get_aux(OldLease) =:= l_on_cseq:get_aux(NewLease) of true -> ok; false -> io:format(" the aux has changed~n ~p~n ->~n ~p~n", [l_on_cseq:get_aux(OldLease), l_on_cseq:get_aux(NewLease)]) end end end, ok. -spec describe_list_of_leases_diff([l_on_cseq:lease_t()], [l_on_cseq:lease_t()], active | passive) -> ok. describe_list_of_leases_diff(OldLeases, NewLeases, Type) -> OldIds = ordsets:from_list([l_on_cseq:get_id(L) || L <- OldLeases]), NewIds = ordsets:from_list([l_on_cseq:get_id(L) || L <- NewLeases]), Unchanged = ordsets:intersection(OldIds, NewIds), FoundIds = ordsets:subtract(NewIds, OldIds), LostIds = ordsets:subtract(OldIds, NewIds), _ = case ordsets:size(LostIds) of 0 -> ok; N -> io:format(" lost ~p passive leases: ~p~n", [N, ordsets:to_list(LostIds)]), describe_list_of_leases(lists:filter(fun (L) -> ordsets:is_element(l_on_cseq:get_id(L), LostIds) end, OldLeases), Type) end, _ = case ordsets:size(FoundIds) of 0 -> ok; N2 -> io:format(" found ~p new passive leases: ~p~n", [N2, ordsets:to_list(FoundIds)]), describe_list_of_leases(lists:filter(fun (L) -> ordsets:is_element(l_on_cseq:get_id(L), FoundIds) end, NewLeases), Type) end, _ = case ordsets:size(Unchanged) of 0 -> ok; _ -> OL = lists:sort(fun (L1, L2) -> l_on_cseq:get_id(L1) < l_on_cseq:get_id(L2) end, OldLeases), NL = lists:sort(fun (L1, L2) -> l_on_cseq:get_id(L1) < l_on_cseq:get_id(L2) end, NewLeases), [ describe_lease_diff(L1,L2, Type) || L1 <- OL, L2 <- NL, ordsets:is_element(l_on_cseq:get_id(L1), Unchanged)] end, ok. -spec create_new_state() -> leases_state(). create_new_state() -> Nodes = lists:foldl(fun (DHTNode, Tree) -> Info = create_node_info(DHTNode), gb_trees:insert(DHTNode, Info, Tree) end, gb_trees:empty(), all_dht_nodes()), #leases_state_t{last_check = os:timestamp(), node_infos=Nodes, last_failed=false}. -spec create_node_info(comm:mypid()) -> node_info() | empty. create_node_info(DHTNode) -> case get_dht_node_state(DHTNode, [lease_list, my_range]) of false -> empty; {true, [{lease_list, LeaseList}, {my_range, MyRange}]} -> #node_info_t{lease_list = LeaseList, my_range = MyRange} end. -spec check_local_leases(comm:mypid(), node_info(), boolean()) -> boolean(). check_local_leases(Pid, NodeInfo, Verbose) -> case NodeInfo of empty -> false; #node_info_t{lease_list=LeaseList, my_range=MyRange} -> ActiveLease = lease_list:get_active_lease(LeaseList), PassiveLeases = lease_list:get_passive_leases(LeaseList), ActiveInterval = case ActiveLease of empty -> intervals:empty(); _ -> l_on_cseq:get_range(ActiveLease) end, LocalCorrect = MyRange =:= ActiveInterval, RelRange = get_relative_range(ActiveInterval), case length(PassiveLeases) == 0 andalso LocalCorrect of true -> true; false -> case Verbose of true -> case ActiveLease of empty -> io:format("the active lease is empty~n"); _ -> Aux = l_on_cseq:get_aux(ActiveLease), io:format(" ~p~n", [Pid]), io:format(" rm =:= leases -> ~w~n", [LocalCorrect]), io:format(" active lease=~p~n", [ActiveInterval]), io:format(" my_range =~p~n", [MyRange]), io:format(" rel_range =~p~n", [RelRange]), io:format(" aux =~p~n", [Aux]), io:format(" passive =~p~n", [PassiveLeases]) end; false -> ok end, false end end. -spec lease_checker(State::leases_state(), Verbose::boolean(), TargetSize::pos_integer()) -> boolean(). lease_checker(#leases_state_t{node_infos=NodeInfos}, Verbose, TargetSize) -> LeaseLists = [Node#node_info_t.lease_list || Node <- gb_trees:values(NodeInfos)], ActiveLeases = [lease_list:get_active_lease(LL) || LL <- LeaseLists], PassiveLeases = lists:flatmap(fun lease_list:get_passive_leases/1, LeaseLists), ActiveIntervals = [l_on_cseq:get_range(Lease) || Lease <- ActiveLeases, Lease =/= empty], NormalizedActiveIntervals = intervals:union(ActiveIntervals), io : format("Lease - Checker : ~w ~w ~w " , [ ActiveLeases , ActiveIntervals , PassiveLeases ] ) , IsAll = intervals:is_all(NormalizedActiveIntervals), IsDisjoint = is_disjoint(ActiveIntervals), HaveAllActiveLeases = length(ActiveLeases) == TargetSize, HaveNoPassiveLeases = length(PassiveLeases) == 0, HaveAllAuxEmpty = lists:all(fun(L) -> L =/= empty andalso l_on_cseq:get_aux(L) =:= empty end, ActiveLeases), ct : pal("lease checker : ~w ~w ~w ~w ~ n ~ w ~ n ~ w ~ n " , [ IsAll , IsDisjoint , HaveAllActiveLeases , HaveNoPassiveLeases , PassiveLeases , NormalizedActiveIntervals ] ) , case IsAll of false -> ok; true -> ok end, case IsAll andalso HaveAllAuxEmpty andalso IsDisjoint andalso HaveAllActiveLeases andalso HaveNoPassiveLeases of true -> ok; false -> case Verbose of true -> io:format("complete ring covered by leases: ~w~n", [IsAll]), io:format("all aux-fields are empty : ~w~n", [HaveAllAuxEmpty]), io:format("no leases overlap : ~w~n", [IsDisjoint]), io:format("each node has one active lease : ~w~n", [HaveAllActiveLeases]), io:format("no passive leases : ~w~n", [HaveNoPassiveLeases]), case HaveAllAuxEmpty of false -> io:format("aux fields: ~w~n", [[ l_on_cseq:get_aux(L) || L <- ActiveLeases, L =/= empty ]]); true -> ok end; false -> ok end end, IsAll andalso HaveAllAuxEmpty andalso IsDisjoint andalso @todo enable after garbage collection is implemented HaveNoPassiveLeases. -spec is_disjoint([intervals:interval()]) -> boolean(). is_disjoint([]) -> true; is_disjoint([H | T]) -> is_disjoint(H, T) andalso is_disjoint(T). is_disjoint(_I, []) -> true; is_disjoint(I, [H|T]) -> intervals:is_empty(intervals:intersection(I,H)) andalso is_disjoint(I, T). -spec get_relative_range(intervals:interval()) -> float(). get_relative_range(ActiveInterval) -> case intervals:empty() of ActiveInterval -> 0.0 / ?RT:n(); _ -> {_, Begin, End, _} = intervals:get_bounds(ActiveInterval), ?RT:get_range(Begin, End) / ?RT:n() end. -spec get_dht_node_state(comm:mypid(), atom() | list(atom())) -> term() | list(term()). get_dht_node_state(Pid, What) -> case proto_sched:infected() of true -> Cookie = {os:timestamp(), randoms:getRandomInt()}, This = comm:reply_as(comm:this(), 2, {get_dht_node_state_response, '_', Cookie}), comm:send(Pid, {get_state, This, What}), trace_mpath:thread_yield(), receive ?SCALARIS_RECV({get_dht_node_state_response, {true, Data}) end; false -> false = trace_mpath:infected(), Cookie = {os:timestamp(), randoms:getRandomInt()}, This = comm:reply_as(comm:this(), 2, {get_dht_node_state_response, '_', Cookie}), comm:send(Pid, {get_state, This, What}), Result = receive {true, Data}) after 50 -> false end, drain_message_queue(), Result end. drain_message_queue() -> false = trace_mpath:infected(), trace_mpath:thread_yield(), receive ok) after 0 -> ok end. -spec all_dht_nodes() -> list(comm:mypid()). all_dht_nodes() -> mgmt_server:node_list(), trace_mpath:thread_yield(), receive Nodes) end. -spec gb_trees_filter(F::fun((K, V) -> boolean()), Tree::gb_trees:tree(K,V)) -> gb_trees:tree(K,V). gb_trees_filter(F, Tree) -> gb_trees_filter(F, gb_trees:empty(), gb_trees:iterator(Tree)). -spec gb_trees_filter(F::fun((K, V) -> boolean()), Acc::gb_trees:tree(K, V), Iter::gb_trees:iter(K,V)) -> gb_trees:tree(K, V). gb_trees_filter(F, Acc, Iter) -> case gb_trees:next(Iter) of none -> Acc; {Key, Value, Iter2} -> case F(Key,Value) of true -> gb_trees_filter(F, gb_trees:enter(Key, Value, Acc), Iter2); false -> gb_trees_filter(F, Acc, Iter2) end end.
41640eff50b1b626064bacd66ba7e4e9fa5a3add4bd023e025d93dc70b79f760
marick/fp-oo
higher-order-functions.clj
` reversed - digits ` takes advantage of two new facts ( that are n't ;;; used in the rest of the book): ;;; 1 . Java interoperability allows you to call Java methods -- both ;;; instance methods and class methods. So you can call one of Java 's Integer constructors like this : ;;; user= > ( Integer . " 321 " ) 321 ;;; 2 . Strings are sequences , so you can apply sequence functions ;;; to them. The result isn't a string, though, but rather a sequence of Java Characters : ;;; ;;; user=> (reverse "foo") ( \o \o \f ) ;;; ;;; You can convert a character into a string with `str`: user= > ( str \o ) ;;; "o" ;;; Thanks to for a version that improved on my ;;; original. (def reversed-digits (fn [string] (map (fn [digit-char] (-> digit-char str Integer.)) (reverse string)))) ( ? " 0131774115 " ) ( ? " 0977716614 " ) ( ? " 1934356190 " ) ( upc ? " 074182265830 " ) ( upc ? " 731124100023 " ) ( upc ? " 722252601404 " ) ; ; This one is incorrect .
null
https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/sources/higher-order-functions.clj
clojure
used in the rest of the book): instance methods and class methods. So you can call one of to them. The result isn't a string, though, but rather a user=> (reverse "foo") You can convert a character into a string with `str`: "o" original. ; This one is incorrect .
` reversed - digits ` takes advantage of two new facts ( that are n't 1 . Java interoperability allows you to call Java methods -- both Java 's Integer constructors like this : user= > ( Integer . " 321 " ) 321 2 . Strings are sequences , so you can apply sequence functions sequence of Java Characters : ( \o \o \f ) user= > ( str \o ) Thanks to for a version that improved on my (def reversed-digits (fn [string] (map (fn [digit-char] (-> digit-char str Integer.)) (reverse string)))) ( ? " 0131774115 " ) ( ? " 0977716614 " ) ( ? " 1934356190 " ) ( upc ? " 074182265830 " ) ( upc ? " 731124100023 " )
eadf4b1cf780df8f80c5916f2ee930c85e6419dee0280b2f5db41ab152d7c277
clj-kondo/clj-kondo
metadata.clj
(ns clj-kondo.impl.metadata {:no-doc true} (:require [clj-kondo.impl.analyzer.common :as common] [clj-kondo.impl.linters.keys :as key-linter] [clj-kondo.impl.utils :as utils])) (defn meta-node->map [ctx node] (let [s (utils/sexpr node)] (cond (keyword? s) {s true} (map? s) (do (key-linter/lint-map-keys ctx node) s) :else {:tag s}))) (def type-hint-bindings "From #TypeAliases" (zipmap '[int ints long longs float floats double doubles void short shorts boolean boolean byte bytes char chars objects] (repeat {}))) (defn lift-meta-content2 ([ctx node] (lift-meta-content2 ctx node false)) ([{:keys [:analyze-meta? :lang] :as ctx} node only-usage?] (if-let [meta-list (:meta node)] (let [meta-list (if (identical? :cljc (:base-lang ctx)) (keep #(utils/select-lang % lang) meta-list) meta-list) cljs? (identical? :cljs lang) ctx (if cljs? (assoc-in ctx [:config :linters :unresolved-symbol :level] :off) ctx) meta-ctx (-> ctx (update :callstack conj [nil :metadata]) (utils/ctx-with-bindings (cond-> type-hint-bindings cljs? (assoc 'js {} 'number {}))) (assoc :arg-types (atom []))) ;; use dorun to force analysis, we don't use the end result! _ (if only-usage? (run! #(dorun (common/analyze-usages2 meta-ctx %)) meta-list) (run! #(dorun (common/analyze-expression** meta-ctx %)) meta-list)) meta-maps (map #(meta-node->map ctx %) meta-list) meta-map (apply merge meta-maps) meta-map (if analyze-meta? (assoc meta-map :user-meta [meta-map]) meta-map) node (dissoc node :meta) node (let [new-meta clear user - coded metadata that can conflict with ;; clj-kondo only sometimes sets these but later always checks them (dissoc meta-map :name-row :name-col :name-end-row :name-end-col) new-meta (merge new-meta (meta node))] (with-meta node new-meta))] node) node))) ;;;; Scratch (comment (meta (lift-meta-content2 {:findings (atom [])} (utils/parse-string "^{:a 1 :a 2} []"))) )
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/5db942f19916f98e8d21b4f787f37f3be0e0d45d/src/clj_kondo/impl/metadata.clj
clojure
use dorun to force analysis, we don't use the end result! clj-kondo only sometimes sets these but later always checks them Scratch
(ns clj-kondo.impl.metadata {:no-doc true} (:require [clj-kondo.impl.analyzer.common :as common] [clj-kondo.impl.linters.keys :as key-linter] [clj-kondo.impl.utils :as utils])) (defn meta-node->map [ctx node] (let [s (utils/sexpr node)] (cond (keyword? s) {s true} (map? s) (do (key-linter/lint-map-keys ctx node) s) :else {:tag s}))) (def type-hint-bindings "From #TypeAliases" (zipmap '[int ints long longs float floats double doubles void short shorts boolean boolean byte bytes char chars objects] (repeat {}))) (defn lift-meta-content2 ([ctx node] (lift-meta-content2 ctx node false)) ([{:keys [:analyze-meta? :lang] :as ctx} node only-usage?] (if-let [meta-list (:meta node)] (let [meta-list (if (identical? :cljc (:base-lang ctx)) (keep #(utils/select-lang % lang) meta-list) meta-list) cljs? (identical? :cljs lang) ctx (if cljs? (assoc-in ctx [:config :linters :unresolved-symbol :level] :off) ctx) meta-ctx (-> ctx (update :callstack conj [nil :metadata]) (utils/ctx-with-bindings (cond-> type-hint-bindings cljs? (assoc 'js {} 'number {}))) (assoc :arg-types (atom []))) _ (if only-usage? (run! #(dorun (common/analyze-usages2 meta-ctx %)) meta-list) (run! #(dorun (common/analyze-expression** meta-ctx %)) meta-list)) meta-maps (map #(meta-node->map ctx %) meta-list) meta-map (apply merge meta-maps) meta-map (if analyze-meta? (assoc meta-map :user-meta [meta-map]) meta-map) node (dissoc node :meta) node (let [new-meta clear user - coded metadata that can conflict with (dissoc meta-map :name-row :name-col :name-end-row :name-end-col) new-meta (merge new-meta (meta node))] (with-meta node new-meta))] node) node))) (comment (meta (lift-meta-content2 {:findings (atom [])} (utils/parse-string "^{:a 1 :a 2} []"))) )
7cd440a72b6df284dbbe0bd0dc62a771d2ea86a5e79989daf2349c4d98f05cd8
alura-cursos/datomic-identidades-e-queries
model.clj
(ns ecommerce.model) (defn uuid [] (java.util.UUID/randomUUID)) (defn novo-produto ; gerar ids dinamicamente ([nome slug preco] (novo-produto (uuid) nome slug preco)) ; usar ids que ja foram criados antes ([uuid nome slug preco] {:produto/id uuid :produto/nome nome :produto/slug slug :produto/preco preco})) (defn nova-categoria ([nome] (nova-categoria (uuid) nome)) ([uuid nome] {:categoria/id uuid :categoria/nome nome}))
null
https://raw.githubusercontent.com/alura-cursos/datomic-identidades-e-queries/2c14e40f02ae3ac2ebd39d2a1d07fbdc87526052/aula3.1/ecommerce/src/ecommerce/model.clj
clojure
gerar ids dinamicamente usar ids que ja foram criados antes
(ns ecommerce.model) (defn uuid [] (java.util.UUID/randomUUID)) (defn novo-produto ([nome slug preco] (novo-produto (uuid) nome slug preco)) ([uuid nome slug preco] {:produto/id uuid :produto/nome nome :produto/slug slug :produto/preco preco})) (defn nova-categoria ([nome] (nova-categoria (uuid) nome)) ([uuid nome] {:categoria/id uuid :categoria/nome nome}))
1f03aeabaa1a4f9346758ae40f83cb815aa18a30ec08cbd0451ca2878ba5ea53
clj-kafka/franzy
client_tests.clj
(ns franzy.clients.consumer.client-tests (:require [midje.sweet :refer :all] [franzy.clients.consumer.client :as cl])) (facts "Clients should instantiate properly." (fact "Invoking make-consumer with just a config map should not throw a ClassCastException when converting config map to Properties instance." (let [config {:bootstrap.servers "127.0.0.1" :value.deserializer "org.apache.kafka.common.serialization.ByteArrayDeserializer" :value.serializer "org.apache.kafka.common.serialization.ByteArrayDeserializer"}] (cl/make-consumer config) =not=> (throws ClassCastException "clojure.lang.PersistentArrayMap cannot be cast to java.util.Properties"))))
null
https://raw.githubusercontent.com/clj-kafka/franzy/6c2e2e65ad137d2bcbc04ff6e671f97ea8c0e380/core/test/franzy/clients/consumer/client_tests.clj
clojure
(ns franzy.clients.consumer.client-tests (:require [midje.sweet :refer :all] [franzy.clients.consumer.client :as cl])) (facts "Clients should instantiate properly." (fact "Invoking make-consumer with just a config map should not throw a ClassCastException when converting config map to Properties instance." (let [config {:bootstrap.servers "127.0.0.1" :value.deserializer "org.apache.kafka.common.serialization.ByteArrayDeserializer" :value.serializer "org.apache.kafka.common.serialization.ByteArrayDeserializer"}] (cl/make-consumer config) =not=> (throws ClassCastException "clojure.lang.PersistentArrayMap cannot be cast to java.util.Properties"))))
e4a3fb88b886db4f9f5e79c153f772566d633dd82d474969e7c9d94d20436bda
informatimago/lisp
wang-cl.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (shadow '(trace untrace)) (defun trace (functions) (eval `(cl:trace ,@functions))) (defun untrace (functions) (eval `(cl:untrace ,@functions))) (defun define (definitions) (dolist (def definitions) (eval (if (and (consp (second def)) (eq 'lambda (car (second def)))) `(progn (defun ,(first def) ,@(cdr (second def))) (defparameter ,(first def) ,(second def))) `(defparameter ,(first def) ,(second def)))))) (defun stop (arguments) (throw 'driver-end-of-deck nil)) (defun fin (arguments) (throw 'driver-end-of-deck nil)) (defun test (arguments) (princ arguments) (terpri)) (defun driver (path) (with-open-file (cards path) (catch 'driver-end-of-deck (loop (let ((first-char (read-char cards))) (if (char= #\* first-char) (read-line cards) ; comment (progn (unread-char first-char cards) (let* ((command (read cards)) (arguments (if (member command '(stop fin test)) (list (read-line cards)) (read cards)))) (print (apply command arguments)))))))))) (driver "wang.job")
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/small-cl-pgms/wang-cl.lisp
lisp
comment
(eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (shadow '(trace untrace)) (defun trace (functions) (eval `(cl:trace ,@functions))) (defun untrace (functions) (eval `(cl:untrace ,@functions))) (defun define (definitions) (dolist (def definitions) (eval (if (and (consp (second def)) (eq 'lambda (car (second def)))) `(progn (defun ,(first def) ,@(cdr (second def))) (defparameter ,(first def) ,(second def))) `(defparameter ,(first def) ,(second def)))))) (defun stop (arguments) (throw 'driver-end-of-deck nil)) (defun fin (arguments) (throw 'driver-end-of-deck nil)) (defun test (arguments) (princ arguments) (terpri)) (defun driver (path) (with-open-file (cards path) (catch 'driver-end-of-deck (loop (let ((first-char (read-char cards))) (if (char= #\* first-char) (progn (unread-char first-char cards) (let* ((command (read cards)) (arguments (if (member command '(stop fin test)) (list (read-line cards)) (read cards)))) (print (apply command arguments)))))))))) (driver "wang.job")
0e6a131ce4daafbbd287ab40b6fb38020b6c752a2ebe76f428ba8c4dda490c5e
silkapp/generic-aeson
IsEnum.hs
{-# LANGUAGE FlexibleContexts , FlexibleInstances , ScopedTypeVariables , TypeOperators #-} | Test if a data type is an enumeration ( only zero - argument constructors ) generically using " GHC.Generics " . module Generics.Generic.IsEnum ( isEnum , GIsEnum (..) ) where import Data.Proxy import GHC.Generics | Class for testing if the functors from " GHC.Generics " are -- enumerations. You generally don't need to give any custom -- instances. Just call 'isEnum'. class GIsEnum f where gIsEnum :: Proxy (f a) -> Bool instance GIsEnum V1 where gIsEnum _ = False instance GIsEnum (K1 i a) where gIsEnum _ = False instance GIsEnum U1 where gIsEnum _ = True instance GIsEnum Par1 where gIsEnum _ = False should be K1 R instance GIsEnum (Rec1 f) where gIsEnum _ = False instance (GIsEnum f, GIsEnum g) => GIsEnum (f :+: g) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) && gIsEnum (Proxy :: Proxy (g a)) instance (GIsEnum f, GIsEnum g) => GIsEnum (f :*: g) where gIsEnum _ = False instance GIsEnum f => GIsEnum (M1 C c f) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) instance GIsEnum (M1 S c a) where gIsEnum _ = False instance GIsEnum f => GIsEnum (M1 D c f) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) instance GIsEnum ( f : . : ) where | test if a data type is an enumeration . isEnum :: forall a. (Generic a, GIsEnum (Rep a)) => Proxy a -> Bool isEnum _ = gIsEnum (Proxy :: Proxy ((Rep a) a))
null
https://raw.githubusercontent.com/silkapp/generic-aeson/d461fffa6731391470ac344b6bdc5a8e88b436ca/src/Generics/Generic/IsEnum.hs
haskell
# LANGUAGE FlexibleContexts , FlexibleInstances , ScopedTypeVariables , TypeOperators # enumerations. You generally don't need to give any custom instances. Just call 'isEnum'.
| Test if a data type is an enumeration ( only zero - argument constructors ) generically using " GHC.Generics " . module Generics.Generic.IsEnum ( isEnum , GIsEnum (..) ) where import Data.Proxy import GHC.Generics | Class for testing if the functors from " GHC.Generics " are class GIsEnum f where gIsEnum :: Proxy (f a) -> Bool instance GIsEnum V1 where gIsEnum _ = False instance GIsEnum (K1 i a) where gIsEnum _ = False instance GIsEnum U1 where gIsEnum _ = True instance GIsEnum Par1 where gIsEnum _ = False should be K1 R instance GIsEnum (Rec1 f) where gIsEnum _ = False instance (GIsEnum f, GIsEnum g) => GIsEnum (f :+: g) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) && gIsEnum (Proxy :: Proxy (g a)) instance (GIsEnum f, GIsEnum g) => GIsEnum (f :*: g) where gIsEnum _ = False instance GIsEnum f => GIsEnum (M1 C c f) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) instance GIsEnum (M1 S c a) where gIsEnum _ = False instance GIsEnum f => GIsEnum (M1 D c f) where gIsEnum _ = gIsEnum (Proxy :: Proxy (f a)) instance GIsEnum ( f : . : ) where | test if a data type is an enumeration . isEnum :: forall a. (Generic a, GIsEnum (Rep a)) => Proxy a -> Bool isEnum _ = gIsEnum (Proxy :: Proxy ((Rep a) a))
64e32688705da8d9d30a2b55034df97a051cc3c4914127d968862ddd6660cc12
cxxxr/jsonrpc
utils.lisp
(in-package #:cl-user) (defpackage #:jsonrpc/utils (:use #:cl) (:import-from #:usocket #:socket-listen #:socket-close #:address-in-use-error) (:import-from #:bordeaux-threads #:make-lock #:with-lock-held) (:export #:random-port #:make-id #:find-mode-class)) (in-package #:jsonrpc/utils) (defun port-available-p (port) (handler-case (let ((socket (usocket:socket-listen "127.0.0.1" port :reuse-address t))) (usocket:socket-close socket)) (usocket:address-in-use-error (e) (declare (ignore e)) nil))) (defun random-port () "Return a port number not in use from 50000 to 60000." (loop for port from (+ 50000 (random 1000)) upto 60000 if (port-available-p port) return port)) (defun make-id (&optional (length 12)) (declare (type fixnum length)) (let ((result (make-string length))) (declare (type simple-string result)) (dotimes (i length result) (setf (aref result i) (ecase (random 5) ((0 1) (code-char (+ #.(char-code #\a) (random 26)))) ((2 3) (code-char (+ #.(char-code #\A) (random 26)))) ((4) (code-char (+ #.(char-code #\0) (random 10))))))))) (defvar *transport-load-lock* (bt:make-recursive-lock)) (defun find-mode-class (mode) (let ((system-name (format nil "jsonrpc/transport/~(~A~)" mode)) (package-name (format nil "~A/~A" :jsonrpc/transport mode))) (let ((package (bt:with-lock-held (*transport-load-lock*) (or (find-package package-name) (progn #+quicklisp (ql:quickload system-name :silent t) #-quicklisp (asdf:load-system system-name :verbose nil) (find-package package-name)))))) (and package (find-class (intern (format nil "~A-~A" mode :transport) package))))))
null
https://raw.githubusercontent.com/cxxxr/jsonrpc/9f7708a9bc8d6f1a9e3a946188c4772adf752058/utils.lisp
lisp
(in-package #:cl-user) (defpackage #:jsonrpc/utils (:use #:cl) (:import-from #:usocket #:socket-listen #:socket-close #:address-in-use-error) (:import-from #:bordeaux-threads #:make-lock #:with-lock-held) (:export #:random-port #:make-id #:find-mode-class)) (in-package #:jsonrpc/utils) (defun port-available-p (port) (handler-case (let ((socket (usocket:socket-listen "127.0.0.1" port :reuse-address t))) (usocket:socket-close socket)) (usocket:address-in-use-error (e) (declare (ignore e)) nil))) (defun random-port () "Return a port number not in use from 50000 to 60000." (loop for port from (+ 50000 (random 1000)) upto 60000 if (port-available-p port) return port)) (defun make-id (&optional (length 12)) (declare (type fixnum length)) (let ((result (make-string length))) (declare (type simple-string result)) (dotimes (i length result) (setf (aref result i) (ecase (random 5) ((0 1) (code-char (+ #.(char-code #\a) (random 26)))) ((2 3) (code-char (+ #.(char-code #\A) (random 26)))) ((4) (code-char (+ #.(char-code #\0) (random 10))))))))) (defvar *transport-load-lock* (bt:make-recursive-lock)) (defun find-mode-class (mode) (let ((system-name (format nil "jsonrpc/transport/~(~A~)" mode)) (package-name (format nil "~A/~A" :jsonrpc/transport mode))) (let ((package (bt:with-lock-held (*transport-load-lock*) (or (find-package package-name) (progn #+quicklisp (ql:quickload system-name :silent t) #-quicklisp (asdf:load-system system-name :verbose nil) (find-package package-name)))))) (and package (find-class (intern (format nil "~A-~A" mode :transport) package))))))
94fb171bcd0df179b123b5e572a21067964c4a8b666b644188617e75ca4c66b9
dyzsr/ocaml-selectml
flambda_utils.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro and , (* *) (* Copyright 2013--2016 OCamlPro SAS *) Copyright 2014 - -2016 Jane Street Group LLC (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) [@@@ocaml.warning "+a-4-9-30-40-41-42-66"] open! Int_replace_polymorphic_compare let name_expr ~name (named : Flambda.named) : Flambda.t = let var = Variable.create ~current_compilation_unit:(Compilation_unit.get_current_exn ()) name in Flambda.create_let var named (Var var) let name_expr_from_var ~var (named : Flambda.named) : Flambda.t = let var = Variable.rename ~current_compilation_unit:(Compilation_unit.get_current_exn ()) var in Flambda.create_let var named (Var var) let find_declaration cf ({ funs } : Flambda.function_declarations) = Variable.Map.find (Closure_id.unwrap cf) funs let find_declaration_variable cf ({ funs } : Flambda.function_declarations) = let var = Closure_id.unwrap cf in if not (Variable.Map.mem var funs) then raise Not_found else var let find_free_variable cv ({ free_vars } : Flambda.set_of_closures) = let var : Flambda.specialised_to = Variable.Map.find (Var_within_closure.unwrap cv) free_vars in var.var let function_arity (f : Flambda.function_declaration) = List.length f.params let variables_bound_by_the_closure cf (decls : Flambda.function_declarations) = let func = find_declaration cf decls in let params = Parameter.Set.vars func.params in let functions = Variable.Map.keys decls.funs in Variable.Set.diff (Variable.Set.diff func.free_variables params) functions let description_of_toplevel_node (expr : Flambda.t) = match expr with | Var id -> Format.asprintf "var %a" Variable.print id | Apply _ -> "apply" | Assign _ -> "assign" | Send _ -> "send" | Proved_unreachable -> "unreachable" | Let { var; _ } -> Format.asprintf "let %a" Variable.print var | Let_mutable _ -> "let_mutable" | Let_rec _ -> "letrec" | If_then_else _ -> "if" | Switch _ -> "switch" | String_switch _ -> "stringswitch" | Static_raise _ -> "staticraise" | Static_catch _ -> "catch" | Try_with _ -> "trywith" | While _ -> "while" | For _ -> "for" let equal_direction_flag (x : Asttypes.direction_flag) (y : Asttypes.direction_flag) = match x, y with | Upto, Upto -> true | Downto, Downto -> true | (Upto | Downto), _ -> false let rec same (l1 : Flambda.t) (l2 : Flambda.t) = l1 == l2 || (* it is ok for the string case: if they are physically the same, it is the same original branch *) match (l1, l2) with | Var v1 , Var v2 -> Variable.equal v1 v2 | Var _, _ | _, Var _ -> false | Apply a1 , Apply a2 -> Flambda.equal_call_kind a1.kind a2.kind && Variable.equal a1.func a2.func && Misc.Stdlib.List.equal Variable.equal a1.args a2.args | Apply _, _ | _, Apply _ -> false | Let { var = var1; defining_expr = defining_expr1; body = body1; _ }, Let { var = var2; defining_expr = defining_expr2; body = body2; _ } -> Variable.equal var1 var2 && same_named defining_expr1 defining_expr2 && same body1 body2 | Let _, _ | _, Let _ -> false | Let_mutable {var = mv1; initial_value = v1; contents_kind = ck1; body = b1}, Let_mutable {var = mv2; initial_value = v2; contents_kind = ck2; body = b2} -> Mutable_variable.equal mv1 mv2 && Variable.equal v1 v2 && Lambda.equal_value_kind ck1 ck2 && same b1 b2 | Let_mutable _, _ | _, Let_mutable _ -> false | Let_rec (bl1, a1), Let_rec (bl2, a2) -> Misc.Stdlib.List.equal samebinding bl1 bl2 && same a1 a2 | Let_rec _, _ | _, Let_rec _ -> false | Switch (a1, s1), Switch (a2, s2) -> Variable.equal a1 a2 && sameswitch s1 s2 | Switch _, _ | _, Switch _ -> false | String_switch (a1, s1, d1), String_switch (a2, s2, d2) -> Variable.equal a1 a2 && Misc.Stdlib.List.equal (fun (s1, e1) (s2, e2) -> String.equal s1 s2 && same e1 e2) s1 s2 && Option.equal same d1 d2 | String_switch _, _ | _, String_switch _ -> false | Static_raise (e1, a1), Static_raise (e2, a2) -> Static_exception.equal e1 e2 && Misc.Stdlib.List.equal Variable.equal a1 a2 | Static_raise _, _ | _, Static_raise _ -> false | Static_catch (s1, v1, a1, b1), Static_catch (s2, v2, a2, b2) -> Static_exception.equal s1 s2 && Misc.Stdlib.List.equal Variable.equal v1 v2 && same a1 a2 && same b1 b2 | Static_catch _, _ | _, Static_catch _ -> false | Try_with (a1, v1, b1), Try_with (a2, v2, b2) -> same a1 a2 && Variable.equal v1 v2 && same b1 b2 | Try_with _, _ | _, Try_with _ -> false | If_then_else (a1, b1, c1), If_then_else (a2, b2, c2) -> Variable.equal a1 a2 && same b1 b2 && same c1 c2 | If_then_else _, _ | _, If_then_else _ -> false | While (a1, b1), While (a2, b2) -> same a1 a2 && same b1 b2 | While _, _ | _, While _ -> false | For { bound_var = bound_var1; from_value = from_value1; to_value = to_value1; direction = direction1; body = body1; }, For { bound_var = bound_var2; from_value = from_value2; to_value = to_value2; direction = direction2; body = body2; } -> Variable.equal bound_var1 bound_var2 && Variable.equal from_value1 from_value2 && Variable.equal to_value1 to_value2 && equal_direction_flag direction1 direction2 && same body1 body2 | For _, _ | _, For _ -> false | Assign { being_assigned = being_assigned1; new_value = new_value1; }, Assign { being_assigned = being_assigned2; new_value = new_value2; } -> Mutable_variable.equal being_assigned1 being_assigned2 && Variable.equal new_value1 new_value2 | Assign _, _ | _, Assign _ -> false | Send { kind = kind1; meth = meth1; obj = obj1; args = args1; dbg = _; }, Send { kind = kind2; meth = meth2; obj = obj2; args = args2; dbg = _; } -> Lambda.equal_meth_kind kind1 kind2 && Variable.equal meth1 meth2 && Variable.equal obj1 obj2 && Misc.Stdlib.List.equal Variable.equal args1 args2 | Send _, _ | _, Send _ -> false | Proved_unreachable, Proved_unreachable -> true and same_named (named1 : Flambda.named) (named2 : Flambda.named) = match named1, named2 with | Symbol s1 , Symbol s2 -> Symbol.equal s1 s2 | Symbol _, _ | _, Symbol _ -> false | Const c1, Const c2 -> Flambda.compare_const c1 c2 = 0 | Const _, _ | _, Const _ -> false | Allocated_const c1, Allocated_const c2 -> Allocated_const.compare c1 c2 = 0 | Allocated_const _, _ | _, Allocated_const _ -> false | Read_mutable mv1, Read_mutable mv2 -> Mutable_variable.equal mv1 mv2 | Read_mutable _, _ | _, Read_mutable _ -> false | Read_symbol_field (s1, i1), Read_symbol_field (s2, i2) -> Symbol.equal s1 s2 && i1 = i2 | Read_symbol_field _, _ | _, Read_symbol_field _ -> false | Set_of_closures s1, Set_of_closures s2 -> same_set_of_closures s1 s2 | Set_of_closures _, _ | _, Set_of_closures _ -> false | Project_closure f1, Project_closure f2 -> same_project_closure f1 f2 | Project_closure _, _ | _, Project_closure _ -> false | Project_var v1, Project_var v2 -> Variable.equal v1.closure v2.closure && Closure_id.equal v1.closure_id v2.closure_id && Var_within_closure.equal v1.var v2.var | Project_var _, _ | _, Project_var _ -> false | Move_within_set_of_closures m1, Move_within_set_of_closures m2 -> same_move_within_set_of_closures m1 m2 | Move_within_set_of_closures _, _ | _, Move_within_set_of_closures _ -> false | Prim (p1, al1, _), Prim (p2, al2, _) -> Clambda_primitives.equal p1 p2 && Misc.Stdlib.List.equal Variable.equal al1 al2 | Prim _, _ | _, Prim _ -> false | Expr e1, Expr e2 -> same e1 e2 and sameclosure (c1 : Flambda.function_declaration) (c2 : Flambda.function_declaration) = Misc.Stdlib.List.equal Parameter.equal c1.params c2.params && same c1.body c2.body and same_set_of_closures (c1 : Flambda.set_of_closures) (c2 : Flambda.set_of_closures) = Variable.Map.equal sameclosure c1.function_decls.funs c2.function_decls.funs && Variable.Map.equal Flambda.equal_specialised_to c1.free_vars c2.free_vars && Variable.Map.equal Flambda.equal_specialised_to c1.specialised_args c2.specialised_args and same_project_closure (s1 : Flambda.project_closure) (s2 : Flambda.project_closure) = Variable.equal s1.set_of_closures s2.set_of_closures && Closure_id.equal s1.closure_id s2.closure_id and same_move_within_set_of_closures (m1 : Flambda.move_within_set_of_closures) (m2 : Flambda.move_within_set_of_closures) = Variable.equal m1.closure m2.closure && Closure_id.equal m1.start_from m2.start_from && Closure_id.equal m1.move_to m2.move_to and samebinding (v1, n1) (v2, n2) = Variable.equal v1 v2 && same_named n1 n2 and sameswitch (fs1 : Flambda.switch) (fs2 : Flambda.switch) = let samecase (n1, a1) (n2, a2) = n1 = n2 && same a1 a2 in Numbers.Int.Set.equal fs1.numconsts fs2.numconsts && Numbers.Int.Set.equal fs1.numblocks fs2.numblocks && Misc.Stdlib.List.equal samecase fs1.consts fs2.consts && Misc.Stdlib.List.equal samecase fs1.blocks fs2.blocks && Option.equal same fs1.failaction fs2.failaction let can_be_merged = same (* CR-soon mshinwell: this should use the explicit ignore functions *) let toplevel_substitution sb tree = let sb' = sb in let sb v = try Variable.Map.find v sb with Not_found -> v in let aux (flam : Flambda.t) : Flambda.t = match flam with | Var var -> let var = sb var in Var var | Let_mutable mutable_let -> let initial_value = sb mutable_let.initial_value in Let_mutable { mutable_let with initial_value } | Assign { being_assigned; new_value; } -> let new_value = sb new_value in Assign { being_assigned; new_value; } | Apply { func; args; kind; dbg; inline; specialise; } -> let func = sb func in let args = List.map sb args in Apply { func; args; kind; dbg; inline; specialise; } | If_then_else (cond, e1, e2) -> let cond = sb cond in If_then_else (cond, e1, e2) | Switch (cond, sw) -> let cond = sb cond in Switch (cond, sw) | String_switch (cond, branches, def) -> let cond = sb cond in String_switch (cond, branches, def) | Send { kind; meth; obj; args; dbg } -> let meth = sb meth in let obj = sb obj in let args = List.map sb args in Send { kind; meth; obj; args; dbg } | For { bound_var; from_value; to_value; direction; body } -> let from_value = sb from_value in let to_value = sb to_value in For { bound_var; from_value; to_value; direction; body } | Static_raise (static_exn, args) -> let args = List.map sb args in Static_raise (static_exn, args) | Static_catch _ | Try_with _ | While _ | Let _ | Let_rec _ | Proved_unreachable -> flam in let aux_named (named : Flambda.named) : Flambda.named = match named with | Symbol _ | Const _ | Expr _ -> named | Allocated_const _ | Read_mutable _ -> named | Read_symbol_field _ -> named | Set_of_closures set_of_closures -> let set_of_closures = Flambda.create_set_of_closures ~function_decls:set_of_closures.function_decls ~free_vars: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.free_vars) ~specialised_args: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.specialised_args) ~direct_call_surrogates:set_of_closures.direct_call_surrogates in Set_of_closures set_of_closures | Project_closure project_closure -> Project_closure { project_closure with set_of_closures = sb project_closure.set_of_closures; } | Move_within_set_of_closures move_within_set_of_closures -> Move_within_set_of_closures { move_within_set_of_closures with closure = sb move_within_set_of_closures.closure; } | Project_var project_var -> Project_var { project_var with closure = sb project_var.closure; } | Prim (prim, args, dbg) -> Prim (prim, List.map sb args, dbg) in if Variable.Map.is_empty sb' then tree else Flambda_iterators.map_toplevel aux aux_named tree (* CR-someday mshinwell: Fix [Flambda_iterators] so this can be implemented properly. *) let toplevel_substitution_named sb named = let name = Internal_variable_names.toplevel_substitution_named in let expr = name_expr named ~name in match toplevel_substitution sb expr with | Let let_expr -> let_expr.defining_expr | _ -> assert false let make_closure_declaration ~is_classic_mode ~id ~body ~params : Flambda.t = let free_variables = Flambda.free_variables body in let param_set = Parameter.Set.vars params in if not (Variable.Set.subset param_set free_variables) then begin Misc.fatal_error "Flambda_utils.make_closure_declaration" end; let sb = Variable.Set.fold (fun id sb -> Variable.Map.add id (Variable.rename id) sb) free_variables Variable.Map.empty in (* CR-soon mshinwell: try to eliminate this [toplevel_substitution]. This function is only called from [Inline_and_simplify], so we should be able to do something similar to what happens in [Inlining_transforms] now. *) let body = toplevel_substitution sb body in let subst id = Variable.Map.find id sb in let subst_param param = Parameter.map_var subst param in let function_declaration = Flambda.create_function_declaration ~params:(List.map subst_param params) ~body ~stub:true ~dbg:Debuginfo.none ~inline:Default_inline ~specialise:Default_specialise ~is_a_functor:false ~closure_origin:(Closure_origin.create (Closure_id.wrap id)) ~poll:Default_poll in begin assert (Variable.Set.equal (Variable.Set.map subst free_variables) function_declaration.free_variables); end; let free_vars = Variable.Map.fold (fun id id' fv' -> let spec_to : Flambda.specialised_to = { var = id; projection = None; } in Variable.Map.add id' spec_to fv') (Variable.Map.filter (fun id _ -> not (Variable.Set.mem id param_set)) sb) Variable.Map.empty in let compilation_unit = Compilation_unit.get_current_exn () in let set_of_closures_var = Variable.create Internal_variable_names.set_of_closures ~current_compilation_unit:compilation_unit in let set_of_closures = let function_decls = Flambda.create_function_declarations ~is_classic_mode ~funs:(Variable.Map.singleton id function_declaration) in Flambda.create_set_of_closures ~function_decls ~free_vars ~specialised_args:Variable.Map.empty ~direct_call_surrogates:Variable.Map.empty in let project_closure : Flambda.named = Project_closure { set_of_closures = set_of_closures_var; closure_id = Closure_id.wrap id; } in let project_closure_var = Variable.create Internal_variable_names.project_closure ~current_compilation_unit:compilation_unit in Flambda.create_let set_of_closures_var (Set_of_closures set_of_closures) (Flambda.create_let project_closure_var project_closure (Var (project_closure_var))) let bind ~bindings ~body = List.fold_left (fun expr (var, var_def) -> Flambda.create_let var var_def expr) body bindings let all_lifted_constants (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Let_symbol (symbol, decl, program) -> (symbol, decl) :: (loop program) | Let_rec_symbol (decls, program) -> List.fold_left (fun l (symbol, decl) -> (symbol, decl) :: l) (loop program) decls | Initialize_symbol (_, _, _, program) | Effect (_, program) -> loop program | End _ -> [] in loop program.program_body let all_lifted_constants_as_map program = Symbol.Map.of_list (all_lifted_constants program) let initialize_symbols (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Initialize_symbol (symbol, tag, fields, program) -> (symbol, tag, fields) :: (loop program) | Effect (_, program) | Let_symbol (_, _, program) | Let_rec_symbol (_, program) -> loop program | End _ -> [] in loop program.program_body let imported_symbols (program : Flambda.program) = program.imported_symbols let needed_import_symbols (program : Flambda.program) = let dependencies = Flambda.free_symbols_program program in let defined_symbol = Symbol.Set.union (Symbol.Set.of_list (List.map fst (all_lifted_constants program))) (Symbol.Set.of_list (List.map (fun (s, _, _) -> s) (initialize_symbols program))) in Symbol.Set.diff dependencies defined_symbol let introduce_needed_import_symbols program : Flambda.program = { program with imported_symbols = needed_import_symbols program; } let root_symbol (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Effect (_, program) | Let_symbol (_, _, program) | Let_rec_symbol (_, program) | Initialize_symbol (_, _, _, program) -> loop program | End root -> root in loop program.program_body let might_raise_static_exn flam stexn = try Flambda_iterators.iter_on_named (function | Flambda.Static_raise (ex, _) when Static_exception.equal ex stexn -> raise Exit | _ -> ()) (fun _ -> ()) flam; false with Exit -> true let make_closure_map program = let map = ref Closure_id.Map.empty in let add_set_of_closures ~constant:_ : Flambda.set_of_closures -> unit = fun { function_decls } -> Variable.Map.iter (fun var _ -> let closure_id = Closure_id.wrap var in let set_of_closures_id = function_decls.set_of_closures_id in map := Closure_id.Map.add closure_id set_of_closures_id !map) function_decls.funs in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:add_set_of_closures; !map let all_lifted_constant_closures program = List.fold_left (fun unchanged flambda -> match flambda with | (_, Flambda.Set_of_closures { function_decls = { funs } }) -> Variable.Map.fold (fun key (_ : Flambda.function_declaration) acc -> Closure_id.Set.add (Closure_id.wrap key) acc) funs unchanged | _ -> unchanged) Closure_id.Set.empty (all_lifted_constants program) let all_lifted_constant_sets_of_closures program = let set = ref Set_of_closures_id.Set.empty in List.iter (function | (_, Flambda.Set_of_closures { function_decls = { set_of_closures_id } }) -> set := Set_of_closures_id.Set.add set_of_closures_id !set | _ -> ()) (all_lifted_constants program); !set let all_sets_of_closures program = let list = ref [] in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:(fun ~constant:_ set_of_closures -> list := set_of_closures :: !list); !list let all_sets_of_closures_map program = let r = ref Set_of_closures_id.Map.empty in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:(fun ~constant:_ set_of_closures -> r := Set_of_closures_id.Map.add set_of_closures.function_decls.set_of_closures_id set_of_closures !r); !r let substitute_read_symbol_field_for_variables (substitution : (Symbol.t * int list) Variable.Map.t) (expr : Flambda.t) = let bind var fresh_var (expr:Flambda.t) : Flambda.t = let symbol, path = Variable.Map.find var substitution in let rec make_named (path:int list) : Flambda.named = match path with | [] -> Symbol symbol | [i] -> Read_symbol_field (symbol, i) | h :: t -> let block_name = Internal_variable_names.symbol_field_block in let block = Variable.create block_name in let field_name = Internal_variable_names.get_symbol_field in let field = Variable.create field_name in Expr ( Flambda.create_let block (make_named t) (Flambda.create_let field (Prim (Pfield h, [block], Debuginfo.none)) (Var field))) in Flambda.create_let fresh_var (make_named path) expr in let substitute_named bindings (named:Flambda.named) : Flambda.named = let sb to_substitute = try Variable.Map.find to_substitute bindings with | Not_found -> to_substitute in match named with | Symbol _ | Const _ | Expr _ -> named | Allocated_const _ | Read_mutable _ -> named | Read_symbol_field _ -> named | Set_of_closures set_of_closures -> let set_of_closures = Flambda.create_set_of_closures ~function_decls:set_of_closures.function_decls ~free_vars: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.free_vars) ~specialised_args: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.specialised_args) ~direct_call_surrogates:set_of_closures.direct_call_surrogates in Set_of_closures set_of_closures | Project_closure project_closure -> Project_closure { project_closure with set_of_closures = sb project_closure.set_of_closures; } | Move_within_set_of_closures move_within_set_of_closures -> Move_within_set_of_closures { move_within_set_of_closures with closure = sb move_within_set_of_closures.closure; } | Project_var project_var -> Project_var { project_var with closure = sb project_var.closure; } | Prim (prim, args, dbg) -> Prim (prim, List.map sb args, dbg) in let make_var_subst var = if Variable.Map.mem var substitution then let fresh = Variable.rename var in fresh, (fun expr -> bind var fresh expr) else var, (fun x -> x) in let f (expr:Flambda.t) : Flambda.t = match expr with | Var v when Variable.Map.mem v substitution -> let fresh = Variable.rename v in bind v fresh (Var fresh) | Var _ -> expr | Let ({ var = v; defining_expr = named; _ } as let_expr) -> let to_substitute = Variable.Set.filter (fun v -> Variable.Map.mem v substitution) (Flambda.free_variables_named named) in if Variable.Set.is_empty to_substitute then expr else let bindings = Variable.Map.of_set (fun var -> Variable.rename var) to_substitute in let named = substitute_named bindings named in let expr = let module W = Flambda.With_free_variables in W.create_let_reusing_body v named (W.of_body_of_let let_expr) in Variable.Map.fold (fun to_substitute fresh expr -> bind to_substitute fresh expr) bindings expr | Let_mutable let_mutable when Variable.Map.mem let_mutable.initial_value substitution -> let fresh = Variable.rename let_mutable.initial_value in bind let_mutable.initial_value fresh (Let_mutable { let_mutable with initial_value = fresh }) | Let_mutable _ -> expr | Let_rec (defs, body) -> let free_variables_of_defs = List.fold_left (fun set (_, named) -> Variable.Set.union set (Flambda.free_variables_named named)) Variable.Set.empty defs in let to_substitute = Variable.Set.filter (fun v -> Variable.Map.mem v substitution) free_variables_of_defs in if Variable.Set.is_empty to_substitute then expr else begin let bindings = Variable.Map.of_set (fun var -> Variable.rename var) to_substitute in let defs = List.map (fun (var, named) -> var, substitute_named bindings named) defs in let expr = Flambda.Let_rec (defs, body) in Variable.Map.fold (fun to_substitute fresh expr -> bind to_substitute fresh expr) bindings expr end | If_then_else (cond, ifso, ifnot) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (If_then_else (fresh, ifso, ifnot)) | If_then_else _ -> expr | Switch (cond, sw) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (Switch (fresh, sw)) | Switch _ -> expr | String_switch (cond, sw, def) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (String_switch (fresh, sw, def)) | String_switch _ -> expr | Assign { being_assigned; new_value } when Variable.Map.mem new_value substitution -> let fresh = Variable.rename new_value in bind new_value fresh (Assign { being_assigned; new_value = fresh }) | Assign _ -> expr | Static_raise (exn, args) -> let args, bind_args = List.split (List.map make_var_subst args) in List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Static_raise (exn, args) | For { bound_var; from_value; to_value; direction; body } -> let from_value, bind_from_value = make_var_subst from_value in let to_value, bind_to_value = make_var_subst to_value in bind_from_value @@ bind_to_value @@ Flambda.For { bound_var; from_value; to_value; direction; body } | Apply { func; args; kind; dbg; inline; specialise } -> let func, bind_func = make_var_subst func in let args, bind_args = List.split (List.map make_var_subst args) in bind_func @@ List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Apply { func; args; kind; dbg; inline; specialise } | Send { kind; meth; obj; args; dbg } -> let meth, bind_meth = make_var_subst meth in let obj, bind_obj = make_var_subst obj in let args, bind_args = List.split (List.map make_var_subst args) in bind_meth @@ bind_obj @@ List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Send { kind; meth; obj; args; dbg } | Proved_unreachable | While _ | Try_with _ | Static_catch _ -> (* No variables directly used in those expressions *) expr in Flambda_iterators.map_toplevel f (fun v -> v) expr module Switch_storer = Switch.Store (struct type t = Flambda.t (* An easily-comparable subset of [Flambda.t]: currently this only supports that required to share switch branches. *) type key = | Var of Variable.t | Let of Variable.t * key_named * key | Static_raise of Static_exception.t * Variable.t list and key_named = | Symbol of Symbol.t | Const of Flambda.const | Prim of Clambda_primitives.primitive * Variable.t list | Expr of key exception Not_comparable let rec make_expr_key (expr : Flambda.t) : key = match expr with | Var v -> Var v | Let { var; defining_expr; body; } -> Let (var, make_named_key defining_expr, make_expr_key body) | Static_raise (e, args) -> Static_raise (e, args) | _ -> raise Not_comparable and make_named_key (named:Flambda.named) : key_named = match named with | Symbol s -> Symbol s | Const c -> Const c | Expr e -> Expr (make_expr_key e) | Prim (prim, args, _dbg) -> Prim (prim, args) | _ -> raise Not_comparable let make_key expr = match make_expr_key expr with | exception Not_comparable -> None | key -> Some key let compare_key e1 e2 = (* The environment [env] maps variables bound in [e2] to the corresponding bound variables in [e1]. Every variable to compare in [e2] must have an equivalent in [e1], otherwise the comparison wouldn't have gone past the [Let] binding. Hence [Variable.Map.find] is safe here. *) let compare_var env v1 v2 = match Variable.Map.find v2 env with | exception Not_found -> (* The variable is free in the expression [e2], hence we can compare it with [v1] directly. *) Variable.compare v1 v2 | bound -> Variable.compare v1 bound in let rec compare_expr env (e1 : key) (e2 : key) : int = match e1, e2 with | Var v1, Var v2 -> compare_var env v1 v2 | Var _, (Let _| Static_raise _) -> -1 | (Let _| Static_raise _), Var _ -> 1 | Let (v1, n1, b1), Let (v2, n2, b2) -> let comp_named = compare_named env n1 n2 in if comp_named <> 0 then comp_named else let env = Variable.Map.add v2 v1 env in compare_expr env b1 b2 | Let _, Static_raise _ -> -1 | Static_raise _, Let _ -> 1 | Static_raise (sexn1, args1), Static_raise (sexn2, args2) -> let comp_sexn = Static_exception.compare sexn1 sexn2 in if comp_sexn <> 0 then comp_sexn else Misc.Stdlib.List.compare (compare_var env) args1 args2 and compare_named env (n1:key_named) (n2:key_named) : int = match n1, n2 with | Symbol s1, Symbol s2 -> Symbol.compare s1 s2 | Symbol _, (Const _ | Expr _ | Prim _) -> -1 | (Const _ | Expr _ | Prim _), Symbol _ -> 1 | Const c1, Const c2 -> Flambda.compare_const c1 c2 | Const _, (Expr _ | Prim _) -> -1 | (Expr _ | Prim _), Const _ -> 1 | Expr e1, Expr e2 -> compare_expr env e1 e2 | Expr _, Prim _ -> -1 | Prim _, Expr _ -> 1 | Prim (prim1, args1), Prim (prim2, args2) -> let comp_prim = Stdlib.compare prim1 prim2 in if comp_prim <> 0 then comp_prim else Misc.Stdlib.List.compare (compare_var env) args1 args2 in compare_expr Variable.Map.empty e1 e2 end) let fun_vars_referenced_in_decls (function_decls : Flambda.function_declarations) ~closure_symbol = let fun_vars = Variable.Map.keys function_decls.funs in let symbols_to_fun_vars = Variable.Set.fold (fun fun_var symbols_to_fun_vars -> let closure_id = Closure_id.wrap fun_var in let symbol = closure_symbol closure_id in Symbol.Map.add symbol fun_var symbols_to_fun_vars) fun_vars Symbol.Map.empty in Variable.Map.map (fun (func_decl : Flambda.function_declaration) -> let from_symbols = Symbol.Set.fold (fun symbol fun_vars' -> match Symbol.Map.find symbol symbols_to_fun_vars with | exception Not_found -> fun_vars' | fun_var -> assert (Variable.Set.mem fun_var fun_vars); Variable.Set.add fun_var fun_vars') func_decl.free_symbols Variable.Set.empty in let from_variables = Variable.Set.inter func_decl.free_variables fun_vars in Variable.Set.union from_symbols from_variables) function_decls.funs let closures_required_by_entry_point ~(entry_point : Closure_id.t) ~closure_symbol (function_decls : Flambda.function_declarations) = let dependencies = fun_vars_referenced_in_decls function_decls ~closure_symbol in let set = ref Variable.Set.empty in let queue = Queue.create () in let add v = if not (Variable.Set.mem v !set) then begin set := Variable.Set.add v !set; Queue.push v queue end in add (Closure_id.unwrap entry_point); while not (Queue.is_empty queue) do let fun_var = Queue.pop queue in match Variable.Map.find fun_var dependencies with | exception Not_found -> () | fun_dependencies -> Variable.Set.iter (fun dep -> if Variable.Map.mem dep function_decls.funs then add dep) fun_dependencies done; !set let all_functions_parameters (function_decls : Flambda.function_declarations) = Variable.Map.fold (fun _ ({ params } : Flambda.function_declaration) set -> Variable.Set.union set (Parameter.Set.vars params)) function_decls.funs Variable.Set.empty let all_free_symbols (function_decls : Flambda.function_declarations) = Variable.Map.fold (fun _ (function_decl : Flambda.function_declaration) syms -> Symbol.Set.union syms function_decl.free_symbols) function_decls.funs Symbol.Set.empty let contains_stub (fun_decls : Flambda.function_declarations) = let number_of_stub_functions = Variable.Map.cardinal (Variable.Map.filter (fun _ { Flambda.stub } -> stub) fun_decls.funs) in number_of_stub_functions > 0 let clean_projections ~which_variables = Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> match spec_to.projection with | None -> spec_to | Some projection -> let from = Projection.projecting_from projection in if Variable.Map.mem from which_variables then spec_to else ({ spec_to with projection = None; } : Flambda.specialised_to)) which_variables let projection_to_named (projection : Projection.t) : Flambda.named = match projection with | Project_var project_var -> Project_var project_var | Project_closure project_closure -> Project_closure project_closure | Move_within_set_of_closures move -> Move_within_set_of_closures move | Field (field_index, var) -> Prim (Pfield field_index, [var], Debuginfo.none) type specialised_to_same_as = | Not_specialised | Specialised_and_aliased_to of Variable.Set.t let parameters_specialised_to_the_same_variable ~(function_decls : Flambda.function_declarations) ~(specialised_args : Flambda.specialised_to Variable.Map.t) = let specialised_arg_aliasing = (* For each external variable involved in a specialisation, which internal variable(s) it maps to via that specialisation. *) Variable.Map.transpose_keys_and_data_set (Variable.Map.map (fun ({ var; _ } : Flambda.specialised_to) -> var) specialised_args) in Variable.Map.map (fun ({ params; _ } : Flambda.function_declaration) -> List.map (fun param -> match Variable.Map.find (Parameter.var param) specialised_args with | exception Not_found -> Not_specialised | { var; _ } -> Specialised_and_aliased_to (Variable.Map.find var specialised_arg_aliasing)) params) function_decls.funs
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/middle_end/flambda/flambda_utils.ml
ocaml
************************************************************************ OCaml Copyright 2013--2016 OCamlPro SAS All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ it is ok for the string case: if they are physically the same, it is the same original branch CR-soon mshinwell: this should use the explicit ignore functions CR-someday mshinwell: Fix [Flambda_iterators] so this can be implemented properly. CR-soon mshinwell: try to eliminate this [toplevel_substitution]. This function is only called from [Inline_and_simplify], so we should be able to do something similar to what happens in [Inlining_transforms] now. No variables directly used in those expressions An easily-comparable subset of [Flambda.t]: currently this only supports that required to share switch branches. The environment [env] maps variables bound in [e2] to the corresponding bound variables in [e1]. Every variable to compare in [e2] must have an equivalent in [e1], otherwise the comparison wouldn't have gone past the [Let] binding. Hence [Variable.Map.find] is safe here. The variable is free in the expression [e2], hence we can compare it with [v1] directly. For each external variable involved in a specialisation, which internal variable(s) it maps to via that specialisation.
, OCamlPro and , Copyright 2014 - -2016 Jane Street Group LLC the GNU Lesser General Public License version 2.1 , with the [@@@ocaml.warning "+a-4-9-30-40-41-42-66"] open! Int_replace_polymorphic_compare let name_expr ~name (named : Flambda.named) : Flambda.t = let var = Variable.create ~current_compilation_unit:(Compilation_unit.get_current_exn ()) name in Flambda.create_let var named (Var var) let name_expr_from_var ~var (named : Flambda.named) : Flambda.t = let var = Variable.rename ~current_compilation_unit:(Compilation_unit.get_current_exn ()) var in Flambda.create_let var named (Var var) let find_declaration cf ({ funs } : Flambda.function_declarations) = Variable.Map.find (Closure_id.unwrap cf) funs let find_declaration_variable cf ({ funs } : Flambda.function_declarations) = let var = Closure_id.unwrap cf in if not (Variable.Map.mem var funs) then raise Not_found else var let find_free_variable cv ({ free_vars } : Flambda.set_of_closures) = let var : Flambda.specialised_to = Variable.Map.find (Var_within_closure.unwrap cv) free_vars in var.var let function_arity (f : Flambda.function_declaration) = List.length f.params let variables_bound_by_the_closure cf (decls : Flambda.function_declarations) = let func = find_declaration cf decls in let params = Parameter.Set.vars func.params in let functions = Variable.Map.keys decls.funs in Variable.Set.diff (Variable.Set.diff func.free_variables params) functions let description_of_toplevel_node (expr : Flambda.t) = match expr with | Var id -> Format.asprintf "var %a" Variable.print id | Apply _ -> "apply" | Assign _ -> "assign" | Send _ -> "send" | Proved_unreachable -> "unreachable" | Let { var; _ } -> Format.asprintf "let %a" Variable.print var | Let_mutable _ -> "let_mutable" | Let_rec _ -> "letrec" | If_then_else _ -> "if" | Switch _ -> "switch" | String_switch _ -> "stringswitch" | Static_raise _ -> "staticraise" | Static_catch _ -> "catch" | Try_with _ -> "trywith" | While _ -> "while" | For _ -> "for" let equal_direction_flag (x : Asttypes.direction_flag) (y : Asttypes.direction_flag) = match x, y with | Upto, Upto -> true | Downto, Downto -> true | (Upto | Downto), _ -> false let rec same (l1 : Flambda.t) (l2 : Flambda.t) = match (l1, l2) with | Var v1 , Var v2 -> Variable.equal v1 v2 | Var _, _ | _, Var _ -> false | Apply a1 , Apply a2 -> Flambda.equal_call_kind a1.kind a2.kind && Variable.equal a1.func a2.func && Misc.Stdlib.List.equal Variable.equal a1.args a2.args | Apply _, _ | _, Apply _ -> false | Let { var = var1; defining_expr = defining_expr1; body = body1; _ }, Let { var = var2; defining_expr = defining_expr2; body = body2; _ } -> Variable.equal var1 var2 && same_named defining_expr1 defining_expr2 && same body1 body2 | Let _, _ | _, Let _ -> false | Let_mutable {var = mv1; initial_value = v1; contents_kind = ck1; body = b1}, Let_mutable {var = mv2; initial_value = v2; contents_kind = ck2; body = b2} -> Mutable_variable.equal mv1 mv2 && Variable.equal v1 v2 && Lambda.equal_value_kind ck1 ck2 && same b1 b2 | Let_mutable _, _ | _, Let_mutable _ -> false | Let_rec (bl1, a1), Let_rec (bl2, a2) -> Misc.Stdlib.List.equal samebinding bl1 bl2 && same a1 a2 | Let_rec _, _ | _, Let_rec _ -> false | Switch (a1, s1), Switch (a2, s2) -> Variable.equal a1 a2 && sameswitch s1 s2 | Switch _, _ | _, Switch _ -> false | String_switch (a1, s1, d1), String_switch (a2, s2, d2) -> Variable.equal a1 a2 && Misc.Stdlib.List.equal (fun (s1, e1) (s2, e2) -> String.equal s1 s2 && same e1 e2) s1 s2 && Option.equal same d1 d2 | String_switch _, _ | _, String_switch _ -> false | Static_raise (e1, a1), Static_raise (e2, a2) -> Static_exception.equal e1 e2 && Misc.Stdlib.List.equal Variable.equal a1 a2 | Static_raise _, _ | _, Static_raise _ -> false | Static_catch (s1, v1, a1, b1), Static_catch (s2, v2, a2, b2) -> Static_exception.equal s1 s2 && Misc.Stdlib.List.equal Variable.equal v1 v2 && same a1 a2 && same b1 b2 | Static_catch _, _ | _, Static_catch _ -> false | Try_with (a1, v1, b1), Try_with (a2, v2, b2) -> same a1 a2 && Variable.equal v1 v2 && same b1 b2 | Try_with _, _ | _, Try_with _ -> false | If_then_else (a1, b1, c1), If_then_else (a2, b2, c2) -> Variable.equal a1 a2 && same b1 b2 && same c1 c2 | If_then_else _, _ | _, If_then_else _ -> false | While (a1, b1), While (a2, b2) -> same a1 a2 && same b1 b2 | While _, _ | _, While _ -> false | For { bound_var = bound_var1; from_value = from_value1; to_value = to_value1; direction = direction1; body = body1; }, For { bound_var = bound_var2; from_value = from_value2; to_value = to_value2; direction = direction2; body = body2; } -> Variable.equal bound_var1 bound_var2 && Variable.equal from_value1 from_value2 && Variable.equal to_value1 to_value2 && equal_direction_flag direction1 direction2 && same body1 body2 | For _, _ | _, For _ -> false | Assign { being_assigned = being_assigned1; new_value = new_value1; }, Assign { being_assigned = being_assigned2; new_value = new_value2; } -> Mutable_variable.equal being_assigned1 being_assigned2 && Variable.equal new_value1 new_value2 | Assign _, _ | _, Assign _ -> false | Send { kind = kind1; meth = meth1; obj = obj1; args = args1; dbg = _; }, Send { kind = kind2; meth = meth2; obj = obj2; args = args2; dbg = _; } -> Lambda.equal_meth_kind kind1 kind2 && Variable.equal meth1 meth2 && Variable.equal obj1 obj2 && Misc.Stdlib.List.equal Variable.equal args1 args2 | Send _, _ | _, Send _ -> false | Proved_unreachable, Proved_unreachable -> true and same_named (named1 : Flambda.named) (named2 : Flambda.named) = match named1, named2 with | Symbol s1 , Symbol s2 -> Symbol.equal s1 s2 | Symbol _, _ | _, Symbol _ -> false | Const c1, Const c2 -> Flambda.compare_const c1 c2 = 0 | Const _, _ | _, Const _ -> false | Allocated_const c1, Allocated_const c2 -> Allocated_const.compare c1 c2 = 0 | Allocated_const _, _ | _, Allocated_const _ -> false | Read_mutable mv1, Read_mutable mv2 -> Mutable_variable.equal mv1 mv2 | Read_mutable _, _ | _, Read_mutable _ -> false | Read_symbol_field (s1, i1), Read_symbol_field (s2, i2) -> Symbol.equal s1 s2 && i1 = i2 | Read_symbol_field _, _ | _, Read_symbol_field _ -> false | Set_of_closures s1, Set_of_closures s2 -> same_set_of_closures s1 s2 | Set_of_closures _, _ | _, Set_of_closures _ -> false | Project_closure f1, Project_closure f2 -> same_project_closure f1 f2 | Project_closure _, _ | _, Project_closure _ -> false | Project_var v1, Project_var v2 -> Variable.equal v1.closure v2.closure && Closure_id.equal v1.closure_id v2.closure_id && Var_within_closure.equal v1.var v2.var | Project_var _, _ | _, Project_var _ -> false | Move_within_set_of_closures m1, Move_within_set_of_closures m2 -> same_move_within_set_of_closures m1 m2 | Move_within_set_of_closures _, _ | _, Move_within_set_of_closures _ -> false | Prim (p1, al1, _), Prim (p2, al2, _) -> Clambda_primitives.equal p1 p2 && Misc.Stdlib.List.equal Variable.equal al1 al2 | Prim _, _ | _, Prim _ -> false | Expr e1, Expr e2 -> same e1 e2 and sameclosure (c1 : Flambda.function_declaration) (c2 : Flambda.function_declaration) = Misc.Stdlib.List.equal Parameter.equal c1.params c2.params && same c1.body c2.body and same_set_of_closures (c1 : Flambda.set_of_closures) (c2 : Flambda.set_of_closures) = Variable.Map.equal sameclosure c1.function_decls.funs c2.function_decls.funs && Variable.Map.equal Flambda.equal_specialised_to c1.free_vars c2.free_vars && Variable.Map.equal Flambda.equal_specialised_to c1.specialised_args c2.specialised_args and same_project_closure (s1 : Flambda.project_closure) (s2 : Flambda.project_closure) = Variable.equal s1.set_of_closures s2.set_of_closures && Closure_id.equal s1.closure_id s2.closure_id and same_move_within_set_of_closures (m1 : Flambda.move_within_set_of_closures) (m2 : Flambda.move_within_set_of_closures) = Variable.equal m1.closure m2.closure && Closure_id.equal m1.start_from m2.start_from && Closure_id.equal m1.move_to m2.move_to and samebinding (v1, n1) (v2, n2) = Variable.equal v1 v2 && same_named n1 n2 and sameswitch (fs1 : Flambda.switch) (fs2 : Flambda.switch) = let samecase (n1, a1) (n2, a2) = n1 = n2 && same a1 a2 in Numbers.Int.Set.equal fs1.numconsts fs2.numconsts && Numbers.Int.Set.equal fs1.numblocks fs2.numblocks && Misc.Stdlib.List.equal samecase fs1.consts fs2.consts && Misc.Stdlib.List.equal samecase fs1.blocks fs2.blocks && Option.equal same fs1.failaction fs2.failaction let can_be_merged = same let toplevel_substitution sb tree = let sb' = sb in let sb v = try Variable.Map.find v sb with Not_found -> v in let aux (flam : Flambda.t) : Flambda.t = match flam with | Var var -> let var = sb var in Var var | Let_mutable mutable_let -> let initial_value = sb mutable_let.initial_value in Let_mutable { mutable_let with initial_value } | Assign { being_assigned; new_value; } -> let new_value = sb new_value in Assign { being_assigned; new_value; } | Apply { func; args; kind; dbg; inline; specialise; } -> let func = sb func in let args = List.map sb args in Apply { func; args; kind; dbg; inline; specialise; } | If_then_else (cond, e1, e2) -> let cond = sb cond in If_then_else (cond, e1, e2) | Switch (cond, sw) -> let cond = sb cond in Switch (cond, sw) | String_switch (cond, branches, def) -> let cond = sb cond in String_switch (cond, branches, def) | Send { kind; meth; obj; args; dbg } -> let meth = sb meth in let obj = sb obj in let args = List.map sb args in Send { kind; meth; obj; args; dbg } | For { bound_var; from_value; to_value; direction; body } -> let from_value = sb from_value in let to_value = sb to_value in For { bound_var; from_value; to_value; direction; body } | Static_raise (static_exn, args) -> let args = List.map sb args in Static_raise (static_exn, args) | Static_catch _ | Try_with _ | While _ | Let _ | Let_rec _ | Proved_unreachable -> flam in let aux_named (named : Flambda.named) : Flambda.named = match named with | Symbol _ | Const _ | Expr _ -> named | Allocated_const _ | Read_mutable _ -> named | Read_symbol_field _ -> named | Set_of_closures set_of_closures -> let set_of_closures = Flambda.create_set_of_closures ~function_decls:set_of_closures.function_decls ~free_vars: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.free_vars) ~specialised_args: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.specialised_args) ~direct_call_surrogates:set_of_closures.direct_call_surrogates in Set_of_closures set_of_closures | Project_closure project_closure -> Project_closure { project_closure with set_of_closures = sb project_closure.set_of_closures; } | Move_within_set_of_closures move_within_set_of_closures -> Move_within_set_of_closures { move_within_set_of_closures with closure = sb move_within_set_of_closures.closure; } | Project_var project_var -> Project_var { project_var with closure = sb project_var.closure; } | Prim (prim, args, dbg) -> Prim (prim, List.map sb args, dbg) in if Variable.Map.is_empty sb' then tree else Flambda_iterators.map_toplevel aux aux_named tree let toplevel_substitution_named sb named = let name = Internal_variable_names.toplevel_substitution_named in let expr = name_expr named ~name in match toplevel_substitution sb expr with | Let let_expr -> let_expr.defining_expr | _ -> assert false let make_closure_declaration ~is_classic_mode ~id ~body ~params : Flambda.t = let free_variables = Flambda.free_variables body in let param_set = Parameter.Set.vars params in if not (Variable.Set.subset param_set free_variables) then begin Misc.fatal_error "Flambda_utils.make_closure_declaration" end; let sb = Variable.Set.fold (fun id sb -> Variable.Map.add id (Variable.rename id) sb) free_variables Variable.Map.empty in let body = toplevel_substitution sb body in let subst id = Variable.Map.find id sb in let subst_param param = Parameter.map_var subst param in let function_declaration = Flambda.create_function_declaration ~params:(List.map subst_param params) ~body ~stub:true ~dbg:Debuginfo.none ~inline:Default_inline ~specialise:Default_specialise ~is_a_functor:false ~closure_origin:(Closure_origin.create (Closure_id.wrap id)) ~poll:Default_poll in begin assert (Variable.Set.equal (Variable.Set.map subst free_variables) function_declaration.free_variables); end; let free_vars = Variable.Map.fold (fun id id' fv' -> let spec_to : Flambda.specialised_to = { var = id; projection = None; } in Variable.Map.add id' spec_to fv') (Variable.Map.filter (fun id _ -> not (Variable.Set.mem id param_set)) sb) Variable.Map.empty in let compilation_unit = Compilation_unit.get_current_exn () in let set_of_closures_var = Variable.create Internal_variable_names.set_of_closures ~current_compilation_unit:compilation_unit in let set_of_closures = let function_decls = Flambda.create_function_declarations ~is_classic_mode ~funs:(Variable.Map.singleton id function_declaration) in Flambda.create_set_of_closures ~function_decls ~free_vars ~specialised_args:Variable.Map.empty ~direct_call_surrogates:Variable.Map.empty in let project_closure : Flambda.named = Project_closure { set_of_closures = set_of_closures_var; closure_id = Closure_id.wrap id; } in let project_closure_var = Variable.create Internal_variable_names.project_closure ~current_compilation_unit:compilation_unit in Flambda.create_let set_of_closures_var (Set_of_closures set_of_closures) (Flambda.create_let project_closure_var project_closure (Var (project_closure_var))) let bind ~bindings ~body = List.fold_left (fun expr (var, var_def) -> Flambda.create_let var var_def expr) body bindings let all_lifted_constants (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Let_symbol (symbol, decl, program) -> (symbol, decl) :: (loop program) | Let_rec_symbol (decls, program) -> List.fold_left (fun l (symbol, decl) -> (symbol, decl) :: l) (loop program) decls | Initialize_symbol (_, _, _, program) | Effect (_, program) -> loop program | End _ -> [] in loop program.program_body let all_lifted_constants_as_map program = Symbol.Map.of_list (all_lifted_constants program) let initialize_symbols (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Initialize_symbol (symbol, tag, fields, program) -> (symbol, tag, fields) :: (loop program) | Effect (_, program) | Let_symbol (_, _, program) | Let_rec_symbol (_, program) -> loop program | End _ -> [] in loop program.program_body let imported_symbols (program : Flambda.program) = program.imported_symbols let needed_import_symbols (program : Flambda.program) = let dependencies = Flambda.free_symbols_program program in let defined_symbol = Symbol.Set.union (Symbol.Set.of_list (List.map fst (all_lifted_constants program))) (Symbol.Set.of_list (List.map (fun (s, _, _) -> s) (initialize_symbols program))) in Symbol.Set.diff dependencies defined_symbol let introduce_needed_import_symbols program : Flambda.program = { program with imported_symbols = needed_import_symbols program; } let root_symbol (program : Flambda.program) = let rec loop (program : Flambda.program_body) = match program with | Effect (_, program) | Let_symbol (_, _, program) | Let_rec_symbol (_, program) | Initialize_symbol (_, _, _, program) -> loop program | End root -> root in loop program.program_body let might_raise_static_exn flam stexn = try Flambda_iterators.iter_on_named (function | Flambda.Static_raise (ex, _) when Static_exception.equal ex stexn -> raise Exit | _ -> ()) (fun _ -> ()) flam; false with Exit -> true let make_closure_map program = let map = ref Closure_id.Map.empty in let add_set_of_closures ~constant:_ : Flambda.set_of_closures -> unit = fun { function_decls } -> Variable.Map.iter (fun var _ -> let closure_id = Closure_id.wrap var in let set_of_closures_id = function_decls.set_of_closures_id in map := Closure_id.Map.add closure_id set_of_closures_id !map) function_decls.funs in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:add_set_of_closures; !map let all_lifted_constant_closures program = List.fold_left (fun unchanged flambda -> match flambda with | (_, Flambda.Set_of_closures { function_decls = { funs } }) -> Variable.Map.fold (fun key (_ : Flambda.function_declaration) acc -> Closure_id.Set.add (Closure_id.wrap key) acc) funs unchanged | _ -> unchanged) Closure_id.Set.empty (all_lifted_constants program) let all_lifted_constant_sets_of_closures program = let set = ref Set_of_closures_id.Set.empty in List.iter (function | (_, Flambda.Set_of_closures { function_decls = { set_of_closures_id } }) -> set := Set_of_closures_id.Set.add set_of_closures_id !set | _ -> ()) (all_lifted_constants program); !set let all_sets_of_closures program = let list = ref [] in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:(fun ~constant:_ set_of_closures -> list := set_of_closures :: !list); !list let all_sets_of_closures_map program = let r = ref Set_of_closures_id.Map.empty in Flambda_iterators.iter_on_set_of_closures_of_program program ~f:(fun ~constant:_ set_of_closures -> r := Set_of_closures_id.Map.add set_of_closures.function_decls.set_of_closures_id set_of_closures !r); !r let substitute_read_symbol_field_for_variables (substitution : (Symbol.t * int list) Variable.Map.t) (expr : Flambda.t) = let bind var fresh_var (expr:Flambda.t) : Flambda.t = let symbol, path = Variable.Map.find var substitution in let rec make_named (path:int list) : Flambda.named = match path with | [] -> Symbol symbol | [i] -> Read_symbol_field (symbol, i) | h :: t -> let block_name = Internal_variable_names.symbol_field_block in let block = Variable.create block_name in let field_name = Internal_variable_names.get_symbol_field in let field = Variable.create field_name in Expr ( Flambda.create_let block (make_named t) (Flambda.create_let field (Prim (Pfield h, [block], Debuginfo.none)) (Var field))) in Flambda.create_let fresh_var (make_named path) expr in let substitute_named bindings (named:Flambda.named) : Flambda.named = let sb to_substitute = try Variable.Map.find to_substitute bindings with | Not_found -> to_substitute in match named with | Symbol _ | Const _ | Expr _ -> named | Allocated_const _ | Read_mutable _ -> named | Read_symbol_field _ -> named | Set_of_closures set_of_closures -> let set_of_closures = Flambda.create_set_of_closures ~function_decls:set_of_closures.function_decls ~free_vars: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.free_vars) ~specialised_args: (Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> { spec_to with var = sb spec_to.var; }) set_of_closures.specialised_args) ~direct_call_surrogates:set_of_closures.direct_call_surrogates in Set_of_closures set_of_closures | Project_closure project_closure -> Project_closure { project_closure with set_of_closures = sb project_closure.set_of_closures; } | Move_within_set_of_closures move_within_set_of_closures -> Move_within_set_of_closures { move_within_set_of_closures with closure = sb move_within_set_of_closures.closure; } | Project_var project_var -> Project_var { project_var with closure = sb project_var.closure; } | Prim (prim, args, dbg) -> Prim (prim, List.map sb args, dbg) in let make_var_subst var = if Variable.Map.mem var substitution then let fresh = Variable.rename var in fresh, (fun expr -> bind var fresh expr) else var, (fun x -> x) in let f (expr:Flambda.t) : Flambda.t = match expr with | Var v when Variable.Map.mem v substitution -> let fresh = Variable.rename v in bind v fresh (Var fresh) | Var _ -> expr | Let ({ var = v; defining_expr = named; _ } as let_expr) -> let to_substitute = Variable.Set.filter (fun v -> Variable.Map.mem v substitution) (Flambda.free_variables_named named) in if Variable.Set.is_empty to_substitute then expr else let bindings = Variable.Map.of_set (fun var -> Variable.rename var) to_substitute in let named = substitute_named bindings named in let expr = let module W = Flambda.With_free_variables in W.create_let_reusing_body v named (W.of_body_of_let let_expr) in Variable.Map.fold (fun to_substitute fresh expr -> bind to_substitute fresh expr) bindings expr | Let_mutable let_mutable when Variable.Map.mem let_mutable.initial_value substitution -> let fresh = Variable.rename let_mutable.initial_value in bind let_mutable.initial_value fresh (Let_mutable { let_mutable with initial_value = fresh }) | Let_mutable _ -> expr | Let_rec (defs, body) -> let free_variables_of_defs = List.fold_left (fun set (_, named) -> Variable.Set.union set (Flambda.free_variables_named named)) Variable.Set.empty defs in let to_substitute = Variable.Set.filter (fun v -> Variable.Map.mem v substitution) free_variables_of_defs in if Variable.Set.is_empty to_substitute then expr else begin let bindings = Variable.Map.of_set (fun var -> Variable.rename var) to_substitute in let defs = List.map (fun (var, named) -> var, substitute_named bindings named) defs in let expr = Flambda.Let_rec (defs, body) in Variable.Map.fold (fun to_substitute fresh expr -> bind to_substitute fresh expr) bindings expr end | If_then_else (cond, ifso, ifnot) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (If_then_else (fresh, ifso, ifnot)) | If_then_else _ -> expr | Switch (cond, sw) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (Switch (fresh, sw)) | Switch _ -> expr | String_switch (cond, sw, def) when Variable.Map.mem cond substitution -> let fresh = Variable.rename cond in bind cond fresh (String_switch (fresh, sw, def)) | String_switch _ -> expr | Assign { being_assigned; new_value } when Variable.Map.mem new_value substitution -> let fresh = Variable.rename new_value in bind new_value fresh (Assign { being_assigned; new_value = fresh }) | Assign _ -> expr | Static_raise (exn, args) -> let args, bind_args = List.split (List.map make_var_subst args) in List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Static_raise (exn, args) | For { bound_var; from_value; to_value; direction; body } -> let from_value, bind_from_value = make_var_subst from_value in let to_value, bind_to_value = make_var_subst to_value in bind_from_value @@ bind_to_value @@ Flambda.For { bound_var; from_value; to_value; direction; body } | Apply { func; args; kind; dbg; inline; specialise } -> let func, bind_func = make_var_subst func in let args, bind_args = List.split (List.map make_var_subst args) in bind_func @@ List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Apply { func; args; kind; dbg; inline; specialise } | Send { kind; meth; obj; args; dbg } -> let meth, bind_meth = make_var_subst meth in let obj, bind_obj = make_var_subst obj in let args, bind_args = List.split (List.map make_var_subst args) in bind_meth @@ bind_obj @@ List.fold_right (fun f expr -> f expr) bind_args @@ Flambda.Send { kind; meth; obj; args; dbg } | Proved_unreachable | While _ | Try_with _ | Static_catch _ -> expr in Flambda_iterators.map_toplevel f (fun v -> v) expr module Switch_storer = Switch.Store (struct type t = Flambda.t type key = | Var of Variable.t | Let of Variable.t * key_named * key | Static_raise of Static_exception.t * Variable.t list and key_named = | Symbol of Symbol.t | Const of Flambda.const | Prim of Clambda_primitives.primitive * Variable.t list | Expr of key exception Not_comparable let rec make_expr_key (expr : Flambda.t) : key = match expr with | Var v -> Var v | Let { var; defining_expr; body; } -> Let (var, make_named_key defining_expr, make_expr_key body) | Static_raise (e, args) -> Static_raise (e, args) | _ -> raise Not_comparable and make_named_key (named:Flambda.named) : key_named = match named with | Symbol s -> Symbol s | Const c -> Const c | Expr e -> Expr (make_expr_key e) | Prim (prim, args, _dbg) -> Prim (prim, args) | _ -> raise Not_comparable let make_key expr = match make_expr_key expr with | exception Not_comparable -> None | key -> Some key let compare_key e1 e2 = let compare_var env v1 v2 = match Variable.Map.find v2 env with | exception Not_found -> Variable.compare v1 v2 | bound -> Variable.compare v1 bound in let rec compare_expr env (e1 : key) (e2 : key) : int = match e1, e2 with | Var v1, Var v2 -> compare_var env v1 v2 | Var _, (Let _| Static_raise _) -> -1 | (Let _| Static_raise _), Var _ -> 1 | Let (v1, n1, b1), Let (v2, n2, b2) -> let comp_named = compare_named env n1 n2 in if comp_named <> 0 then comp_named else let env = Variable.Map.add v2 v1 env in compare_expr env b1 b2 | Let _, Static_raise _ -> -1 | Static_raise _, Let _ -> 1 | Static_raise (sexn1, args1), Static_raise (sexn2, args2) -> let comp_sexn = Static_exception.compare sexn1 sexn2 in if comp_sexn <> 0 then comp_sexn else Misc.Stdlib.List.compare (compare_var env) args1 args2 and compare_named env (n1:key_named) (n2:key_named) : int = match n1, n2 with | Symbol s1, Symbol s2 -> Symbol.compare s1 s2 | Symbol _, (Const _ | Expr _ | Prim _) -> -1 | (Const _ | Expr _ | Prim _), Symbol _ -> 1 | Const c1, Const c2 -> Flambda.compare_const c1 c2 | Const _, (Expr _ | Prim _) -> -1 | (Expr _ | Prim _), Const _ -> 1 | Expr e1, Expr e2 -> compare_expr env e1 e2 | Expr _, Prim _ -> -1 | Prim _, Expr _ -> 1 | Prim (prim1, args1), Prim (prim2, args2) -> let comp_prim = Stdlib.compare prim1 prim2 in if comp_prim <> 0 then comp_prim else Misc.Stdlib.List.compare (compare_var env) args1 args2 in compare_expr Variable.Map.empty e1 e2 end) let fun_vars_referenced_in_decls (function_decls : Flambda.function_declarations) ~closure_symbol = let fun_vars = Variable.Map.keys function_decls.funs in let symbols_to_fun_vars = Variable.Set.fold (fun fun_var symbols_to_fun_vars -> let closure_id = Closure_id.wrap fun_var in let symbol = closure_symbol closure_id in Symbol.Map.add symbol fun_var symbols_to_fun_vars) fun_vars Symbol.Map.empty in Variable.Map.map (fun (func_decl : Flambda.function_declaration) -> let from_symbols = Symbol.Set.fold (fun symbol fun_vars' -> match Symbol.Map.find symbol symbols_to_fun_vars with | exception Not_found -> fun_vars' | fun_var -> assert (Variable.Set.mem fun_var fun_vars); Variable.Set.add fun_var fun_vars') func_decl.free_symbols Variable.Set.empty in let from_variables = Variable.Set.inter func_decl.free_variables fun_vars in Variable.Set.union from_symbols from_variables) function_decls.funs let closures_required_by_entry_point ~(entry_point : Closure_id.t) ~closure_symbol (function_decls : Flambda.function_declarations) = let dependencies = fun_vars_referenced_in_decls function_decls ~closure_symbol in let set = ref Variable.Set.empty in let queue = Queue.create () in let add v = if not (Variable.Set.mem v !set) then begin set := Variable.Set.add v !set; Queue.push v queue end in add (Closure_id.unwrap entry_point); while not (Queue.is_empty queue) do let fun_var = Queue.pop queue in match Variable.Map.find fun_var dependencies with | exception Not_found -> () | fun_dependencies -> Variable.Set.iter (fun dep -> if Variable.Map.mem dep function_decls.funs then add dep) fun_dependencies done; !set let all_functions_parameters (function_decls : Flambda.function_declarations) = Variable.Map.fold (fun _ ({ params } : Flambda.function_declaration) set -> Variable.Set.union set (Parameter.Set.vars params)) function_decls.funs Variable.Set.empty let all_free_symbols (function_decls : Flambda.function_declarations) = Variable.Map.fold (fun _ (function_decl : Flambda.function_declaration) syms -> Symbol.Set.union syms function_decl.free_symbols) function_decls.funs Symbol.Set.empty let contains_stub (fun_decls : Flambda.function_declarations) = let number_of_stub_functions = Variable.Map.cardinal (Variable.Map.filter (fun _ { Flambda.stub } -> stub) fun_decls.funs) in number_of_stub_functions > 0 let clean_projections ~which_variables = Variable.Map.map (fun (spec_to : Flambda.specialised_to) -> match spec_to.projection with | None -> spec_to | Some projection -> let from = Projection.projecting_from projection in if Variable.Map.mem from which_variables then spec_to else ({ spec_to with projection = None; } : Flambda.specialised_to)) which_variables let projection_to_named (projection : Projection.t) : Flambda.named = match projection with | Project_var project_var -> Project_var project_var | Project_closure project_closure -> Project_closure project_closure | Move_within_set_of_closures move -> Move_within_set_of_closures move | Field (field_index, var) -> Prim (Pfield field_index, [var], Debuginfo.none) type specialised_to_same_as = | Not_specialised | Specialised_and_aliased_to of Variable.Set.t let parameters_specialised_to_the_same_variable ~(function_decls : Flambda.function_declarations) ~(specialised_args : Flambda.specialised_to Variable.Map.t) = let specialised_arg_aliasing = Variable.Map.transpose_keys_and_data_set (Variable.Map.map (fun ({ var; _ } : Flambda.specialised_to) -> var) specialised_args) in Variable.Map.map (fun ({ params; _ } : Flambda.function_declaration) -> List.map (fun param -> match Variable.Map.find (Parameter.var param) specialised_args with | exception Not_found -> Not_specialised | { var; _ } -> Specialised_and_aliased_to (Variable.Map.find var specialised_arg_aliasing)) params) function_decls.funs
bd71493701a74000b3d735721ff35edbc12965f10108e890995ad08b470b7bb8
rtoy/ansi-cl-tests
values.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Oct 19 08:18:50 2002 ;;;; Contains: Tests of VALUES (in-package :cl-test) (deftest values.0 (values)) (deftest values.1 (values 1) 1) (deftest values.2 (values 1 2) 1 2) (deftest values.3 (values 1 2 3) 1 2 3) (deftest values.4 (values 1 2 3 4) 1 2 3 4) (deftest values.10 (values 1 2 3 4 5 6 7 8 9 10) 1 2 3 4 5 6 7 8 9 10) (deftest values.15 (values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) (deftest values.19 (values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) (deftest values.20 (let ((a t) (b t) (c t) (d t) (e t) (f t)) (setf (values a (values b c) (values d) (values e f)) (values 0 1 2 3 4 5 6)) (list a b c d e f)) (0 1 nil 2 3 nil)) (deftest values.21 (let (a b c d e f) (setf (values a (values b c) (values d) (values e f)) (values 0 1 2 3 4 5 6))) 0 1 2 3) (deftest values.A (values (values 1 2) (values 3 4 5) (values) (values 10)) 1 3 nil 10) (deftest values.B (funcall #'values 1 2 3 4) 1 2 3 4) (deftest values.C (let ((x (loop for i from 1 to (min 1000 (1- call-arguments-limit) (1- multiple-values-limit)) collect i))) (equalt x (multiple-value-list (apply #'values x)))) t) (deftest values.order.1 (let ((i 0) a b c) (values (multiple-value-list (values (setf a (incf i)) (setf b (incf i)) (setf c (incf i)))) i a b c)) (1 2 3) 3 1 2 3)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/values.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of VALUES
Author : Created : Sat Oct 19 08:18:50 2002 (in-package :cl-test) (deftest values.0 (values)) (deftest values.1 (values 1) 1) (deftest values.2 (values 1 2) 1 2) (deftest values.3 (values 1 2 3) 1 2 3) (deftest values.4 (values 1 2 3 4) 1 2 3 4) (deftest values.10 (values 1 2 3 4 5 6 7 8 9 10) 1 2 3 4 5 6 7 8 9 10) (deftest values.15 (values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) (deftest values.19 (values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19) (deftest values.20 (let ((a t) (b t) (c t) (d t) (e t) (f t)) (setf (values a (values b c) (values d) (values e f)) (values 0 1 2 3 4 5 6)) (list a b c d e f)) (0 1 nil 2 3 nil)) (deftest values.21 (let (a b c d e f) (setf (values a (values b c) (values d) (values e f)) (values 0 1 2 3 4 5 6))) 0 1 2 3) (deftest values.A (values (values 1 2) (values 3 4 5) (values) (values 10)) 1 3 nil 10) (deftest values.B (funcall #'values 1 2 3 4) 1 2 3 4) (deftest values.C (let ((x (loop for i from 1 to (min 1000 (1- call-arguments-limit) (1- multiple-values-limit)) collect i))) (equalt x (multiple-value-list (apply #'values x)))) t) (deftest values.order.1 (let ((i 0) a b c) (values (multiple-value-list (values (setf a (incf i)) (setf b (incf i)) (setf c (incf i)))) i a b c)) (1 2 3) 3 1 2 3)
47f0f60c3930c43d0ef170b90db7fd51df6fb5a53a8603f5f44e10d51a343317
casperschipper/ocaml-cisp
scheduler.ml
schedular allows to schedule parallel streams of any type . The unit is a timedsection , which has a timedsection that defines its content and a starting sample . Schedular 's schedule to an internal sample clock . To play back any type , one has to define the properties ( monoid ): - empty event , for example , MidiSilence or 0.0 - merge two into one stream These have been provided for float streams and midi event streams . The unit is a timedsection, which has a timedsection that defines its content and a starting sample. Schedular's schedule to an internal sample clock. To play back any type, one has to define the properties (monoid): - empty event, for example, MidiSilence or 0.0 - merge two into one stream These have been provided for float streams and midi event streams. *) (* section has a start point and a sequence of sounds *) type 'a timedSection = Section of { startSample : int; seq : 'a Seq.t } (* finite, has an end *) let mkSectionOfInf start duration (sq : 'a Infseq.t) = let truncated = Infseq.take duration sq in Section { startSample = start; seq = truncated } let mkSection start duration seq = Section { startSample = start; seq = Cisp.take duration seq } let compareSection (Section sectA) (Section sectB) = compare sectA.startSample sectB.startSample type 'a playingSection = PlayingSection of { seq : 'a Seq.t } type 'a score = Score of 'a timedSection Sorted.t let toPlay (Section section) = PlayingSection { seq = section.seq } type 'a t = | SectionScheduler of { score : 'a timedSection Sorted.t; playingScore : 'a timedSection Sorted.t; now : int; currentSecs : 'a playingSection list; currentOut : 'a; } let schedWithOffset (SectionScheduler score) offsetInSmps = SectionScheduler { score with now = offsetInSmps } let schedulerOfScore empty (Score sortedTimedSecs) = SectionScheduler { playingScore = sortedTimedSecs; score = sortedTimedSecs; now = 0; currentSecs = []; currentOut = empty; } let mkScore sectionLst = Score (Sorted.mkSorted compareSection sectionLst) this is for seqs of floats let mappend_float_sq (sum, tails) (PlayingSection playingSeq) = (* this takes the heads of secs sums them, and updates the remaining part in the state *) match playingSeq.seq () with | Nil -> (sum, tails) | Cons (x, tail) -> (sum +. x, PlayingSection { seq = tail } :: tails) let mappend_midi (bundle, tails) (PlayingSection midiEvtSq) = match midiEvtSq.seq () with | Seq.Nil -> (bundle, tails) | Seq.Cons (midiEvt, tail) -> (Midi.addToBundle bundle midiEvt, PlayingSection { seq = tail } :: tails) let merge mergefunc (merged, tails) (PlayingSection sq) = match sq.seq () with | Seq.Nil -> (merged, tails) | Seq.Cons (head, tail) -> (mergefunc merged head, PlayingSection { seq = tail } :: tails) let updateScheduler (SectionScheduler scheduler) merge empty = let newCurrentSecs, future = scheduler.playingScore |> Sorted.mozesSorted (fun (Section e) -> e.startSample <= scheduler.now) |> Cisp.mapFst (fun (Sorted.Sorted playableEvts) -> List.map toPlay playableEvts) in let currentSects = newCurrentSecs @ scheduler.currentSecs in let out, newPlayingSecs = List.fold_left merge (empty, []) currentSects in match (future, newPlayingSecs) with (* to deal with reset, if there is no future, then we reset the score *) | Sorted.Sorted [], [] -> SectionScheduler { scheduler with playingScore = scheduler.score; now = 0; currentSecs = []; currentOut = out; } | Sorted.Sorted futureEvts, _ -> SectionScheduler { scheduler with playingScore = Sorted futureEvts; now = scheduler.now + 1; currentSecs = newPlayingSecs; currentOut = out; } let printTimedSectionLst timedSectionList = let open Format in let printSection i (Section s) = printf "-section nr %i\nstartSample %i\n" i s.startSample in List.iteri printSection timedSectionList let printScheduler (SectionScheduler sch) = let open Format in printf "\n** now: %i **\n score=\n" sch.now; printTimedSectionLst (Sorted.sortedAsList sch.score); printf "currently playing %i" (List.length sch.currentSecs) let evaluateScheduler (SectionScheduler scheduler) = scheduler.currentOut let playScore score = Cisp.simpleRecursive ( schedulerOfScore score ) updateScheduler evaluateScheduler Cisp.simpleRecursive (schedulerOfScore score) updateScheduler evaluateScheduler*)
null
https://raw.githubusercontent.com/casperschipper/ocaml-cisp/571ffb8e508c5427d01e407ba5e91ff2a4604f40/src/scheduler/scheduler.ml
ocaml
section has a start point and a sequence of sounds finite, has an end this takes the heads of secs sums them, and updates the remaining part in the state to deal with reset, if there is no future, then we reset the score
schedular allows to schedule parallel streams of any type . The unit is a timedsection , which has a timedsection that defines its content and a starting sample . Schedular 's schedule to an internal sample clock . To play back any type , one has to define the properties ( monoid ): - empty event , for example , MidiSilence or 0.0 - merge two into one stream These have been provided for float streams and midi event streams . The unit is a timedsection, which has a timedsection that defines its content and a starting sample. Schedular's schedule to an internal sample clock. To play back any type, one has to define the properties (monoid): - empty event, for example, MidiSilence or 0.0 - merge two into one stream These have been provided for float streams and midi event streams. *) type 'a timedSection = Section of { startSample : int; seq : 'a Seq.t } let mkSectionOfInf start duration (sq : 'a Infseq.t) = let truncated = Infseq.take duration sq in Section { startSample = start; seq = truncated } let mkSection start duration seq = Section { startSample = start; seq = Cisp.take duration seq } let compareSection (Section sectA) (Section sectB) = compare sectA.startSample sectB.startSample type 'a playingSection = PlayingSection of { seq : 'a Seq.t } type 'a score = Score of 'a timedSection Sorted.t let toPlay (Section section) = PlayingSection { seq = section.seq } type 'a t = | SectionScheduler of { score : 'a timedSection Sorted.t; playingScore : 'a timedSection Sorted.t; now : int; currentSecs : 'a playingSection list; currentOut : 'a; } let schedWithOffset (SectionScheduler score) offsetInSmps = SectionScheduler { score with now = offsetInSmps } let schedulerOfScore empty (Score sortedTimedSecs) = SectionScheduler { playingScore = sortedTimedSecs; score = sortedTimedSecs; now = 0; currentSecs = []; currentOut = empty; } let mkScore sectionLst = Score (Sorted.mkSorted compareSection sectionLst) this is for seqs of floats let mappend_float_sq (sum, tails) (PlayingSection playingSeq) = match playingSeq.seq () with | Nil -> (sum, tails) | Cons (x, tail) -> (sum +. x, PlayingSection { seq = tail } :: tails) let mappend_midi (bundle, tails) (PlayingSection midiEvtSq) = match midiEvtSq.seq () with | Seq.Nil -> (bundle, tails) | Seq.Cons (midiEvt, tail) -> (Midi.addToBundle bundle midiEvt, PlayingSection { seq = tail } :: tails) let merge mergefunc (merged, tails) (PlayingSection sq) = match sq.seq () with | Seq.Nil -> (merged, tails) | Seq.Cons (head, tail) -> (mergefunc merged head, PlayingSection { seq = tail } :: tails) let updateScheduler (SectionScheduler scheduler) merge empty = let newCurrentSecs, future = scheduler.playingScore |> Sorted.mozesSorted (fun (Section e) -> e.startSample <= scheduler.now) |> Cisp.mapFst (fun (Sorted.Sorted playableEvts) -> List.map toPlay playableEvts) in let currentSects = newCurrentSecs @ scheduler.currentSecs in let out, newPlayingSecs = List.fold_left merge (empty, []) currentSects in match (future, newPlayingSecs) with | Sorted.Sorted [], [] -> SectionScheduler { scheduler with playingScore = scheduler.score; now = 0; currentSecs = []; currentOut = out; } | Sorted.Sorted futureEvts, _ -> SectionScheduler { scheduler with playingScore = Sorted futureEvts; now = scheduler.now + 1; currentSecs = newPlayingSecs; currentOut = out; } let printTimedSectionLst timedSectionList = let open Format in let printSection i (Section s) = printf "-section nr %i\nstartSample %i\n" i s.startSample in List.iteri printSection timedSectionList let printScheduler (SectionScheduler sch) = let open Format in printf "\n** now: %i **\n score=\n" sch.now; printTimedSectionLst (Sorted.sortedAsList sch.score); printf "currently playing %i" (List.length sch.currentSecs) let evaluateScheduler (SectionScheduler scheduler) = scheduler.currentOut let playScore score = Cisp.simpleRecursive ( schedulerOfScore score ) updateScheduler evaluateScheduler Cisp.simpleRecursive (schedulerOfScore score) updateScheduler evaluateScheduler*)
41956a1b85a2e2e518a94ce8ed14a76905bff554f9b48f1af7a745b9a0677dcc
typelead/eta
tcfail131.hs
-- Error message in monomorphic case module ShouldFail where g :: Num b => b -> b g x = f x x
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/fail/tcfail131.hs
haskell
Error message in monomorphic case
module ShouldFail where g :: Num b => b -> b g x = f x x
f60459e2f734d7851654cc5c81d79b7397b85bac0532d90e568e0deab668b9ef
SjVer/Som-Lang
tast.ml
type tast = toplevel node list and 'a node = 'a Parse.Ast.node and 'a tnode = { span: Span.t; item: 'a; typ: Types.t; } = = = = = = = = = = = = = = = = = = = = = = Toplevel = = = = = = = = = = = = = = = = = = = = = = and toplevel = | TL_Declaration of string node * Types.t node | TL_Value_Definition of value_binding | TL_Section of string node * tast and value_binding = { patt: pattern tnode; expr: expr tnode; } (* ====================== Pattern ======================= *) and pattern = | PA_Variable of string | PA_Wildcard (* ===================== Expression ===================== *) and expr = | EX_Grouping of expr tnode | EX_Binding of value_binding * expr tnode | EX_Lambda of value_binding | EX_Sequence of expr tnode * expr tnode | EX_Application of expr tnode * expr tnode list | EX_Tuple of expr tnode list | EX_Construct of Symboltable.Ident.t tnode * expr tnode option | EX_Literal of literal | EX_Identifier of Symboltable.Ident.t tnode | EX_External of string | EX_Error and literal = | LI_Int of int | LI_Float of float | LI_Char of char | LI_String of string | LI_Nil
null
https://raw.githubusercontent.com/SjVer/Som-Lang/01b973a39769bba1e4ba71ebcb4e4a970328dfe3/somc/lib/typing/tast.ml
ocaml
====================== Pattern ======================= ===================== Expression =====================
type tast = toplevel node list and 'a node = 'a Parse.Ast.node and 'a tnode = { span: Span.t; item: 'a; typ: Types.t; } = = = = = = = = = = = = = = = = = = = = = = Toplevel = = = = = = = = = = = = = = = = = = = = = = and toplevel = | TL_Declaration of string node * Types.t node | TL_Value_Definition of value_binding | TL_Section of string node * tast and value_binding = { patt: pattern tnode; expr: expr tnode; } and pattern = | PA_Variable of string | PA_Wildcard and expr = | EX_Grouping of expr tnode | EX_Binding of value_binding * expr tnode | EX_Lambda of value_binding | EX_Sequence of expr tnode * expr tnode | EX_Application of expr tnode * expr tnode list | EX_Tuple of expr tnode list | EX_Construct of Symboltable.Ident.t tnode * expr tnode option | EX_Literal of literal | EX_Identifier of Symboltable.Ident.t tnode | EX_External of string | EX_Error and literal = | LI_Int of int | LI_Float of float | LI_Char of char | LI_String of string | LI_Nil
fa1084a4233098161730cf0f998eda0f81878161a90ae5253f1eac23a51b4c0f
rowangithub/DOrder
oper.ml
(**************************************************************************) (* *) : a generic graph library for OCaml Copyright ( C ) 2004 - 2007 , and (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************) $ I d : oper.ml , v 1.13 2005 - 06 - 30 10:48:55 filliatr Exp $ (* Basic operations over graphs *) module type S = sig type g val transitive_closure : ?reflexive:bool -> g -> g val add_transitive_closure : ?reflexive:bool -> g -> g val mirror : g -> g val complement : g -> g val intersect : g -> g -> g val union : g -> g -> g end module Make(B : Builder.S) = struct open B Roy - Warshall 's algorithm type g = G.t let add_transitive_closure ?(reflexive=false) g0 = let phi v g = let g = if reflexive then B.add_edge g v v else g in G.fold_succ (fun sv g -> G.fold_pred (fun pv g -> B.add_edge g pv sv) g v g) g v g in G.fold_vertex phi g0 g0 let transitive_closure ?(reflexive=false) g0 = add_transitive_closure ~reflexive (B.copy g0) module H = Hashtbl.Make(G.V) let mirror g = if G.is_directed then begin let g' = B.empty () in G.fold_edges_e (fun e g' -> let v1 = (G.E.src e) in let v2 = (G.E.dst e) in B.add_edge_e g' (G.E.create v2 (G.E.label e) v1)) g g' end else B.copy g let complement g = G.fold_vertex (fun v g' -> G.fold_vertex (fun w g' -> if G.mem_edge g v w then g' else B.add_edge g' v w) g g') g (B.empty ()) let intersect g1 g2 = G.fold_vertex (fun v g -> try let succ = G.succ_e g2 v in G.fold_succ_e (fun e g -> if List.mem e succ then B.add_edge_e g e else B.add_vertex g (G.E.dst e)) g1 v (B.add_vertex g v) with Invalid_argument _ -> (* $v \notin g2$ *) g) g1 (B.empty ()) let union g1 g2 = let add g1 g2 = (* add the graph [g1] in [g2] *) G.fold_vertex (fun v g -> G.fold_succ_e (fun e g -> B.add_edge_e g e) g1 v (B.add_vertex g v)) g1 g2 in add g1 (B.copy g2) end module P(G : Sig.P) = Make(Builder.P(G)) module I(G : Sig.I) = Make(Builder.I(G)) module Choose(G : sig type t type vertex type edge val iter_vertex : (vertex -> unit) -> t -> unit val iter_edges_e : (edge -> unit) -> t -> unit end) = struct exception Found_Vertex of G.vertex let choose_vertex g = try G.iter_vertex (fun v -> raise (Found_Vertex v)) g; invalid_arg "choose_vertex" with Found_Vertex v -> v exception Found_Edge of G.edge let choose_edge g = try G.iter_edges_e (fun v -> raise (Found_Edge v)) g; invalid_arg "choose_vertex" with Found_Edge v -> v end module Neighbourhood(G : sig type t module V : Sig.COMPARABLE val fold_succ: (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val succ: t -> V.t -> V.t list end) = struct module Vertex_Set = Set.Make(G.V) let set_from_vertex g v = G.fold_succ (fun v' s -> if G.V.equal v v' then s else Vertex_Set.add v' s) g v Vertex_Set.empty let list_from_vertex g v = let rec aux = function | [] -> [] | v' :: l -> if G.V.equal v v' then begin assert (not (List.exists (G.V.equal v) l)); l end else v' :: aux l in aux (G.succ g v) let set_from_vertices g l = let fold_left f = List.fold_left f Vertex_Set.empty l in let env_init = fold_left (fun s v -> Vertex_Set.add v s) in let add x s = if Vertex_Set.mem x env_init then s else Vertex_Set.add x s in fold_left (fun s v -> G.fold_succ add g v s) let list_from_vertices g l = Vertex_Set.elements (set_from_vertices g l) end
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/external/ocamlgraph/src/oper.ml
ocaml
************************************************************************ This software is free software; you can redistribute it and/or described in file LICENSE. This software 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. ************************************************************************ Basic operations over graphs $v \notin g2$ add the graph [g1] in [g2]
: a generic graph library for OCaml Copyright ( C ) 2004 - 2007 , and modify it under the terms of the GNU Library General Public License version 2 , with the special exception on linking $ I d : oper.ml , v 1.13 2005 - 06 - 30 10:48:55 filliatr Exp $ module type S = sig type g val transitive_closure : ?reflexive:bool -> g -> g val add_transitive_closure : ?reflexive:bool -> g -> g val mirror : g -> g val complement : g -> g val intersect : g -> g -> g val union : g -> g -> g end module Make(B : Builder.S) = struct open B Roy - Warshall 's algorithm type g = G.t let add_transitive_closure ?(reflexive=false) g0 = let phi v g = let g = if reflexive then B.add_edge g v v else g in G.fold_succ (fun sv g -> G.fold_pred (fun pv g -> B.add_edge g pv sv) g v g) g v g in G.fold_vertex phi g0 g0 let transitive_closure ?(reflexive=false) g0 = add_transitive_closure ~reflexive (B.copy g0) module H = Hashtbl.Make(G.V) let mirror g = if G.is_directed then begin let g' = B.empty () in G.fold_edges_e (fun e g' -> let v1 = (G.E.src e) in let v2 = (G.E.dst e) in B.add_edge_e g' (G.E.create v2 (G.E.label e) v1)) g g' end else B.copy g let complement g = G.fold_vertex (fun v g' -> G.fold_vertex (fun w g' -> if G.mem_edge g v w then g' else B.add_edge g' v w) g g') g (B.empty ()) let intersect g1 g2 = G.fold_vertex (fun v g -> try let succ = G.succ_e g2 v in G.fold_succ_e (fun e g -> if List.mem e succ then B.add_edge_e g e else B.add_vertex g (G.E.dst e)) g1 v (B.add_vertex g v) with Invalid_argument _ -> g) g1 (B.empty ()) let union g1 g2 = let add g1 g2 = G.fold_vertex (fun v g -> G.fold_succ_e (fun e g -> B.add_edge_e g e) g1 v (B.add_vertex g v)) g1 g2 in add g1 (B.copy g2) end module P(G : Sig.P) = Make(Builder.P(G)) module I(G : Sig.I) = Make(Builder.I(G)) module Choose(G : sig type t type vertex type edge val iter_vertex : (vertex -> unit) -> t -> unit val iter_edges_e : (edge -> unit) -> t -> unit end) = struct exception Found_Vertex of G.vertex let choose_vertex g = try G.iter_vertex (fun v -> raise (Found_Vertex v)) g; invalid_arg "choose_vertex" with Found_Vertex v -> v exception Found_Edge of G.edge let choose_edge g = try G.iter_edges_e (fun v -> raise (Found_Edge v)) g; invalid_arg "choose_vertex" with Found_Edge v -> v end module Neighbourhood(G : sig type t module V : Sig.COMPARABLE val fold_succ: (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a val succ: t -> V.t -> V.t list end) = struct module Vertex_Set = Set.Make(G.V) let set_from_vertex g v = G.fold_succ (fun v' s -> if G.V.equal v v' then s else Vertex_Set.add v' s) g v Vertex_Set.empty let list_from_vertex g v = let rec aux = function | [] -> [] | v' :: l -> if G.V.equal v v' then begin assert (not (List.exists (G.V.equal v) l)); l end else v' :: aux l in aux (G.succ g v) let set_from_vertices g l = let fold_left f = List.fold_left f Vertex_Set.empty l in let env_init = fold_left (fun s v -> Vertex_Set.add v s) in let add x s = if Vertex_Set.mem x env_init then s else Vertex_Set.add x s in fold_left (fun s v -> G.fold_succ add g v s) let list_from_vertices g l = Vertex_Set.elements (set_from_vertices g l) end
d789896f7ec838671c32a45b5c7d13f1190bee54e41d446d4805c1d32cf816ec
tommaisey/aeon
soft-clip.help.scm
;; (soft-clip a) ;; Nonlinear distortion. Distortion with a perfectly linear region from -0.5 to +0.5 . (audition (out 0 (mul (soft-clip (mul (f-sin-osc ar 500 0.0) (x-line kr 0.1 10 10 do-nothing))) 0.25)))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/unary-ops/soft-clip.help.scm
scheme
(soft-clip a) Nonlinear distortion. Distortion with a perfectly linear region
from -0.5 to +0.5 . (audition (out 0 (mul (soft-clip (mul (f-sin-osc ar 500 0.0) (x-line kr 0.1 10 10 do-nothing))) 0.25)))
505125bfff8c517940de80c814d14c6f42f7917e7b7b8166dcab42ecfbacec08
teamwalnut/graphql-ppx
traversal_utils.ml
open Graphql_ast open Source_pos type ctx = { map_loc : source_position * source_position -> Result_structure.loc; fragments : (string, Graphql_ast.fragment) Hashtbl.t; schema : Schema.t; errors : (Result_structure.loc * string) list ref; warnings : (Result_structure.loc * string) list ref; type_stack : Schema.type_meta option list; type_literal_stack : Schema.type_ref option list; input_type_stack : Schema.type_meta option list; input_type_literal_stack : Schema.type_ref option list; parent_type_stack : Schema.type_meta option list; } module type VisitorSig = sig type t val make_self : unit -> t val enter_document : t -> ctx -> document -> unit val exit_document : t -> ctx -> document -> unit val enter_operation_definition : t -> ctx -> operation spanning -> unit val exit_operation_definition : t -> ctx -> operation spanning -> unit val enter_fragment_definition : t -> ctx -> fragment spanning -> unit val exit_fragment_definition : t -> ctx -> fragment spanning -> unit val enter_variable_definition : t -> ctx -> string spanning * variable_definition -> unit val exit_variable_definition : t -> ctx -> string spanning * variable_definition -> unit val enter_directive : t -> ctx -> directive spanning -> unit val exit_directive : t -> ctx -> directive spanning -> unit val enter_argument : t -> ctx -> string spanning * Schema.type_ref option * input_value spanning -> unit val exit_argument : t -> ctx -> string spanning * input_value spanning -> unit val enter_selection_set : t -> ctx -> selection list spanning -> unit val exit_selection_set : t -> ctx -> selection list spanning -> unit val enter_field : t -> ctx -> field spanning -> unit val exit_field : t -> ctx -> field spanning -> unit val enter_fragment_spread : t -> ctx -> fragment_spread spanning -> unit val exit_fragment_spread : t -> ctx -> fragment_spread spanning -> unit val enter_inline_fragment : t -> ctx -> inline_fragment spanning -> unit val exit_inline_fragment : t -> ctx -> inline_fragment spanning -> unit val enter_null_value : t -> ctx -> unit spanning -> unit val exit_null_value : t -> ctx -> unit spanning -> unit val enter_int_value : t -> ctx -> int spanning -> unit val exit_int_value : t -> ctx -> int spanning -> unit val enter_float_value : t -> ctx -> float spanning -> unit val exit_float_value : t -> ctx -> float spanning -> unit val enter_string_value : t -> ctx -> string spanning -> unit val exit_string_value : t -> ctx -> string spanning -> unit val enter_bool_value : t -> ctx -> bool spanning -> unit val exit_bool_value : t -> ctx -> bool spanning -> unit val enter_enum_value : t -> ctx -> string spanning -> unit val exit_enum_value : t -> ctx -> string spanning -> unit val enter_variable_value : t -> ctx -> string spanning -> unit val exit_variable_value : t -> ctx -> string spanning -> unit val enter_list_value : t -> ctx -> input_value spanning list spanning -> unit val exit_list_value : t -> ctx -> input_value spanning list spanning -> unit val enter_object_value : t -> ctx -> (string spanning * input_value spanning) list spanning -> unit val exit_object_value : t -> ctx -> (string spanning * input_value spanning) list spanning -> unit val enter_object_field : t -> ctx -> string spanning * input_value spanning -> unit val exit_object_field : t -> ctx -> string spanning * input_value spanning -> unit end module AbstractVisitor = struct let enter_document _self _ctx _ = () let exit_document _self _ctx _ = () let enter_operation_definition _self _ctx _ = () let exit_operation_definition _self _ctx _ = () let enter_fragment_definition _self _ctx _ = () let exit_fragment_definition _self _ctx _ = () let enter_variable_definition _self _ctx _ = () let exit_variable_definition _self _ctx _ = () let enter_directive _self _ctx _ = () let exit_directive _self _ctx _ = () let enter_argument _self _ctx _ = () let exit_argument _self _ctx _ = () let enter_selection_set _self _ctx _ = () let exit_selection_set _self _ctx _ = () let enter_field _self _ctx _ = () let exit_field _self _ctx _ = () let enter_fragment_spread _self _ctx _ = () let exit_fragment_spread _self _ctx _ = () let enter_inline_fragment _self _ctx _ = () let exit_inline_fragment _self _ctx _ = () let enter_null_value _self _ctx _ = () let exit_null_value _self _ctx _ = () let enter_int_value _self _ctx _ = () let exit_int_value _self _ctx _ = () let enter_float_value _self _ctx _ = () let exit_float_value _self _ctx _ = () let enter_string_value _self _ctx _ = () let exit_string_value _self _ctx _ = () let enter_bool_value _self _ctx _ = () let exit_bool_value _self _ctx _ = () let enter_enum_value _self _ctx _ = () let exit_enum_value _self _ctx _ = () let enter_variable_value _self _ctx _ = () let exit_variable_value _self _ctx _ = () let enter_list_value _self _ctx _ = () let exit_list_value _self _ctx _ = () let enter_object_value _self _ctx _ = () let exit_object_value _self _ctx _ = () let enter_object_field _self _ctx _ = () let exit_object_field _self _ctx _ = () end module Context = struct let push_type ctx type_ref = { ctx with type_stack = Option.flat_map (fun type_ref -> Schema.lookup_type ctx.schema (Schema.innermost_name type_ref)) type_ref :: ctx.type_stack; type_literal_stack = type_ref :: ctx.type_literal_stack; } let push_input_type ctx type_ref = { ctx with input_type_stack = Option.flat_map (fun type_ref -> Schema.lookup_type ctx.schema (Schema.innermost_name type_ref)) type_ref :: ctx.input_type_stack; input_type_literal_stack = type_ref :: ctx.input_type_literal_stack; } let push_parent_type ctx = let top = match ctx.type_stack with t :: _ -> t | [] -> None in { ctx with parent_type_stack = top :: ctx.parent_type_stack } let parent_type ctx = match ctx.parent_type_stack with t :: _ -> t | [] -> None let current_input_type_literal ctx = match ctx.input_type_literal_stack with t :: _ -> t | [] -> None let push_error ctx loc msg = ctx.errors := (ctx.map_loc loc, msg) :: !(ctx.errors) let push_warning ctx loc msg = ctx.warnings := (ctx.map_loc loc, msg) :: !(ctx.warnings) end let rec as_schema_type_ref = function | Tr_named { item; _ } -> Schema.Named item | Tr_list { item; _ } -> Schema.List (as_schema_type_ref item) | Tr_non_null_named { item; _ } -> Schema.NonNull (Schema.Named item) | Tr_non_null_list { item; _ } -> Schema.NonNull (Schema.List (as_schema_type_ref item)) module Visitor (V : VisitorSig) = struct let enter_input_value self ctx value = match value.item with | Iv_null -> V.enter_null_value self ctx (Source_pos.replace value ()) | Iv_int i -> V.enter_int_value self ctx (Source_pos.replace value i) | Iv_float f -> V.enter_float_value self ctx (Source_pos.replace value f) | Iv_string s -> V.enter_string_value self ctx (Source_pos.replace value s) | Iv_boolean b -> V.enter_bool_value self ctx (Source_pos.replace value b) | Iv_enum e -> V.enter_enum_value self ctx (Source_pos.replace value e) | Iv_variable v -> V.enter_variable_value self ctx (Source_pos.replace value v) | Iv_list l -> V.enter_list_value self ctx (Source_pos.replace value l) | Iv_object o -> V.enter_object_value self ctx (Source_pos.replace value o) let exit_input_value self ctx value = match value.item with | Iv_null -> V.exit_null_value self ctx (Source_pos.replace value ()) | Iv_int i -> V.exit_int_value self ctx (Source_pos.replace value i) | Iv_float f -> V.exit_float_value self ctx (Source_pos.replace value f) | Iv_string s -> V.exit_string_value self ctx (Source_pos.replace value s) | Iv_boolean b -> V.exit_bool_value self ctx (Source_pos.replace value b) | Iv_enum e -> V.exit_enum_value self ctx (Source_pos.replace value e) | Iv_variable v -> V.exit_variable_value self ctx (Source_pos.replace value v) | Iv_list l -> V.exit_list_value self ctx (Source_pos.replace value l) | Iv_object o -> V.exit_object_value self ctx (Source_pos.replace value o) let rec visit_input_value self ctx (arg_type : Schema.type_ref option) value = let () = enter_input_value self ctx value in let () = match ( arg_type |> Option.map Schema.innermost_name |> Option.flat_map (Schema.lookup_type ctx.schema), value.item ) with | Some (Scalar _ as ty), _ when ty |> Schema.is_type_default == false -> () | _, Iv_object fields -> List.iter (fun (key, value) -> let inner_type = Context.current_input_type_literal ctx |> Option.flat_map (function | Schema.Named name | Schema.NonNull (Schema.Named name) -> Schema.lookup_type ctx.schema name | _ -> None) |> Option.flat_map (fun t -> try Schema.lookup_input_field t key.item with | Schema.Invalid_type msg -> Context.push_error ctx key.span msg; None | other -> raise other) |> Option.map (fun am -> am.Schema.am_arg_type) in let ctx = Context.push_input_type ctx inner_type in let () = V.enter_object_field self ctx (key, value) in let () = visit_input_value self ctx inner_type value in V.exit_object_field self ctx (key, value)) fields | _, Iv_list items -> let inner_type = Context.current_input_type_literal ctx |> Option.flat_map (function | Schema.List inner | Schema.NonNull (Schema.List inner) -> Some inner | _ -> None) in let ctx = Context.push_input_type ctx inner_type in List.iter (visit_input_value self ctx inner_type) items | _ -> () in exit_input_value self ctx value let rec visit_inline_fragment self ctx inline_fragment = let ctx = match inline_fragment.item.if_type_condition with | None -> ctx | Some { item; _ } -> Context.push_type ctx (Some (Schema.NonNull (Schema.Named item))) in let () = V.enter_inline_fragment self ctx inline_fragment in let () = visit_directives self ctx inline_fragment.item.if_directives in let () = visit_selection_set self ctx inline_fragment.item.if_selection_set in V.exit_inline_fragment self ctx inline_fragment and visit_fragment_spread self ctx fragment_spread = let () = V.enter_fragment_spread self ctx fragment_spread in let () = visit_directives self ctx fragment_spread.item.fs_directives in V.exit_fragment_spread self ctx fragment_spread and visit_field self ctx field = let meta_field = Context.parent_type ctx |> Option.flat_map (fun t -> Schema.lookup_field t field.item.fd_name.item) in let field_type = Option.map (fun fm -> fm.Schema.fm_field_type) meta_field in let field_args = Option.map (fun fm -> fm.Schema.fm_arguments) meta_field in let ctx = Context.push_type ctx field_type in let () = V.enter_field self ctx field in let () = visit_arguments self ctx field_args field.item.fd_arguments in let () = visit_directives self ctx field.item.fd_directives in let () = match field.item.fd_selection_set with | None -> () | Some selection_set -> visit_selection_set self ctx selection_set in V.exit_field self ctx field and visit_selection self ctx = function | Field field -> visit_field self ctx field | FragmentSpread fragment_spread -> visit_fragment_spread self ctx fragment_spread | InlineFragment inline_fragment -> visit_inline_fragment self ctx inline_fragment and visit_selection_set self ctx selection_set = let ctx = Context.push_parent_type ctx in let () = V.enter_selection_set self ctx selection_set in let () = List.iter (visit_selection self ctx) selection_set.item in V.exit_selection_set self ctx selection_set and visit_arguments self ctx meta_args = function | None -> () | Some { item; _ } -> List.iter (fun (name, value) -> let arg_type = meta_args |> Option.flat_map (fun meta_args -> match List.find (fun am -> am.Schema.am_name = name.item) meta_args with | am -> Some am | exception Not_found -> None) |> Option.map (fun am -> am.Schema.am_arg_type) in let ctx = Context.push_input_type ctx arg_type in let () = V.enter_argument self ctx (name, arg_type, value) in let () = visit_input_value self ctx arg_type value in V.exit_argument self ctx (name, value)) item and visit_directives self ctx = List.iter (fun directive -> let meta_args = Schema.lookup_directive ctx.schema directive.item.d_name.item |> Option.map (fun d -> d.Schema.dm_arguments) in let () = V.enter_directive self ctx directive in let () = visit_arguments self ctx meta_args directive.item.d_arguments in V.exit_directive self ctx directive) let visit_variable_definitions self ctx = function | None -> () | Some { item; _ } -> List.iter (fun (name, def) -> let ctx = Context.push_input_type ctx (Some (as_schema_type_ref def.vd_type.item)) in let () = V.enter_variable_definition self ctx (name, def) in let () = match def.vd_default_value with | None -> () | Some value -> visit_input_value self ctx (Some (def.vd_type.item |> Type_utils.to_schema_type_ref)) value in V.exit_variable_definition self ctx (name, def)) item let visit_operation_definition self ctx operation = let () = visit_variable_definitions self ctx operation.o_variable_definitions in let () = visit_directives self ctx operation.o_directives in visit_selection_set self ctx operation.o_selection_set let visit_fragment_definition self ctx fragment = let () = visit_directives self ctx fragment.fg_directives in visit_selection_set self ctx fragment.fg_selection_set let visit_definition self ctx def = let def_type = Schema.NonNull (Schema.Named (match def with | Operation { item = { o_type = Query; _ }; _ } -> Schema.query_type ctx.schema |> Schema.type_name | Operation { item = { o_type = Mutation; _ }; _ } -> Schema.mutation_type ctx.schema |> Option.unsafe_unwrap ~reason:"Can't find mutation type" |> Schema.type_name | Operation { item = { o_type = Subscription; _ }; _ } -> Schema.subscription_type ctx.schema |> Option.unsafe_unwrap ~reason:"Can't find subscription type" |> Schema.type_name | Fragment { item = { fg_type_condition = { item; _ }; _ }; _ } -> item)) in let ctx = Context.push_type ctx (Some def_type) in match def with | Operation operation -> let () = V.enter_operation_definition self ctx operation in let () = visit_operation_definition self ctx operation.item in V.exit_operation_definition self ctx operation | Fragment fragment -> let () = V.enter_fragment_definition self ctx fragment in let () = visit_fragment_definition self ctx fragment.item in V.exit_fragment_definition self ctx fragment let visit_document ctx doc = let self = V.make_self () in let () = V.enter_document self ctx doc in let () = List.iter (visit_definition self ctx) doc in let () = V.exit_document self ctx doc in self end let find_fragments doc = let open Graphql_ast in let open Source_pos in let lookup = Hashtbl.create 1 in let () = List.iter (function | Fragment fragment -> Hashtbl.add lookup fragment.item.fg_name.item fragment.item | _ -> ()) doc in lookup let make_context config document = { map_loc = config.Generator_utils.map_loc; fragments = find_fragments document; schema = config.Generator_utils.schema; errors = ref []; warnings = ref []; type_stack = []; type_literal_stack = []; input_type_stack = []; input_type_literal_stack = []; parent_type_stack = []; }
null
https://raw.githubusercontent.com/teamwalnut/graphql-ppx/8276452ebe8d89a748b6b267afc94161650ab620/src/graphql_compiler/traversal_utils.ml
ocaml
open Graphql_ast open Source_pos type ctx = { map_loc : source_position * source_position -> Result_structure.loc; fragments : (string, Graphql_ast.fragment) Hashtbl.t; schema : Schema.t; errors : (Result_structure.loc * string) list ref; warnings : (Result_structure.loc * string) list ref; type_stack : Schema.type_meta option list; type_literal_stack : Schema.type_ref option list; input_type_stack : Schema.type_meta option list; input_type_literal_stack : Schema.type_ref option list; parent_type_stack : Schema.type_meta option list; } module type VisitorSig = sig type t val make_self : unit -> t val enter_document : t -> ctx -> document -> unit val exit_document : t -> ctx -> document -> unit val enter_operation_definition : t -> ctx -> operation spanning -> unit val exit_operation_definition : t -> ctx -> operation spanning -> unit val enter_fragment_definition : t -> ctx -> fragment spanning -> unit val exit_fragment_definition : t -> ctx -> fragment spanning -> unit val enter_variable_definition : t -> ctx -> string spanning * variable_definition -> unit val exit_variable_definition : t -> ctx -> string spanning * variable_definition -> unit val enter_directive : t -> ctx -> directive spanning -> unit val exit_directive : t -> ctx -> directive spanning -> unit val enter_argument : t -> ctx -> string spanning * Schema.type_ref option * input_value spanning -> unit val exit_argument : t -> ctx -> string spanning * input_value spanning -> unit val enter_selection_set : t -> ctx -> selection list spanning -> unit val exit_selection_set : t -> ctx -> selection list spanning -> unit val enter_field : t -> ctx -> field spanning -> unit val exit_field : t -> ctx -> field spanning -> unit val enter_fragment_spread : t -> ctx -> fragment_spread spanning -> unit val exit_fragment_spread : t -> ctx -> fragment_spread spanning -> unit val enter_inline_fragment : t -> ctx -> inline_fragment spanning -> unit val exit_inline_fragment : t -> ctx -> inline_fragment spanning -> unit val enter_null_value : t -> ctx -> unit spanning -> unit val exit_null_value : t -> ctx -> unit spanning -> unit val enter_int_value : t -> ctx -> int spanning -> unit val exit_int_value : t -> ctx -> int spanning -> unit val enter_float_value : t -> ctx -> float spanning -> unit val exit_float_value : t -> ctx -> float spanning -> unit val enter_string_value : t -> ctx -> string spanning -> unit val exit_string_value : t -> ctx -> string spanning -> unit val enter_bool_value : t -> ctx -> bool spanning -> unit val exit_bool_value : t -> ctx -> bool spanning -> unit val enter_enum_value : t -> ctx -> string spanning -> unit val exit_enum_value : t -> ctx -> string spanning -> unit val enter_variable_value : t -> ctx -> string spanning -> unit val exit_variable_value : t -> ctx -> string spanning -> unit val enter_list_value : t -> ctx -> input_value spanning list spanning -> unit val exit_list_value : t -> ctx -> input_value spanning list spanning -> unit val enter_object_value : t -> ctx -> (string spanning * input_value spanning) list spanning -> unit val exit_object_value : t -> ctx -> (string spanning * input_value spanning) list spanning -> unit val enter_object_field : t -> ctx -> string spanning * input_value spanning -> unit val exit_object_field : t -> ctx -> string spanning * input_value spanning -> unit end module AbstractVisitor = struct let enter_document _self _ctx _ = () let exit_document _self _ctx _ = () let enter_operation_definition _self _ctx _ = () let exit_operation_definition _self _ctx _ = () let enter_fragment_definition _self _ctx _ = () let exit_fragment_definition _self _ctx _ = () let enter_variable_definition _self _ctx _ = () let exit_variable_definition _self _ctx _ = () let enter_directive _self _ctx _ = () let exit_directive _self _ctx _ = () let enter_argument _self _ctx _ = () let exit_argument _self _ctx _ = () let enter_selection_set _self _ctx _ = () let exit_selection_set _self _ctx _ = () let enter_field _self _ctx _ = () let exit_field _self _ctx _ = () let enter_fragment_spread _self _ctx _ = () let exit_fragment_spread _self _ctx _ = () let enter_inline_fragment _self _ctx _ = () let exit_inline_fragment _self _ctx _ = () let enter_null_value _self _ctx _ = () let exit_null_value _self _ctx _ = () let enter_int_value _self _ctx _ = () let exit_int_value _self _ctx _ = () let enter_float_value _self _ctx _ = () let exit_float_value _self _ctx _ = () let enter_string_value _self _ctx _ = () let exit_string_value _self _ctx _ = () let enter_bool_value _self _ctx _ = () let exit_bool_value _self _ctx _ = () let enter_enum_value _self _ctx _ = () let exit_enum_value _self _ctx _ = () let enter_variable_value _self _ctx _ = () let exit_variable_value _self _ctx _ = () let enter_list_value _self _ctx _ = () let exit_list_value _self _ctx _ = () let enter_object_value _self _ctx _ = () let exit_object_value _self _ctx _ = () let enter_object_field _self _ctx _ = () let exit_object_field _self _ctx _ = () end module Context = struct let push_type ctx type_ref = { ctx with type_stack = Option.flat_map (fun type_ref -> Schema.lookup_type ctx.schema (Schema.innermost_name type_ref)) type_ref :: ctx.type_stack; type_literal_stack = type_ref :: ctx.type_literal_stack; } let push_input_type ctx type_ref = { ctx with input_type_stack = Option.flat_map (fun type_ref -> Schema.lookup_type ctx.schema (Schema.innermost_name type_ref)) type_ref :: ctx.input_type_stack; input_type_literal_stack = type_ref :: ctx.input_type_literal_stack; } let push_parent_type ctx = let top = match ctx.type_stack with t :: _ -> t | [] -> None in { ctx with parent_type_stack = top :: ctx.parent_type_stack } let parent_type ctx = match ctx.parent_type_stack with t :: _ -> t | [] -> None let current_input_type_literal ctx = match ctx.input_type_literal_stack with t :: _ -> t | [] -> None let push_error ctx loc msg = ctx.errors := (ctx.map_loc loc, msg) :: !(ctx.errors) let push_warning ctx loc msg = ctx.warnings := (ctx.map_loc loc, msg) :: !(ctx.warnings) end let rec as_schema_type_ref = function | Tr_named { item; _ } -> Schema.Named item | Tr_list { item; _ } -> Schema.List (as_schema_type_ref item) | Tr_non_null_named { item; _ } -> Schema.NonNull (Schema.Named item) | Tr_non_null_list { item; _ } -> Schema.NonNull (Schema.List (as_schema_type_ref item)) module Visitor (V : VisitorSig) = struct let enter_input_value self ctx value = match value.item with | Iv_null -> V.enter_null_value self ctx (Source_pos.replace value ()) | Iv_int i -> V.enter_int_value self ctx (Source_pos.replace value i) | Iv_float f -> V.enter_float_value self ctx (Source_pos.replace value f) | Iv_string s -> V.enter_string_value self ctx (Source_pos.replace value s) | Iv_boolean b -> V.enter_bool_value self ctx (Source_pos.replace value b) | Iv_enum e -> V.enter_enum_value self ctx (Source_pos.replace value e) | Iv_variable v -> V.enter_variable_value self ctx (Source_pos.replace value v) | Iv_list l -> V.enter_list_value self ctx (Source_pos.replace value l) | Iv_object o -> V.enter_object_value self ctx (Source_pos.replace value o) let exit_input_value self ctx value = match value.item with | Iv_null -> V.exit_null_value self ctx (Source_pos.replace value ()) | Iv_int i -> V.exit_int_value self ctx (Source_pos.replace value i) | Iv_float f -> V.exit_float_value self ctx (Source_pos.replace value f) | Iv_string s -> V.exit_string_value self ctx (Source_pos.replace value s) | Iv_boolean b -> V.exit_bool_value self ctx (Source_pos.replace value b) | Iv_enum e -> V.exit_enum_value self ctx (Source_pos.replace value e) | Iv_variable v -> V.exit_variable_value self ctx (Source_pos.replace value v) | Iv_list l -> V.exit_list_value self ctx (Source_pos.replace value l) | Iv_object o -> V.exit_object_value self ctx (Source_pos.replace value o) let rec visit_input_value self ctx (arg_type : Schema.type_ref option) value = let () = enter_input_value self ctx value in let () = match ( arg_type |> Option.map Schema.innermost_name |> Option.flat_map (Schema.lookup_type ctx.schema), value.item ) with | Some (Scalar _ as ty), _ when ty |> Schema.is_type_default == false -> () | _, Iv_object fields -> List.iter (fun (key, value) -> let inner_type = Context.current_input_type_literal ctx |> Option.flat_map (function | Schema.Named name | Schema.NonNull (Schema.Named name) -> Schema.lookup_type ctx.schema name | _ -> None) |> Option.flat_map (fun t -> try Schema.lookup_input_field t key.item with | Schema.Invalid_type msg -> Context.push_error ctx key.span msg; None | other -> raise other) |> Option.map (fun am -> am.Schema.am_arg_type) in let ctx = Context.push_input_type ctx inner_type in let () = V.enter_object_field self ctx (key, value) in let () = visit_input_value self ctx inner_type value in V.exit_object_field self ctx (key, value)) fields | _, Iv_list items -> let inner_type = Context.current_input_type_literal ctx |> Option.flat_map (function | Schema.List inner | Schema.NonNull (Schema.List inner) -> Some inner | _ -> None) in let ctx = Context.push_input_type ctx inner_type in List.iter (visit_input_value self ctx inner_type) items | _ -> () in exit_input_value self ctx value let rec visit_inline_fragment self ctx inline_fragment = let ctx = match inline_fragment.item.if_type_condition with | None -> ctx | Some { item; _ } -> Context.push_type ctx (Some (Schema.NonNull (Schema.Named item))) in let () = V.enter_inline_fragment self ctx inline_fragment in let () = visit_directives self ctx inline_fragment.item.if_directives in let () = visit_selection_set self ctx inline_fragment.item.if_selection_set in V.exit_inline_fragment self ctx inline_fragment and visit_fragment_spread self ctx fragment_spread = let () = V.enter_fragment_spread self ctx fragment_spread in let () = visit_directives self ctx fragment_spread.item.fs_directives in V.exit_fragment_spread self ctx fragment_spread and visit_field self ctx field = let meta_field = Context.parent_type ctx |> Option.flat_map (fun t -> Schema.lookup_field t field.item.fd_name.item) in let field_type = Option.map (fun fm -> fm.Schema.fm_field_type) meta_field in let field_args = Option.map (fun fm -> fm.Schema.fm_arguments) meta_field in let ctx = Context.push_type ctx field_type in let () = V.enter_field self ctx field in let () = visit_arguments self ctx field_args field.item.fd_arguments in let () = visit_directives self ctx field.item.fd_directives in let () = match field.item.fd_selection_set with | None -> () | Some selection_set -> visit_selection_set self ctx selection_set in V.exit_field self ctx field and visit_selection self ctx = function | Field field -> visit_field self ctx field | FragmentSpread fragment_spread -> visit_fragment_spread self ctx fragment_spread | InlineFragment inline_fragment -> visit_inline_fragment self ctx inline_fragment and visit_selection_set self ctx selection_set = let ctx = Context.push_parent_type ctx in let () = V.enter_selection_set self ctx selection_set in let () = List.iter (visit_selection self ctx) selection_set.item in V.exit_selection_set self ctx selection_set and visit_arguments self ctx meta_args = function | None -> () | Some { item; _ } -> List.iter (fun (name, value) -> let arg_type = meta_args |> Option.flat_map (fun meta_args -> match List.find (fun am -> am.Schema.am_name = name.item) meta_args with | am -> Some am | exception Not_found -> None) |> Option.map (fun am -> am.Schema.am_arg_type) in let ctx = Context.push_input_type ctx arg_type in let () = V.enter_argument self ctx (name, arg_type, value) in let () = visit_input_value self ctx arg_type value in V.exit_argument self ctx (name, value)) item and visit_directives self ctx = List.iter (fun directive -> let meta_args = Schema.lookup_directive ctx.schema directive.item.d_name.item |> Option.map (fun d -> d.Schema.dm_arguments) in let () = V.enter_directive self ctx directive in let () = visit_arguments self ctx meta_args directive.item.d_arguments in V.exit_directive self ctx directive) let visit_variable_definitions self ctx = function | None -> () | Some { item; _ } -> List.iter (fun (name, def) -> let ctx = Context.push_input_type ctx (Some (as_schema_type_ref def.vd_type.item)) in let () = V.enter_variable_definition self ctx (name, def) in let () = match def.vd_default_value with | None -> () | Some value -> visit_input_value self ctx (Some (def.vd_type.item |> Type_utils.to_schema_type_ref)) value in V.exit_variable_definition self ctx (name, def)) item let visit_operation_definition self ctx operation = let () = visit_variable_definitions self ctx operation.o_variable_definitions in let () = visit_directives self ctx operation.o_directives in visit_selection_set self ctx operation.o_selection_set let visit_fragment_definition self ctx fragment = let () = visit_directives self ctx fragment.fg_directives in visit_selection_set self ctx fragment.fg_selection_set let visit_definition self ctx def = let def_type = Schema.NonNull (Schema.Named (match def with | Operation { item = { o_type = Query; _ }; _ } -> Schema.query_type ctx.schema |> Schema.type_name | Operation { item = { o_type = Mutation; _ }; _ } -> Schema.mutation_type ctx.schema |> Option.unsafe_unwrap ~reason:"Can't find mutation type" |> Schema.type_name | Operation { item = { o_type = Subscription; _ }; _ } -> Schema.subscription_type ctx.schema |> Option.unsafe_unwrap ~reason:"Can't find subscription type" |> Schema.type_name | Fragment { item = { fg_type_condition = { item; _ }; _ }; _ } -> item)) in let ctx = Context.push_type ctx (Some def_type) in match def with | Operation operation -> let () = V.enter_operation_definition self ctx operation in let () = visit_operation_definition self ctx operation.item in V.exit_operation_definition self ctx operation | Fragment fragment -> let () = V.enter_fragment_definition self ctx fragment in let () = visit_fragment_definition self ctx fragment.item in V.exit_fragment_definition self ctx fragment let visit_document ctx doc = let self = V.make_self () in let () = V.enter_document self ctx doc in let () = List.iter (visit_definition self ctx) doc in let () = V.exit_document self ctx doc in self end let find_fragments doc = let open Graphql_ast in let open Source_pos in let lookup = Hashtbl.create 1 in let () = List.iter (function | Fragment fragment -> Hashtbl.add lookup fragment.item.fg_name.item fragment.item | _ -> ()) doc in lookup let make_context config document = { map_loc = config.Generator_utils.map_loc; fragments = find_fragments document; schema = config.Generator_utils.schema; errors = ref []; warnings = ref []; type_stack = []; type_literal_stack = []; input_type_stack = []; input_type_literal_stack = []; parent_type_stack = []; }
25be54d4738440665dcbfb3eb19c1a8c4029110bc17d870cb3a9f24aca951b20
RunOrg/RunOrg
events.ml
(* © 2014 RunOrg *) open Std include type module [ `Created of < id : GId.t ; pid : PId.t option ; label : String.Label.t option ; audience : GroupAccess.Audience.t ; > | `Deleted of < id : GId.t ; pid : PId.t option ; > | `Added of < pid : PId.t option ; people : PId.t list ; groups : GId.t list ; > | `Removed of < pid : PId.t option ; people : PId.t list ; groups : GId.t list ; > | `Updated of < id : GId.t ; pid : PId.t option ; label : [ `Keep | `Set of String.Label.t option ] ; audience : [ `Keep | `Set of GroupAccess.Audience.t ] ; > ]
null
https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/groupLib/events.ml
ocaml
© 2014 RunOrg
open Std include type module [ `Created of < id : GId.t ; pid : PId.t option ; label : String.Label.t option ; audience : GroupAccess.Audience.t ; > | `Deleted of < id : GId.t ; pid : PId.t option ; > | `Added of < pid : PId.t option ; people : PId.t list ; groups : GId.t list ; > | `Removed of < pid : PId.t option ; people : PId.t list ; groups : GId.t list ; > | `Updated of < id : GId.t ; pid : PId.t option ; label : [ `Keep | `Set of String.Label.t option ] ; audience : [ `Keep | `Set of GroupAccess.Audience.t ] ; > ]
8a1c1fc727e8006183dd2989208657c03eaa009d51fda03033119de957e7d806
aharisu/Gauche-CV
seq.scm
;; ;;test section for <cv-seq> (test-section "cv.core#<cv-seq>") (define storage (make-cv-mem-storage)) (define seq (make-cv-seq storage)) (cv-seq-push seq 1) (cv-seq-push seq 2) (cv-seq-push seq 3) (test* "(cv-seq-pop seq)" 3 (cv-seq-pop seq)) (test* "(cv-seq-pop seq)" 2 (cv-seq-pop seq)) (test* "(cv-seq-pop seq)" 1 (cv-seq-pop seq)) (cv-seq-push-front seq 1) (cv-seq-push-front seq 2) (cv-seq-push-front seq 3) (test* "(cv-seq-pop-front seq)" 3 (cv-seq-pop-front seq)) (test* "(cv-seq-pop seq)" 1 (cv-seq-pop seq)) (cv-seq-push-multi seq #(1 2 3 4 5)) (test* "cv-seq-push-multi cv-seq-pop-multi (small size) (vector)" #(1 2 3 4 5) (cv-seq-pop-multi seq 5)) (cv-seq-push-multi seq #(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (test* "cv-seq-push-multi cv-seq-pop-multi (large size) (vector)" #(1 2 3 4 5 6 7 8 9 10 11 12 13 14) (cv-seq-pop-multi seq 14)) (cv-seq-push-multi seq '(1 2 3 4 5)) (test* "cv-seq-push-multi cv-seq-pop-multi (small size) (list)" #(1 2 3 4 5) (cv-seq-pop-multi seq 5)) (cv-seq-push-multi seq '(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (test* "cv-seq-push-multi cv-seq-pop-multi (large size) (list)" #(1 2 3 4 5 6 7 8 9 10 11 12 13 14) (cv-seq-pop-multi seq 14)) (cv-seq-push-multi seq #(1 2 3)) (cv-clear-seq seq) (test* "(cv-seq-clear seq)" 0 (ref seq 'total)) (define writer (cv-start-append-to-seq seq)) (cv-write-seq-elem 1 writer) (cv-write-seq-elem 2 writer) (cv-write-seq-elem 3 writer) (cv-end-write-seq writer) (test* "<cv-seq-writer>" #(1 2 3) (cv-seq-pop-multi seq 3)) (cv-seq-push-multi seq #(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (define reader (cv-start-read-seq seq)) (test* "cv-read-seq-elem" 1 (cv-read-seq-elem reader)) (cv-next-seq-elem reader) (test* "cv-next-seq-elem cv-ref-req-elem" 3 (cv-ref-seq-elem reader)) (cv-prev-seq-elem reader) (test* "cv-prev-seq-elem cv-ref-req-elem" 2 (cv-ref-seq-elem reader)) (cv-set-seq-reader-pos reader 4) (test* "cv-set-seq-reader-pos cv-get-seq-reader-pos" 4 (cv-get-seq-reader-pos reader))
null
https://raw.githubusercontent.com/aharisu/Gauche-CV/5e4c51501431c72270765121ea4d92693f11d60b/src/test/seq.scm
scheme
test section for <cv-seq>
(test-section "cv.core#<cv-seq>") (define storage (make-cv-mem-storage)) (define seq (make-cv-seq storage)) (cv-seq-push seq 1) (cv-seq-push seq 2) (cv-seq-push seq 3) (test* "(cv-seq-pop seq)" 3 (cv-seq-pop seq)) (test* "(cv-seq-pop seq)" 2 (cv-seq-pop seq)) (test* "(cv-seq-pop seq)" 1 (cv-seq-pop seq)) (cv-seq-push-front seq 1) (cv-seq-push-front seq 2) (cv-seq-push-front seq 3) (test* "(cv-seq-pop-front seq)" 3 (cv-seq-pop-front seq)) (test* "(cv-seq-pop seq)" 1 (cv-seq-pop seq)) (cv-seq-push-multi seq #(1 2 3 4 5)) (test* "cv-seq-push-multi cv-seq-pop-multi (small size) (vector)" #(1 2 3 4 5) (cv-seq-pop-multi seq 5)) (cv-seq-push-multi seq #(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (test* "cv-seq-push-multi cv-seq-pop-multi (large size) (vector)" #(1 2 3 4 5 6 7 8 9 10 11 12 13 14) (cv-seq-pop-multi seq 14)) (cv-seq-push-multi seq '(1 2 3 4 5)) (test* "cv-seq-push-multi cv-seq-pop-multi (small size) (list)" #(1 2 3 4 5) (cv-seq-pop-multi seq 5)) (cv-seq-push-multi seq '(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (test* "cv-seq-push-multi cv-seq-pop-multi (large size) (list)" #(1 2 3 4 5 6 7 8 9 10 11 12 13 14) (cv-seq-pop-multi seq 14)) (cv-seq-push-multi seq #(1 2 3)) (cv-clear-seq seq) (test* "(cv-seq-clear seq)" 0 (ref seq 'total)) (define writer (cv-start-append-to-seq seq)) (cv-write-seq-elem 1 writer) (cv-write-seq-elem 2 writer) (cv-write-seq-elem 3 writer) (cv-end-write-seq writer) (test* "<cv-seq-writer>" #(1 2 3) (cv-seq-pop-multi seq 3)) (cv-seq-push-multi seq #(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) (define reader (cv-start-read-seq seq)) (test* "cv-read-seq-elem" 1 (cv-read-seq-elem reader)) (cv-next-seq-elem reader) (test* "cv-next-seq-elem cv-ref-req-elem" 3 (cv-ref-seq-elem reader)) (cv-prev-seq-elem reader) (test* "cv-prev-seq-elem cv-ref-req-elem" 2 (cv-ref-seq-elem reader)) (cv-set-seq-reader-pos reader 4) (test* "cv-set-seq-reader-pos cv-get-seq-reader-pos" 4 (cv-get-seq-reader-pos reader))
4016fdd4374ad7476781aca9e6679154a52adbec372e8069e1857459958d9464
manuel-serrano/hop
hintnum.scm
;*=====================================================================*/ * serrano / prgm / project / hop / hop / js2scheme / hintnum.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue May 1 16:06:44 2018 * / * Last change : Sun Nov 21 10:02:50 2021 ( serrano ) * / * Copyright : 2018 - 21 * / ;* ------------------------------------------------------------- */ ;* hint typing of numerical values. */ ;* ------------------------------------------------------------- */ ;* This optimization consists in propagating expression and */ ;* declaration hints that will be used by the code generator. */ ;* ------------------------------------------------------------- */ * Two top - down hints are propagated on unary op , binary op , and * / ;* assignments. */ ;* */ * 1- if only one argument of binary expression is typed / hinted , * / * add its type / hint as a hint of the second argument . * / ;* 2- if the result is typed/hinted, propagate that hint to the */ ;* arguments. */ * 3- in a variable assignment ( aliasing ) , if one of the vars * / ;* is hinted/typed, the hint is propagated. */ ;* */ ;* This propagation iterates until the fix point is reached. */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __js2scheme_hintnum (include "ast.sch") (import __js2scheme_ast __js2scheme_dump __js2scheme_utils __js2scheme_compile __js2scheme_stage) (export j2s-hintnum-stage)) ;*---------------------------------------------------------------------*/ * ... * / ;*---------------------------------------------------------------------*/ (define j2s-hintnum-stage (instantiate::J2SStageProc (name "hintnum") (comment "Numerical hint typing") (optional :optim-hintnum) (proc j2s-hintnum))) ;*---------------------------------------------------------------------*/ * ... * / ;*---------------------------------------------------------------------*/ (define (j2s-hintnum this conf) (define j2s-verbose (config-get conf :verbose 0)) (when (isa? this J2SProgram) (when (>=fx j2s-verbose 3) (display " " (current-error-port))) (let global-loop () (let ((fix (make-cell #t))) (let loop ((i 1)) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "~a." i) (flush-output-port (current-error-port))) (cell-set! fix #t) (hintnum this #f fix) (unless (cell-ref fix) (loop (+fx i 1))))) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "/")) (let ((fix (make-cell #t))) (let loop ((i 1)) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "~a." i) (flush-output-port (current-error-port))) (cell-set! fix #t) (propagate-types this fix) (cond ((not (cell-ref fix)) (loop (+fx i 1))) ((>fx i 1) (global-loop))))))) (propagate-real! this) this) ;*---------------------------------------------------------------------*/ ;* expr-hint ... */ ;*---------------------------------------------------------------------*/ (define (expr-hint::pair-nil this::J2SExpr) (with-access::J2SExpr this (type hint) (cond ((not (memq type '(number any integer real))) (list (cons type 100))) ((pair? hint) hint) (else '())))) ;*---------------------------------------------------------------------*/ ;* add-expr-hint! ... */ ;*---------------------------------------------------------------------*/ (define (add-expr-hint! this::J2SExpr newhint propagate::bool fix) (define (add-hint!::pair-nil hint::pair-nil newhint::pair-nil) (if (null? hint) (begin (cell-set! fix #f) newhint) (let loop ((hint hint) (newhint newhint)) (if (null? newhint) hint (let* ((h (car newhint)) (o (assq (car h) hint))) (let ((nh (cond ((not (pair? o)) (cell-set! fix #f) (cons h hint)) ((<fx (cdr o) 0) hint) ((<fx (cdr h) 0) (if (>=fx (cdr o) 0) (begin (cell-set! fix #f) (cons h (remq o hint))) hint)) ((<fx (cdr o) (cdr h)) (cell-set! fix #f) (cons h (remq o hint))) (else hint)))) (loop nh (cdr newhint)))))))) (when (pair? newhint) (with-access::J2SExpr this (hint) (set! hint (add-hint! hint newhint))) (when (and propagate (isa? this J2SRef)) (with-access::J2SRef this (decl) (let loop ((decl decl)) (with-access::J2SDecl decl (hint id loc %info) (unless (isa? decl J2SThis) (set! hint (add-hint! hint newhint)) (when (and (pair? %info) (eq? (car %info) 'hintnum-alias)) (loop (cdr %info)))))))))) ;*---------------------------------------------------------------------*/ ;* union-hint! ... */ ;*---------------------------------------------------------------------*/ (define (union-hint! x y) (for-each (lambda (x) (let ((c (assq (car x) y))) (cond ((not (pair? c)) (set! y (cons x y))) ((<fx (cdr x) 0) (set-cdr! c (cdr x))) ((>=fx (cdr c) 0) (set-cdr! c (max (cdr x) (cdr c))))))) x) y) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SNode ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SNode assig::bool fix::cell) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SReturn ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SReturn assig::bool fix::cell) (with-access::J2SReturn this (from expr) (when (isa? from J2SBindExit) (with-access::J2SBindExit from (hint) (add-expr-hint! expr hint #t fix))) (call-default-walker))) ;*---------------------------------------------------------------------*/ ;* hintnum-binary ... */ ;*---------------------------------------------------------------------*/ (define (hintnum-binary this op lhs rhs fix) (define (hintnum-result!) (when (memq (j2s-type lhs) '(any number)) (add-expr-hint! lhs (expr-hint this) #t fix)) (when (memq (j2s-type rhs) '(any number)) (add-expr-hint! rhs (expr-hint this) #t fix))) (case op ((+ ++) (hintnum-result!) (when (eq? op '++) (add-expr-hint! lhs '((integer . 2)) #f fix) (add-expr-hint! this '((integer . 2)) #f fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (add-expr-hint! lhs hint #t fix) (add-expr-hint! this hint #f fix)))) ((-) (hintnum-result!) (unless (eq? (j2s-type lhs) 'any) (unhint-string-ref lhs fix)) (unless (eq? (j2s-type rhs) 'any) (unhint-string-ref rhs fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (unless (eq? (j2s-type lhs) 'any) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) hint) #t fix)) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint lhs)))) (unless (eq? (j2s-type rhs) 'any) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) hint) #t fix)) (add-expr-hint! this hint #f fix)))) ((-- *) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix) (when (eq? op '--) (add-expr-hint! lhs '((integer . 2)) #f fix) (add-expr-hint! this '((integer . 2)) #f fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) hint) #t fix) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint lhs)))) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) hint) #t fix) (add-expr-hint! this hint #f fix)))) ((/ %) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix) (when (memq (j2s-type lhs) '(any number)) (let* ((hint (union-hint! (expr-hint this) (expr-hint rhs))) (noreal (filter (lambda (c) (not (eq? (car c) 'real))) hint))) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) noreal) #t fix) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let* ((hint (union-hint! (expr-hint this) (expr-hint lhs))) (noreal (filter (lambda (c) (not (eq? (car c) 'real))) hint))) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) noreal) #t fix) (add-expr-hint! this hint #f fix)))) ((< > <= >= == === != !==) (when (memq (j2s-type lhs) '(any number)) (unless (eq? (j2s-type lhs) 'any) (unhint-string-ref lhs fix)) (let ((hint (expr-hint rhs))) (when (and (pair? hint) (eq? op '>=)) (add-expr-hint! lhs hint #t fix)))) (when (memq (j2s-type rhs) '(any number)) (unless (eq? (j2s-type rhs) 'any) (unhint-string-ref rhs fix)) (let ((hint (expr-hint lhs))) (add-expr-hint! rhs hint #t fix)))) ((>> >>> << BIT_OR & ^) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix)) ((&& ||) (hintnum-result!) (hintnum lhs #f fix) (hintnum rhs #f fix)))) ;*---------------------------------------------------------------------*/ ;* unhint-string-ref ... */ ;*---------------------------------------------------------------------*/ (define (unhint-string-ref expr fix) (when (isa? expr J2SAccess) (with-access::J2SAccess expr (obj) (add-expr-hint! obj (list `(string . ,(minvalfx))) #t fix)))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SBinary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SBinary assig fix::cell) (call-default-walker) (with-access::J2SBinary this (lhs rhs op loc hint) (hintnum-binary this op lhs rhs fix))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SUnary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SUnary assig fix::cell) (call-default-walker) (with-access::J2SUnary this (expr) (when (memq (j2s-type expr) '(any number)) (add-expr-hint! expr (expr-hint this) #t fix)))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SParen ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SParen assig fix::cell) (call-default-walker) (with-access::J2SParen this (expr) (when (memq (j2s-type expr) '(any number)) (add-expr-hint! expr (expr-hint this) #t fix)))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SAssigOp ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SAssigOp assig fix::cell) (with-access::J2SAssigOp this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SPostfix ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SPostfix assig fix::cell) (with-access::J2SPostfix this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SPrefix ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SPrefix assig fix::cell) (with-access::J2SPrefix this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SRef assig fix::cell) (unless assig (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (hint (loc2 loc)) (add-expr-hint! this hint #f fix))))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SDeclInit ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SDeclInit assig fix::cell) (call-default-walker) (with-access::J2SDeclInit this (hint val vtype loc %info) (when (isa? val J2SRef) (with-access::J2SRef val (decl) (set! %info (cons 'hintnum-alias decl)))) (unless (isa? this J2SDeclFun) (add-expr-hint! val hint #f fix) (when (and (is-hint? val 'real) (memq vtype '(integer number))) (set! vtype 'real) (when (isa? val J2SUndefined) (with-access::J2SUndefined val (loc) (set! val (J2SNumber 0.0)))))))) ;*---------------------------------------------------------------------*/ ;* hintnum ::J2SAssig ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SAssig assig fix::cell) (with-access::J2SAssig this (lhs rhs) (hintnum lhs #t fix) (hintnum rhs #f fix) propagate all the negative types of the lhs (when (isa? lhs J2SRef) (with-access::J2SRef lhs (decl) (with-access::J2SDecl decl (hint) (for-each (lambda (h) (when (=fx (cdr h) (minvalfx)) (add-expr-hint! rhs (list h) #t fix))) hint)))) (cond ((is-hint? lhs 'real) (add-expr-hint! rhs (expr-hint lhs) #f fix)) ((is-hint? rhs 'real) (add-expr-hint! this (expr-hint rhs) #f fix) (when (isa? lhs J2SRef) (add-expr-hint! lhs (expr-hint rhs) #t fix))) ((eq? (j2s-type rhs) 'real) (add-expr-hint! this '((real . 20)) #f fix) (when (isa? lhs J2SRef) (add-expr-hint! lhs '((real . 20)) #t fix)))))) ;*---------------------------------------------------------------------*/ ;* hinthum ::J2SCall ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (hintnum this::J2SCall assig fix::cell) (define (math-call? fun args) (when (and (pair? args) (isa? fun J2SAccess)) (with-access::J2SAccess fun (obj field) (when (and (is-builtin-ref? obj 'Math) (isa? field J2SString)) (with-access::J2SString field (val) (member val '("floor" "round" "ceil"))))))) (define (math-callfl? fun args) (when (and (pair? args) (isa? fun J2SAccess)) (with-access::J2SAccess fun (obj field) (when (and (is-builtin-ref? obj 'Math) (isa? field J2SString)) (with-access::J2SString field (val) (member val '("asin" "sin" "acos" "cos" "sqrt" "log"))))))) (call-default-walker) (with-access::J2SCall this (fun args) (cond ((math-callfl? fun args) (add-expr-hint! (car args) '((real . 40)) #f fix) (add-expr-hint! this '((real . 40)) #f fix)) ((math-call? fun args) (add-expr-hint! (car args) '((real . 2)) #f fix))))) ;*---------------------------------------------------------------------*/ ;* type<? ... */ ;*---------------------------------------------------------------------*/ (define (type<? t1 t2) (unless (eq? t1 t2) (eq? t1 'real))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SNode ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SNode fix::cell) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SRef ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SRef fix::cell) (with-access::J2SRef this (decl type) (with-access::J2SDecl decl (vtype) (when (type<? vtype type) (set! type vtype) (cell-set! fix #f))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SBinary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SBinary fix::cell) (call-default-walker) (with-access::J2SBinary this (op lhs rhs type loc) (when (memq op '(- -- / * + ++)) (when (or (eq? (j2s-vtype lhs) 'real) (eq? (j2s-vtype rhs) 'real)) (when (memq (j2s-vtype lhs) '(number integer)) (set! lhs (J2SCast 'real lhs))) (when (memq (j2s-vtype rhs) '(number integer)) (set! rhs (J2SCast 'real rhs))) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f)))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SPrefix ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SPrefix fix::cell) (call-default-walker) (with-access::J2SPrefix this (rhs type) (when (eq? (j2s-type rhs) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SPostfix ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SPostfix fix::cell) (call-default-walker) (with-access::J2SPostfix this (rhs type) (when (eq? (j2s-type rhs) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SUnary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SUnary fix::cell) (call-default-walker) (with-access::J2SUnary this (op expr type) (when (memq op '(- +)) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f)))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SParen ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SParen fix::cell) (call-default-walker) (with-access::J2SParen this (expr type loc) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) ;*---------------------------------------------------------------------*/ ;* propagate-types ::J2SDeclInit ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-types this::J2SDeclInit fix::cell) (call-default-walker) (with-access::J2SDeclInit this (val vtype) (when (and (memq vtype '(integer number)) (eq? (j2s-vtype val) 'real)) (set! vtype 'real) (cell-set! fix #f)))) ;*---------------------------------------------------------------------*/ ;* propagate-real! ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-real! this::J2SNode) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* propagate-real! ::J2SExpr ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-real! this::J2SExpr) (call-default-walker) (with-access::J2SExpr this (type loc) (if (and (is-hint? this 'real) (not (eq? type 'real)) (memq type '(number integer))) (as-real! this) this))) ;*---------------------------------------------------------------------*/ ;* propagate-real! ::J2SParen ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-real! this::J2SParen) (call-default-walker) (with-access::J2SParen this (expr type loc) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real)))) this) ;*---------------------------------------------------------------------*/ ;* propagate-real! ::J2SCast ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (propagate-real! this::J2SCast) (with-access::J2SCast this (type) (when (and (is-hint? this 'real) (not (eq? type 'real))) (set! type 'real))) this) ;*---------------------------------------------------------------------*/ ;* as-real! ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SNode) (call-default-walker)) ;*---------------------------------------------------------------------*/ ;* as-real! ::J2SExpr ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SExpr) (if (eq? (j2s-vtype this) 'real) this (with-access::J2SExpr this (loc) (J2SCast 'real this)))) ;*---------------------------------------------------------------------*/ ;* as-real! ::J2SBinary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SBinary) (call-default-walker) (with-access::J2SBinary this (type) (set! type 'real)) this) ;*---------------------------------------------------------------------*/ ;* as-real! ::J2SUnary ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SUnary) (call-default-walker) (with-access::J2SUnary this (type) (set! type 'real)) this) ;*---------------------------------------------------------------------*/ ;* as-real! ::J2SCast ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SCast) (with-access::J2SCast this (type) (set! type 'real) this)) ;*---------------------------------------------------------------------*/ ;* as-real! ::J2SParen ... */ ;*---------------------------------------------------------------------*/ (define-walk-method (as-real! this::J2SParen) (with-access::J2SParen this (expr type loc) (if (eq? (j2s-type expr) 'real) (begin (set! type 'real) this) (J2SCast 'real this))))
null
https://raw.githubusercontent.com/manuel-serrano/hop/6510926d28b54ee4e3f72950838a1bb3724eca39/js2scheme/hintnum.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * hint typing of numerical values. */ * ------------------------------------------------------------- */ * This optimization consists in propagating expression and */ * declaration hints that will be used by the code generator. */ * ------------------------------------------------------------- */ * assignments. */ * */ * 2- if the result is typed/hinted, propagate that hint to the */ * arguments. */ * is hinted/typed, the hint is propagated. */ * */ * This propagation iterates until the fix point is reached. */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * expr-hint ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * add-expr-hint! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * union-hint! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SNode ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SReturn ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum-binary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * unhint-string-ref ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SBinary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SUnary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SParen ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SAssigOp ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SPostfix ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SPrefix ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SDeclInit ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hintnum ::J2SAssig ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * hinthum ::J2SCall ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * type<? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SNode ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SRef ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SBinary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SPrefix ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SPostfix ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SUnary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SParen ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-types ::J2SDeclInit ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-real! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-real! ::J2SExpr ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-real! ::J2SParen ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * propagate-real! ::J2SCast ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ::J2SExpr ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ::J2SBinary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ::J2SUnary ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ::J2SCast ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * as-real! ::J2SParen ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / hop / hop / js2scheme / hintnum.scm * / * Author : * / * Creation : Tue May 1 16:06:44 2018 * / * Last change : Sun Nov 21 10:02:50 2021 ( serrano ) * / * Copyright : 2018 - 21 * / * Two top - down hints are propagated on unary op , binary op , and * / * 1- if only one argument of binary expression is typed / hinted , * / * add its type / hint as a hint of the second argument . * / * 3- in a variable assignment ( aliasing ) , if one of the vars * / (module __js2scheme_hintnum (include "ast.sch") (import __js2scheme_ast __js2scheme_dump __js2scheme_utils __js2scheme_compile __js2scheme_stage) (export j2s-hintnum-stage)) * ... * / (define j2s-hintnum-stage (instantiate::J2SStageProc (name "hintnum") (comment "Numerical hint typing") (optional :optim-hintnum) (proc j2s-hintnum))) * ... * / (define (j2s-hintnum this conf) (define j2s-verbose (config-get conf :verbose 0)) (when (isa? this J2SProgram) (when (>=fx j2s-verbose 3) (display " " (current-error-port))) (let global-loop () (let ((fix (make-cell #t))) (let loop ((i 1)) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "~a." i) (flush-output-port (current-error-port))) (cell-set! fix #t) (hintnum this #f fix) (unless (cell-ref fix) (loop (+fx i 1))))) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "/")) (let ((fix (make-cell #t))) (let loop ((i 1)) (when (>=fx j2s-verbose 3) (fprintf (current-error-port) "~a." i) (flush-output-port (current-error-port))) (cell-set! fix #t) (propagate-types this fix) (cond ((not (cell-ref fix)) (loop (+fx i 1))) ((>fx i 1) (global-loop))))))) (propagate-real! this) this) (define (expr-hint::pair-nil this::J2SExpr) (with-access::J2SExpr this (type hint) (cond ((not (memq type '(number any integer real))) (list (cons type 100))) ((pair? hint) hint) (else '())))) (define (add-expr-hint! this::J2SExpr newhint propagate::bool fix) (define (add-hint!::pair-nil hint::pair-nil newhint::pair-nil) (if (null? hint) (begin (cell-set! fix #f) newhint) (let loop ((hint hint) (newhint newhint)) (if (null? newhint) hint (let* ((h (car newhint)) (o (assq (car h) hint))) (let ((nh (cond ((not (pair? o)) (cell-set! fix #f) (cons h hint)) ((<fx (cdr o) 0) hint) ((<fx (cdr h) 0) (if (>=fx (cdr o) 0) (begin (cell-set! fix #f) (cons h (remq o hint))) hint)) ((<fx (cdr o) (cdr h)) (cell-set! fix #f) (cons h (remq o hint))) (else hint)))) (loop nh (cdr newhint)))))))) (when (pair? newhint) (with-access::J2SExpr this (hint) (set! hint (add-hint! hint newhint))) (when (and propagate (isa? this J2SRef)) (with-access::J2SRef this (decl) (let loop ((decl decl)) (with-access::J2SDecl decl (hint id loc %info) (unless (isa? decl J2SThis) (set! hint (add-hint! hint newhint)) (when (and (pair? %info) (eq? (car %info) 'hintnum-alias)) (loop (cdr %info)))))))))) (define (union-hint! x y) (for-each (lambda (x) (let ((c (assq (car x) y))) (cond ((not (pair? c)) (set! y (cons x y))) ((<fx (cdr x) 0) (set-cdr! c (cdr x))) ((>=fx (cdr c) 0) (set-cdr! c (max (cdr x) (cdr c))))))) x) y) (define-walk-method (hintnum this::J2SNode assig::bool fix::cell) (call-default-walker)) (define-walk-method (hintnum this::J2SReturn assig::bool fix::cell) (with-access::J2SReturn this (from expr) (when (isa? from J2SBindExit) (with-access::J2SBindExit from (hint) (add-expr-hint! expr hint #t fix))) (call-default-walker))) (define (hintnum-binary this op lhs rhs fix) (define (hintnum-result!) (when (memq (j2s-type lhs) '(any number)) (add-expr-hint! lhs (expr-hint this) #t fix)) (when (memq (j2s-type rhs) '(any number)) (add-expr-hint! rhs (expr-hint this) #t fix))) (case op ((+ ++) (hintnum-result!) (when (eq? op '++) (add-expr-hint! lhs '((integer . 2)) #f fix) (add-expr-hint! this '((integer . 2)) #f fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (add-expr-hint! lhs hint #t fix) (add-expr-hint! this hint #f fix)))) ((-) (hintnum-result!) (unless (eq? (j2s-type lhs) 'any) (unhint-string-ref lhs fix)) (unless (eq? (j2s-type rhs) 'any) (unhint-string-ref rhs fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (unless (eq? (j2s-type lhs) 'any) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) hint) #t fix)) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint lhs)))) (unless (eq? (j2s-type rhs) 'any) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) hint) #t fix)) (add-expr-hint! this hint #f fix)))) ((-- *) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix) (when (eq? op '--) (add-expr-hint! lhs '((integer . 2)) #f fix) (add-expr-hint! this '((integer . 2)) #f fix)) (when (memq (j2s-type lhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint rhs)))) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) hint) #t fix) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let ((hint (union-hint! (expr-hint this) (expr-hint lhs)))) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) hint) #t fix) (add-expr-hint! this hint #f fix)))) ((/ %) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix) (when (memq (j2s-type lhs) '(any number)) (let* ((hint (union-hint! (expr-hint this) (expr-hint rhs))) (noreal (filter (lambda (c) (not (eq? (car c) 'real))) hint))) (add-expr-hint! lhs (cons `(string . ,(minvalfx)) noreal) #t fix) (add-expr-hint! this hint #f fix))) (when (memq (j2s-type rhs) '(any number)) (let* ((hint (union-hint! (expr-hint this) (expr-hint lhs))) (noreal (filter (lambda (c) (not (eq? (car c) 'real))) hint))) (add-expr-hint! rhs (cons `(string . ,(minvalfx)) noreal) #t fix) (add-expr-hint! this hint #f fix)))) ((< > <= >= == === != !==) (when (memq (j2s-type lhs) '(any number)) (unless (eq? (j2s-type lhs) 'any) (unhint-string-ref lhs fix)) (let ((hint (expr-hint rhs))) (when (and (pair? hint) (eq? op '>=)) (add-expr-hint! lhs hint #t fix)))) (when (memq (j2s-type rhs) '(any number)) (unless (eq? (j2s-type rhs) 'any) (unhint-string-ref rhs fix)) (let ((hint (expr-hint lhs))) (add-expr-hint! rhs hint #t fix)))) ((>> >>> << BIT_OR & ^) (hintnum-result!) (unhint-string-ref lhs fix) (unhint-string-ref rhs fix)) ((&& ||) (hintnum-result!) (hintnum lhs #f fix) (hintnum rhs #f fix)))) (define (unhint-string-ref expr fix) (when (isa? expr J2SAccess) (with-access::J2SAccess expr (obj) (add-expr-hint! obj (list `(string . ,(minvalfx))) #t fix)))) (define-walk-method (hintnum this::J2SBinary assig fix::cell) (call-default-walker) (with-access::J2SBinary this (lhs rhs op loc hint) (hintnum-binary this op lhs rhs fix))) (define-walk-method (hintnum this::J2SUnary assig fix::cell) (call-default-walker) (with-access::J2SUnary this (expr) (when (memq (j2s-type expr) '(any number)) (add-expr-hint! expr (expr-hint this) #t fix)))) (define-walk-method (hintnum this::J2SParen assig fix::cell) (call-default-walker) (with-access::J2SParen this (expr) (when (memq (j2s-type expr) '(any number)) (add-expr-hint! expr (expr-hint this) #t fix)))) (define-walk-method (hintnum this::J2SAssigOp assig fix::cell) (with-access::J2SAssigOp this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) (define-walk-method (hintnum this::J2SPostfix assig fix::cell) (with-access::J2SPostfix this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) (define-walk-method (hintnum this::J2SPrefix assig fix::cell) (with-access::J2SPrefix this (op lhs rhs) (call-default-walker) (hintnum-binary this op lhs rhs fix))) (define-walk-method (hintnum this::J2SRef assig fix::cell) (unless assig (with-access::J2SRef this (decl loc) (with-access::J2SDecl decl (hint (loc2 loc)) (add-expr-hint! this hint #f fix))))) (define-walk-method (hintnum this::J2SDeclInit assig fix::cell) (call-default-walker) (with-access::J2SDeclInit this (hint val vtype loc %info) (when (isa? val J2SRef) (with-access::J2SRef val (decl) (set! %info (cons 'hintnum-alias decl)))) (unless (isa? this J2SDeclFun) (add-expr-hint! val hint #f fix) (when (and (is-hint? val 'real) (memq vtype '(integer number))) (set! vtype 'real) (when (isa? val J2SUndefined) (with-access::J2SUndefined val (loc) (set! val (J2SNumber 0.0)))))))) (define-walk-method (hintnum this::J2SAssig assig fix::cell) (with-access::J2SAssig this (lhs rhs) (hintnum lhs #t fix) (hintnum rhs #f fix) propagate all the negative types of the lhs (when (isa? lhs J2SRef) (with-access::J2SRef lhs (decl) (with-access::J2SDecl decl (hint) (for-each (lambda (h) (when (=fx (cdr h) (minvalfx)) (add-expr-hint! rhs (list h) #t fix))) hint)))) (cond ((is-hint? lhs 'real) (add-expr-hint! rhs (expr-hint lhs) #f fix)) ((is-hint? rhs 'real) (add-expr-hint! this (expr-hint rhs) #f fix) (when (isa? lhs J2SRef) (add-expr-hint! lhs (expr-hint rhs) #t fix))) ((eq? (j2s-type rhs) 'real) (add-expr-hint! this '((real . 20)) #f fix) (when (isa? lhs J2SRef) (add-expr-hint! lhs '((real . 20)) #t fix)))))) (define-walk-method (hintnum this::J2SCall assig fix::cell) (define (math-call? fun args) (when (and (pair? args) (isa? fun J2SAccess)) (with-access::J2SAccess fun (obj field) (when (and (is-builtin-ref? obj 'Math) (isa? field J2SString)) (with-access::J2SString field (val) (member val '("floor" "round" "ceil"))))))) (define (math-callfl? fun args) (when (and (pair? args) (isa? fun J2SAccess)) (with-access::J2SAccess fun (obj field) (when (and (is-builtin-ref? obj 'Math) (isa? field J2SString)) (with-access::J2SString field (val) (member val '("asin" "sin" "acos" "cos" "sqrt" "log"))))))) (call-default-walker) (with-access::J2SCall this (fun args) (cond ((math-callfl? fun args) (add-expr-hint! (car args) '((real . 40)) #f fix) (add-expr-hint! this '((real . 40)) #f fix)) ((math-call? fun args) (add-expr-hint! (car args) '((real . 2)) #f fix))))) (define (type<? t1 t2) (unless (eq? t1 t2) (eq? t1 'real))) (define-walk-method (propagate-types this::J2SNode fix::cell) (call-default-walker)) (define-walk-method (propagate-types this::J2SRef fix::cell) (with-access::J2SRef this (decl type) (with-access::J2SDecl decl (vtype) (when (type<? vtype type) (set! type vtype) (cell-set! fix #f))))) (define-walk-method (propagate-types this::J2SBinary fix::cell) (call-default-walker) (with-access::J2SBinary this (op lhs rhs type loc) (when (memq op '(- -- / * + ++)) (when (or (eq? (j2s-vtype lhs) 'real) (eq? (j2s-vtype rhs) 'real)) (when (memq (j2s-vtype lhs) '(number integer)) (set! lhs (J2SCast 'real lhs))) (when (memq (j2s-vtype rhs) '(number integer)) (set! rhs (J2SCast 'real rhs))) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f)))))) (define-walk-method (propagate-types this::J2SPrefix fix::cell) (call-default-walker) (with-access::J2SPrefix this (rhs type) (when (eq? (j2s-type rhs) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) (define-walk-method (propagate-types this::J2SPostfix fix::cell) (call-default-walker) (with-access::J2SPostfix this (rhs type) (when (eq? (j2s-type rhs) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) (define-walk-method (propagate-types this::J2SUnary fix::cell) (call-default-walker) (with-access::J2SUnary this (op expr type) (when (memq op '(- +)) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f)))))) (define-walk-method (propagate-types this::J2SParen fix::cell) (call-default-walker) (with-access::J2SParen this (expr type loc) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real) (cell-set! fix #f))))) (define-walk-method (propagate-types this::J2SDeclInit fix::cell) (call-default-walker) (with-access::J2SDeclInit this (val vtype) (when (and (memq vtype '(integer number)) (eq? (j2s-vtype val) 'real)) (set! vtype 'real) (cell-set! fix #f)))) (define-walk-method (propagate-real! this::J2SNode) (call-default-walker)) (define-walk-method (propagate-real! this::J2SExpr) (call-default-walker) (with-access::J2SExpr this (type loc) (if (and (is-hint? this 'real) (not (eq? type 'real)) (memq type '(number integer))) (as-real! this) this))) (define-walk-method (propagate-real! this::J2SParen) (call-default-walker) (with-access::J2SParen this (expr type loc) (when (eq? (j2s-type expr) 'real) (when (memq type '(number integer)) (set! type 'real)))) this) (define-walk-method (propagate-real! this::J2SCast) (with-access::J2SCast this (type) (when (and (is-hint? this 'real) (not (eq? type 'real))) (set! type 'real))) this) (define-walk-method (as-real! this::J2SNode) (call-default-walker)) (define-walk-method (as-real! this::J2SExpr) (if (eq? (j2s-vtype this) 'real) this (with-access::J2SExpr this (loc) (J2SCast 'real this)))) (define-walk-method (as-real! this::J2SBinary) (call-default-walker) (with-access::J2SBinary this (type) (set! type 'real)) this) (define-walk-method (as-real! this::J2SUnary) (call-default-walker) (with-access::J2SUnary this (type) (set! type 'real)) this) (define-walk-method (as-real! this::J2SCast) (with-access::J2SCast this (type) (set! type 'real) this)) (define-walk-method (as-real! this::J2SParen) (with-access::J2SParen this (expr type loc) (if (eq? (j2s-type expr) 'real) (begin (set! type 'real) this) (J2SCast 'real this))))
2f224e23892f7f18c6239227a43ad76589f64b3e4b22e6f74e96c21a76b965c1
google/ormolu
separation-1b-out.hs
decompressingPipe :: (PrimMonad m, MonadThrow m, MonadResource m) => CompressionMethod -> ConduitT ByteString ByteString m () decompressingPipe Store = C.awaitForever C.yield decompressingPipe Deflate = Z.decompress $ Z.WindowBits (-15) #ifdef ENABLE_BZIP2 decompressingPipe BZip2 = BZ.bunzip2 #else decompressingPipe BZip2 = throwM BZip2Unsupported #endif foo :: Int foo = undefined
null
https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/other/cpp/separation-1b-out.hs
haskell
decompressingPipe :: (PrimMonad m, MonadThrow m, MonadResource m) => CompressionMethod -> ConduitT ByteString ByteString m () decompressingPipe Store = C.awaitForever C.yield decompressingPipe Deflate = Z.decompress $ Z.WindowBits (-15) #ifdef ENABLE_BZIP2 decompressingPipe BZip2 = BZ.bunzip2 #else decompressingPipe BZip2 = throwM BZip2Unsupported #endif foo :: Int foo = undefined
b4c426eb8e4086357e974d3ecdfea0eec9f4219047a159662efb2a5686d49204
pyrmont/pondent
posting.cljs
(ns pondent.specs.posting (:require [clojure.spec.alpha :as s])) (def filename-regex #"[^/]") (def url-regex #"https?://[\w.-]+[\w./%#?&=-]+") (s/def ::content string?) (s/def ::date #(instance? goog.date.DateTime %)) (s/def ::filename (s/and string? #(re-matches filename-regex %))) (s/def ::path string?) (s/def ::promise #(instance? js/Promise %)) (s/def ::settings (s/keys :req-un [::owner ::repo ::gh-user ::gh-password ::gh-token])) (s/def ::slug string?) (s/def ::url (s/and string? #(re-matches url-regex %))) (s/fdef pondent.posting/create-file :args (s/cat :file map? :settings ::settings) :ret ::promise) (s/fdef pondent.posting/create-post :args (s/cat :post map? :settings ::settings) :ret ::promise) (s/fdef pondent.posting/file-path :args (s/cat :dir ::path :filename ::filename) :ret ::path) (s/fdef pondent.posting/format-categories :args (s/cat :categories (s/nilable string?)) :ret (s/nilable string?)) (s/fdef pondent.posting/format-body :args (s/cat :body ::content) :ret string?) (s/fdef pondent.posting/format-date :args (s/cat :date ::date) :ret string?) (s/fdef pondent.posting/format-post :args (s/cat :body ::content :date ::date :title (s/nilable string?) :categories (s/nilable string?)) :ret string?) (s/fdef pondent.posting/format-title :args (s/cat :title (s/nilable string?)) :ret (s/nilable string?)) (s/fdef pondent.posting/input-errors :args (s/keys :req-un [::content ::slug]) :ret map?) (s/fdef pondent.posting/loose-images :args (s/cat :files (s/nilable seq?) :content (s/nilable ::content) :settings :settings) :ret string?) (s/fdef pondent.posting/post-path :args (s/cat :dir ::path :date ::date :slug ::slug) :ret ::path) (s/fdef pondent.posting/success? :args (s/cat :result (s/nilable map?)) :ret boolean?) (s/fdef pondent.posting/uploaded? :args (s/cat :result (s/nilable map?)) :ret boolean?)
null
https://raw.githubusercontent.com/pyrmont/pondent/446adb8aaa62916b20fa34fb0cf5c419bb06f07c/test/pondent/specs/posting.cljs
clojure
(ns pondent.specs.posting (:require [clojure.spec.alpha :as s])) (def filename-regex #"[^/]") (def url-regex #"https?://[\w.-]+[\w./%#?&=-]+") (s/def ::content string?) (s/def ::date #(instance? goog.date.DateTime %)) (s/def ::filename (s/and string? #(re-matches filename-regex %))) (s/def ::path string?) (s/def ::promise #(instance? js/Promise %)) (s/def ::settings (s/keys :req-un [::owner ::repo ::gh-user ::gh-password ::gh-token])) (s/def ::slug string?) (s/def ::url (s/and string? #(re-matches url-regex %))) (s/fdef pondent.posting/create-file :args (s/cat :file map? :settings ::settings) :ret ::promise) (s/fdef pondent.posting/create-post :args (s/cat :post map? :settings ::settings) :ret ::promise) (s/fdef pondent.posting/file-path :args (s/cat :dir ::path :filename ::filename) :ret ::path) (s/fdef pondent.posting/format-categories :args (s/cat :categories (s/nilable string?)) :ret (s/nilable string?)) (s/fdef pondent.posting/format-body :args (s/cat :body ::content) :ret string?) (s/fdef pondent.posting/format-date :args (s/cat :date ::date) :ret string?) (s/fdef pondent.posting/format-post :args (s/cat :body ::content :date ::date :title (s/nilable string?) :categories (s/nilable string?)) :ret string?) (s/fdef pondent.posting/format-title :args (s/cat :title (s/nilable string?)) :ret (s/nilable string?)) (s/fdef pondent.posting/input-errors :args (s/keys :req-un [::content ::slug]) :ret map?) (s/fdef pondent.posting/loose-images :args (s/cat :files (s/nilable seq?) :content (s/nilable ::content) :settings :settings) :ret string?) (s/fdef pondent.posting/post-path :args (s/cat :dir ::path :date ::date :slug ::slug) :ret ::path) (s/fdef pondent.posting/success? :args (s/cat :result (s/nilable map?)) :ret boolean?) (s/fdef pondent.posting/uploaded? :args (s/cat :result (s/nilable map?)) :ret boolean?)
e2524391ab0cf033eeae098bbdb26fd25c9fe517596d5609f9e1b13ab8921209
her01n/guile-web-driver
key.scm
(define-module (web driver key)) (use-modules (ice-9 match) (srfi srfi-1)) (define-public (key->unicode-char code) (if (equal? 1 (string-length code)) code (first (find (match-lambda ((char key-code) (string-ci=? key-code code))) char-key-codes)))) ; Mappings between single unicode character and keyevent codes ; Copy Pasted from the specification page ; ttps/ (define char-key-codes ; normalized key value table '(("\uE001" "Cancel") ("\uE002" "Help") ("\uE003" "Backspace") ("\uE004" "Tab") ("\uE005" "Clear") ("\uE006" "Return") ("\uE007" "Enter") ("\uE008" "Shift") ("\uE009" "Control") ("\uE00A" "Alt") ("\uE00B" "Pause") ("\uE00C" "Escape") ("\uE00D" " ") ("\uE00E" "PageUp") ("\uE00F" "PageDown") ("\uE010" "End") ("\uE011" "Home") ("\uE012" "ArrowLeft") ("\uE013" "ArrowUp") ("\uE014" "ArrowRight") ("\uE015" "ArrowDown") ("\uE016" "Insert") ("\uE017" "Delete") ("\uE018" ";") ("\uE019" "=") ("\uE01A" "0") ("\uE01B" "1") ("\uE01C" "2") ("\uE01D" "3") ("\uE01E" "4") ("\uE01F" "5") ("\uE020" "6") ("\uE021" "7") ("\uE022" "8") ("\uE023" "9") ("\uE024" "*") ("\uE025" "+") ("\uE026" ",") ("\uE027" "-") ("\uE028" ".") ("\uE029" "/") ("\uE031" "F1") ("\uE032" "F2") ("\uE033" "F3") ("\uE034" "F4") ("\uE035" "F5") ("\uE036" "F6") ("\uE037" "F7") ("\uE038" "F8") ("\uE039" "F9") ("\uE03A" "F10") ("\uE03B" "F11") ("\uE03C" "F12") ("\uE03D" "Meta") ("\uE040" "ZenkakuHankaku") ("\uE050" "Shift") ("\uE051" "Control") ("\uE052" "Alt") ("\uE053" "Meta") ("\uE054" "PageUp") ("\uE055" "PageDown") ("\uE056" "End") ("\uE057" "Home") ("\uE058" "ArrowLeft") ("\uE059" "ArrowUp") ("\uE05A" "ArrowRight") ("\uE05B" "ArrowDown") ("\uE05C" "Insert") ("\uE05D" "Delete") ; Shifted character table ("`" "Backquote") ("\\" "Backslash") ("\uE003" "Backspace") ("[" "BracketLeft") ("]" "BracketRight") ("," "Comma") ("0" "Digit0") ("1" "Digit1") ("2" "Digit2") ("3" "Digit3") ("4" "Digit4") ("5" "Digit5") ("6" "Digit6") ("7" "Digit7") ("8" "Digit8") ("9" "Digit9") ("=" "Equal") ("<" "IntlBackslash") ("a" "KeyA") ("b" "KeyB") ("c" "KeyC") ("d" "KeyD") ("e" "KeyE") ("f" "KeyF") ("g" "KeyG") ("h" "KeyH") ("i" "KeyI") ("j" "KeyJ") ("k" "KeyK") ("l" "KeyL") ("m" "KeyM") ("n" "KeyN") ("o" "KeyO") ("p" "KeyP") ("q" "KeyQ") ("r" "KeyR") ("s" "KeyS") ("t" "KeyT") ("u" "KeyU") ("v" "KeyV") ("w" "KeyW") ("x" "KeyX") ("y" "KeyY") ("z" "KeyZ") ("-" "Minus") ("." "Period") ("'" "Quote") (";" "Semicolon") ("/" "Slash") ("\uE00A" "AltLeft") ("\uE052" "AltRight") ("\uE009" "ControlLeft") ("\uE051" "ControlRight") ("\uE006" "Enter") ("\uE03D" "OSLeft") ("\uE053" "OSRight") ("\uE008" "ShiftLeft") ("\uE050" "ShiftRight") (" " "Space") ("\uE004" "Tab") ("\uE017" "Delete") ("\uE010" "End") ("\uE002" "Help") ("\uE011" "Home") ("\uE016" "Insert") ("\uE00F" "PageDown") ("\uE00E" "PageUp") ("\uE015" "ArrowDown") ("\uE012" "ArrowLeft") ("\uE014" "ArrowRight") ("\uE013" "ArrowUp") ("\uE00C" "Escape") ("\uE031" "F1") ("\uE032" "F2") ("\uE033" "F3") ("\uE034" "F4") ("\uE035" "F5") ("\uE036" "F6") ("\uE037" "F7") ("\uE038" "F8") ("\uE039" "F9") ("\uE03A" "F10") ("\uE03B" "F11") ("\uE03C" "F12") ("\uE01A" "Numpad0") ("\uE01B" "Numpad1") ("\uE01C" "Numpad2") ("\uE01D" "Numpad3") ("\uE01E" "Numpad4") ("\uE01F" "Numpad5") ("\uE020" "Numpad6") ("\uE021" "Numpad7") ("\uE022" "Numpad8") ("\uE023" "Numpad9") ("\uE025" "NumpadAdd") ("\uE026" "NumpadComma") ("\uE028" "NumpadDecimal") ("\uE029" "NumpadDivide") ("\uE007" "NumpadEnter") ("\uE024" "NumpadMultiply") ("\uE027" "NumpadSubtract")))
null
https://raw.githubusercontent.com/her01n/guile-web-driver/792995f001b13b6f0fb3301cb8c05eb825833328/web/driver/key.scm
scheme
Mappings between single unicode character and keyevent codes Copy Pasted from the specification page ttps/ normalized key value table Shifted character table
(define-module (web driver key)) (use-modules (ice-9 match) (srfi srfi-1)) (define-public (key->unicode-char code) (if (equal? 1 (string-length code)) code (first (find (match-lambda ((char key-code) (string-ci=? key-code code))) char-key-codes)))) (define char-key-codes '(("\uE001" "Cancel") ("\uE002" "Help") ("\uE003" "Backspace") ("\uE004" "Tab") ("\uE005" "Clear") ("\uE006" "Return") ("\uE007" "Enter") ("\uE008" "Shift") ("\uE009" "Control") ("\uE00A" "Alt") ("\uE00B" "Pause") ("\uE00C" "Escape") ("\uE00D" " ") ("\uE00E" "PageUp") ("\uE00F" "PageDown") ("\uE010" "End") ("\uE011" "Home") ("\uE012" "ArrowLeft") ("\uE013" "ArrowUp") ("\uE014" "ArrowRight") ("\uE015" "ArrowDown") ("\uE016" "Insert") ("\uE017" "Delete") ("\uE018" ";") ("\uE019" "=") ("\uE01A" "0") ("\uE01B" "1") ("\uE01C" "2") ("\uE01D" "3") ("\uE01E" "4") ("\uE01F" "5") ("\uE020" "6") ("\uE021" "7") ("\uE022" "8") ("\uE023" "9") ("\uE024" "*") ("\uE025" "+") ("\uE026" ",") ("\uE027" "-") ("\uE028" ".") ("\uE029" "/") ("\uE031" "F1") ("\uE032" "F2") ("\uE033" "F3") ("\uE034" "F4") ("\uE035" "F5") ("\uE036" "F6") ("\uE037" "F7") ("\uE038" "F8") ("\uE039" "F9") ("\uE03A" "F10") ("\uE03B" "F11") ("\uE03C" "F12") ("\uE03D" "Meta") ("\uE040" "ZenkakuHankaku") ("\uE050" "Shift") ("\uE051" "Control") ("\uE052" "Alt") ("\uE053" "Meta") ("\uE054" "PageUp") ("\uE055" "PageDown") ("\uE056" "End") ("\uE057" "Home") ("\uE058" "ArrowLeft") ("\uE059" "ArrowUp") ("\uE05A" "ArrowRight") ("\uE05B" "ArrowDown") ("\uE05C" "Insert") ("\uE05D" "Delete") ("`" "Backquote") ("\\" "Backslash") ("\uE003" "Backspace") ("[" "BracketLeft") ("]" "BracketRight") ("," "Comma") ("0" "Digit0") ("1" "Digit1") ("2" "Digit2") ("3" "Digit3") ("4" "Digit4") ("5" "Digit5") ("6" "Digit6") ("7" "Digit7") ("8" "Digit8") ("9" "Digit9") ("=" "Equal") ("<" "IntlBackslash") ("a" "KeyA") ("b" "KeyB") ("c" "KeyC") ("d" "KeyD") ("e" "KeyE") ("f" "KeyF") ("g" "KeyG") ("h" "KeyH") ("i" "KeyI") ("j" "KeyJ") ("k" "KeyK") ("l" "KeyL") ("m" "KeyM") ("n" "KeyN") ("o" "KeyO") ("p" "KeyP") ("q" "KeyQ") ("r" "KeyR") ("s" "KeyS") ("t" "KeyT") ("u" "KeyU") ("v" "KeyV") ("w" "KeyW") ("x" "KeyX") ("y" "KeyY") ("z" "KeyZ") ("-" "Minus") ("." "Period") ("'" "Quote") (";" "Semicolon") ("/" "Slash") ("\uE00A" "AltLeft") ("\uE052" "AltRight") ("\uE009" "ControlLeft") ("\uE051" "ControlRight") ("\uE006" "Enter") ("\uE03D" "OSLeft") ("\uE053" "OSRight") ("\uE008" "ShiftLeft") ("\uE050" "ShiftRight") (" " "Space") ("\uE004" "Tab") ("\uE017" "Delete") ("\uE010" "End") ("\uE002" "Help") ("\uE011" "Home") ("\uE016" "Insert") ("\uE00F" "PageDown") ("\uE00E" "PageUp") ("\uE015" "ArrowDown") ("\uE012" "ArrowLeft") ("\uE014" "ArrowRight") ("\uE013" "ArrowUp") ("\uE00C" "Escape") ("\uE031" "F1") ("\uE032" "F2") ("\uE033" "F3") ("\uE034" "F4") ("\uE035" "F5") ("\uE036" "F6") ("\uE037" "F7") ("\uE038" "F8") ("\uE039" "F9") ("\uE03A" "F10") ("\uE03B" "F11") ("\uE03C" "F12") ("\uE01A" "Numpad0") ("\uE01B" "Numpad1") ("\uE01C" "Numpad2") ("\uE01D" "Numpad3") ("\uE01E" "Numpad4") ("\uE01F" "Numpad5") ("\uE020" "Numpad6") ("\uE021" "Numpad7") ("\uE022" "Numpad8") ("\uE023" "Numpad9") ("\uE025" "NumpadAdd") ("\uE026" "NumpadComma") ("\uE028" "NumpadDecimal") ("\uE029" "NumpadDivide") ("\uE007" "NumpadEnter") ("\uE024" "NumpadMultiply") ("\uE027" "NumpadSubtract")))
25855e10ecb514b6f13b57e7b13d89aaf2116eeabe4d3eefc584255d02e16e49
wies/grasshopper
logger.ml
-*- Mode : ; indent - tabs - mode : nil -*- (******************************************************************************) Copyright ( c ) 2009 , Metaweb Technologies , Inc. * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions * are met : * * Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * Redistributions in binary form must reproduce the above * copyright notice , this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution . * * THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ` ` 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 METAWEB TECHNOLOGIES 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 , * 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 . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ``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 METAWEB TECHNOLOGIES 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. ******************************************************************************) open Printf type log = { name : string; mutable level : int; } type level = NONE | FATAL | ERROR | WARN | NOTICE | INFO | DEBUG type event = string * (string * string) list type formatter = log -> level -> event -> float -> unit (******************************************************************************) (** log utilities *) let int_of_level = function | NONE -> 0 | FATAL -> 1 | ERROR -> 2 | WARN -> 3 | NOTICE -> 4 | INFO -> 5 | DEBUG -> 6 let level_of_int = function | 0 -> NONE | 1 -> FATAL | 2 -> ERROR | 3 -> WARN | 4 -> NOTICE | 5 -> INFO | 6 -> DEBUG | i -> failwith ("invalid level: " ^ string_of_int i) let name_of_level = function | NONE -> "NONE" | FATAL -> "FATAL" | ERROR -> "ERROR" | WARN -> "WARN" | NOTICE -> "NOTICE" | INFO -> "INFO" | DEBUG -> "DEBUG" let level_of_name = function | "NONE" -> NONE | "FATAL" -> FATAL | "ERROR" -> ERROR | "WARN" -> WARN | "NOTICE" -> NOTICE | "INFO" -> INFO | "DEBUG" -> DEBUG | n -> failwith ("invalid level: " ^ n) let format_timestamp out ts = let tm = Unix.gmtime ts in let ms, _ = modf ts in fprintf out "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ" (1900 + tm.Unix.tm_year) (1 + tm.Unix.tm_mon) (tm.Unix.tm_mday) (tm.Unix.tm_hour) (tm.Unix.tm_min) (tm.Unix.tm_sec) (int_of_float (100000. *. ms)) (******************************************************************************) (** log modules *) let logs = Hashtbl.create 16 let default_level = ref (int_of_level INFO) let make_log name = try Hashtbl.find logs name with Not_found -> let lm = { name = name; level = !default_level } in Hashtbl.replace logs name lm; lm let log_enable lm lev = lm.level <- int_of_level lev let log_enabled lm lev = let lev_no = int_of_level lev in lev_no <= lm.level let log_name lm = lm.name let log_level lm = level_of_int lm.level (******************************************************************************) (** log formatters *) let depth = ref 0 let formatters : (string * formatter) list ref = ref [] let register_formatter name f = formatters := (name, f) :: !formatters let unregister_formatter name = formatters := List.remove_assoc name !formatters let rec format_kvl oc = function | [] -> () | (k, v)::rest -> fprintf oc "\t%s:%s" k v; format_kvl oc rest let make_std_formatter oc lm lev (event_name, event_args) timestamp = fprintf oc "D:%a\tE:%s.%s\tL:%s%a\n%!" (*D:*) format_timestamp timestamp (*E:*) lm.name event_name (*L:*) (name_of_level lev) format_kvl event_args let stderr_formatter = make_std_formatter stderr let null_formatter lm lev event timestamp = () let format_indent oc depth = for i = 0 to depth do fprintf oc "| " done let make_dbg_formatter oc lm lev (event_name, event_args) timestamp = let indent = try int_of_string (List.assoc "I" event_args) with _ -> 0 in let args = List.remove_assoc "I" event_args in fprintf oc "### %a%s.%s %a [%s]\n%!" format_indent indent (log_name lm) event_name format_kvl args (name_of_level lev) let dbg_formatter lm lev ep ts = make_dbg_formatter stderr lm lev ep ts (******************************************************************************) (** log events *) let log lm lev event_fun = if log_enabled lm lev then let time = Unix.gettimeofday () in let event_name, event_args = event_fun () in let event = event_name, ("I", string_of_int !depth) :: event_args in List.iter (fun (name, fmt) -> fmt lm lev event time) !formatters let with_log lm lev event_fun ?result body = if log_enabled lm lev then begin try log lm lev event_fun; incr depth; let rv = body () in decr depth; log lm lev (fun () -> let event_name, event_args = event_fun () in let result_str = match result with | Some f -> f rv | None -> "-" in event_name, ("RESULT", result_str) ::event_args); rv with exn -> decr depth; log lm lev (fun () -> let event_name, event_args = event_fun () in event_name, ("EXN", Printexc.to_string exn) :: event_args); raise exn end else body () (******************************************************************************) (** logger initialization *) let init name_level_list formatter = List.iter (fun (name, level) -> let lm = make_log name in log_enable lm level) name_level_list; register_formatter "default" formatter let init_from_string name_level_string formatter = let init_key_value ss = try let name_ss, level_ss = Util.splitl (fun c -> c <> ':') ss in let name = Util.to_string name_ss in let level = level_of_name (Util.to_string level_ss) in let lm = make_log name in log_enable lm level with Not_found -> try let level = level_of_name (Util.to_string ss) in default_level := int_of_level level; Hashtbl.iter (fun name lm -> log_enable lm level) logs with Failure _ -> failwith ("invalid log initialization: " ^ Util.to_string ss) in List.iter init_key_value (Util.split_on_comma (Util.of_string name_level_string) ); register_formatter "default" formatter (******************************************************************************) let test () = let lm = make_log "test" in let direct () = log lm NOTICE (fun () -> "hello", []); log lm DEBUG (fun () -> "debug msg1", []); log lm ERROR (fun () -> "error msg1", []); log lm ERROR (fun () -> "ok", ["ARG1", string_of_int 234]); in let rec run () = direct (); Unix.sleep 3; run () in run () (******************************************************************************)
null
https://raw.githubusercontent.com/wies/grasshopper/108473b0a678f0d93fffec6da2ad6bcdce5bddb9/src/util/logger.ml
ocaml
**************************************************************************** **************************************************************************** * log utilities **************************************************************************** * log modules **************************************************************************** * log formatters D: E: L: **************************************************************************** * log events **************************************************************************** * logger initialization **************************************************************************** ****************************************************************************
-*- Mode : ; indent - tabs - mode : nil -*- Copyright ( c ) 2009 , Metaweb Technologies , Inc. * All rights reserved . * * Redistribution and use in source and binary forms , with or without * modification , are permitted provided that the following conditions * are met : * * Redistributions of source code must retain the above copyright * notice , this list of conditions and the following disclaimer . * * Redistributions in binary form must reproduce the above * copyright notice , this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution . * * THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ` ` 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 METAWEB TECHNOLOGIES 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 , * 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 . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY METAWEB TECHNOLOGIES ``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 METAWEB TECHNOLOGIES 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. ******************************************************************************) open Printf type log = { name : string; mutable level : int; } type level = NONE | FATAL | ERROR | WARN | NOTICE | INFO | DEBUG type event = string * (string * string) list type formatter = log -> level -> event -> float -> unit let int_of_level = function | NONE -> 0 | FATAL -> 1 | ERROR -> 2 | WARN -> 3 | NOTICE -> 4 | INFO -> 5 | DEBUG -> 6 let level_of_int = function | 0 -> NONE | 1 -> FATAL | 2 -> ERROR | 3 -> WARN | 4 -> NOTICE | 5 -> INFO | 6 -> DEBUG | i -> failwith ("invalid level: " ^ string_of_int i) let name_of_level = function | NONE -> "NONE" | FATAL -> "FATAL" | ERROR -> "ERROR" | WARN -> "WARN" | NOTICE -> "NOTICE" | INFO -> "INFO" | DEBUG -> "DEBUG" let level_of_name = function | "NONE" -> NONE | "FATAL" -> FATAL | "ERROR" -> ERROR | "WARN" -> WARN | "NOTICE" -> NOTICE | "INFO" -> INFO | "DEBUG" -> DEBUG | n -> failwith ("invalid level: " ^ n) let format_timestamp out ts = let tm = Unix.gmtime ts in let ms, _ = modf ts in fprintf out "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ" (1900 + tm.Unix.tm_year) (1 + tm.Unix.tm_mon) (tm.Unix.tm_mday) (tm.Unix.tm_hour) (tm.Unix.tm_min) (tm.Unix.tm_sec) (int_of_float (100000. *. ms)) let logs = Hashtbl.create 16 let default_level = ref (int_of_level INFO) let make_log name = try Hashtbl.find logs name with Not_found -> let lm = { name = name; level = !default_level } in Hashtbl.replace logs name lm; lm let log_enable lm lev = lm.level <- int_of_level lev let log_enabled lm lev = let lev_no = int_of_level lev in lev_no <= lm.level let log_name lm = lm.name let log_level lm = level_of_int lm.level let depth = ref 0 let formatters : (string * formatter) list ref = ref [] let register_formatter name f = formatters := (name, f) :: !formatters let unregister_formatter name = formatters := List.remove_assoc name !formatters let rec format_kvl oc = function | [] -> () | (k, v)::rest -> fprintf oc "\t%s:%s" k v; format_kvl oc rest let make_std_formatter oc lm lev (event_name, event_args) timestamp = fprintf oc "D:%a\tE:%s.%s\tL:%s%a\n%!" format_kvl event_args let stderr_formatter = make_std_formatter stderr let null_formatter lm lev event timestamp = () let format_indent oc depth = for i = 0 to depth do fprintf oc "| " done let make_dbg_formatter oc lm lev (event_name, event_args) timestamp = let indent = try int_of_string (List.assoc "I" event_args) with _ -> 0 in let args = List.remove_assoc "I" event_args in fprintf oc "### %a%s.%s %a [%s]\n%!" format_indent indent (log_name lm) event_name format_kvl args (name_of_level lev) let dbg_formatter lm lev ep ts = make_dbg_formatter stderr lm lev ep ts let log lm lev event_fun = if log_enabled lm lev then let time = Unix.gettimeofday () in let event_name, event_args = event_fun () in let event = event_name, ("I", string_of_int !depth) :: event_args in List.iter (fun (name, fmt) -> fmt lm lev event time) !formatters let with_log lm lev event_fun ?result body = if log_enabled lm lev then begin try log lm lev event_fun; incr depth; let rv = body () in decr depth; log lm lev (fun () -> let event_name, event_args = event_fun () in let result_str = match result with | Some f -> f rv | None -> "-" in event_name, ("RESULT", result_str) ::event_args); rv with exn -> decr depth; log lm lev (fun () -> let event_name, event_args = event_fun () in event_name, ("EXN", Printexc.to_string exn) :: event_args); raise exn end else body () let init name_level_list formatter = List.iter (fun (name, level) -> let lm = make_log name in log_enable lm level) name_level_list; register_formatter "default" formatter let init_from_string name_level_string formatter = let init_key_value ss = try let name_ss, level_ss = Util.splitl (fun c -> c <> ':') ss in let name = Util.to_string name_ss in let level = level_of_name (Util.to_string level_ss) in let lm = make_log name in log_enable lm level with Not_found -> try let level = level_of_name (Util.to_string ss) in default_level := int_of_level level; Hashtbl.iter (fun name lm -> log_enable lm level) logs with Failure _ -> failwith ("invalid log initialization: " ^ Util.to_string ss) in List.iter init_key_value (Util.split_on_comma (Util.of_string name_level_string) ); register_formatter "default" formatter let test () = let lm = make_log "test" in let direct () = log lm NOTICE (fun () -> "hello", []); log lm DEBUG (fun () -> "debug msg1", []); log lm ERROR (fun () -> "error msg1", []); log lm ERROR (fun () -> "ok", ["ARG1", string_of_int 234]); in let rec run () = direct (); Unix.sleep 3; run () in run ()
eeb7d942d846509cf4e9e28eaf8825bfdfa96de397c492e126ce1e071c2ec371
diku-dk/futhark
SOAC.hs
# LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # -- | Definition of /Second-Order Array Combinators/ (SOACs), which are -- the main form of parallelism in the early stages of the compiler. module Futhark.IR.SOACS.SOAC ( SOAC (..), ScremaForm (..), HistOp (..), Scan (..), scanResults, singleScan, Reduce (..), redResults, singleReduce, -- * Utility scremaType, soacType, typeCheckSOAC, mkIdentityLambda, isIdentityLambda, nilFn, scanomapSOAC, redomapSOAC, scanSOAC, reduceSOAC, mapSOAC, isScanomapSOAC, isRedomapSOAC, isScanSOAC, isReduceSOAC, isMapSOAC, scremaLambda, ppScrema, ppHist, ppStream, ppScatter, groupScatterResults, groupScatterResults', splitScatterResults, -- * Generic traversal SOACMapper (..), identitySOACMapper, mapSOACM, traverseSOACStms, ) where import Control.Category import Control.Monad.Identity import Control.Monad.State.Strict import Control.Monad.Writer import Data.Function ((&)) import Data.List (intersperse) import Data.Map.Strict qualified as M import Data.Maybe import Futhark.Analysis.Alias qualified as Alias import Futhark.Analysis.Metrics import Futhark.Analysis.PrimExp.Convert import Futhark.Analysis.SymbolTable qualified as ST import Futhark.Construct import Futhark.IR import Futhark.IR.Aliases (Aliases, CanBeAliased (..)) import Futhark.IR.Prop.Aliases import Futhark.IR.TypeCheck qualified as TC import Futhark.Optimise.Simplify.Rep import Futhark.Transform.Rename import Futhark.Transform.Substitute import Futhark.Util (chunks, maybeNth) import Futhark.Util.Pretty (Doc, align, comma, commasep, docText, parens, ppTuple', pretty, (<+>), (</>)) import Futhark.Util.Pretty qualified as PP import Prelude hiding (id, (.)) | A second - order array combinator ( SOAC ) . data SOAC rep = Stream SubExp [VName] [SubExp] (Lambda rep) | @Scatter < length > < inputs > < lambda > < outputs>@ -- -- Scatter maps values from a set of input arrays to indices and values of a -- set of output arrays. It is able to write multiple values to multiple -- outputs each of which may have multiple dimensions. -- -- <inputs> is a list of input arrays, all having size <length>, elements of -- which are applied to the <lambda> function. For instance, if there are two arrays , < lambda > will get two values as input , one from each array . -- -- <outputs> specifies the result of the <lambda> and which arrays to write -- to. Each element of the list consists of a <VName> specifying which array -- to scatter to, a <Shape> describing the shape of that array, and an <Int> -- describing how many elements should be written to that array for each -- invocation of the <lambda>. -- -- <lambda> is a function that takes inputs from <inputs> and returns values -- according to the output-specification in <outputs>. It returns values in -- the following manner: -- [ , index_1 , ... , index_n , value_0 , value_1 , ... , value_m ] -- -- For each output in <outputs>, <lambda> returns <i> * <j> index values and -- <j> output values, where <i> is the number of dimensions (rank) of the -- given output, and <j> is the number of output values written to the given -- output. -- -- For example, given the following output specification: -- [ ( [ x1 , y1 , z1 ] , 2 , arr1 ) , ( [ x2 , y2 ] , 1 , arr2 ) ] -- < lambda > will produce 6 ( 3 * 2 ) index values and 2 output values for < arr1 > , and 2 ( 2 * 1 ) index values and 1 output value for arr2 . Additionally , the results are grouped , so the first 6 index values will correspond to the first two output values , and so on . For this example , < lambda > should return a total of 11 values , 8 index values and 3 output values . See also ' splitScatterResults ' . Scatter SubExp [VName] (Lambda rep) [(Shape, Int, VName)] | -- | @Hist <length> <input arrays> <dest-arrays-and-ops> <bucket fun>@ -- -- The final lambda produces indexes and values for the 'HistOp's. Hist SubExp [VName] [HistOp rep] (Lambda rep) | -- FIXME: this should not be here JVP (Lambda rep) [SubExp] [SubExp] | -- FIXME: this should not be here VJP (Lambda rep) [SubExp] [SubExp] | A combination of scan , reduction , and map . The first -- t'SubExp' is the size of the input arrays. Screma SubExp [VName] (ScremaForm rep) deriving (Eq, Ord, Show) -- | Information about computing a single histogram. data HistOp rep = HistOp { histShape :: Shape, -- | Race factor @RF@ means that only @1/RF@ -- bins are used. histRaceFactor :: SubExp, histDest :: [VName], histNeutral :: [SubExp], histOp :: Lambda rep } deriving (Eq, Ord, Show) | The essential parts of a ' Screma ' factored out ( everything -- except the input arrays). data ScremaForm rep = ScremaForm [Scan rep] [Reduce rep] (Lambda rep) deriving (Eq, Ord, Show) singleBinOp :: Buildable rep => [Lambda rep] -> Lambda rep singleBinOp lams = Lambda { lambdaParams = concatMap xParams lams ++ concatMap yParams lams, lambdaReturnType = concatMap lambdaReturnType lams, lambdaBody = mkBody (mconcat (map (bodyStms . lambdaBody) lams)) (concatMap (bodyResult . lambdaBody) lams) } where xParams lam = take (length (lambdaReturnType lam)) (lambdaParams lam) yParams lam = drop (length (lambdaReturnType lam)) (lambdaParams lam) -- | How to compute a single scan result. data Scan rep = Scan { scanLambda :: Lambda rep, scanNeutral :: [SubExp] } deriving (Eq, Ord, Show) -- | How many reduction results are produced by these 'Scan's? scanResults :: [Scan rep] -> Int scanResults = sum . map (length . scanNeutral) -- | Combine multiple scan operators to a single operator. singleScan :: Buildable rep => [Scan rep] -> Scan rep singleScan scans = let scan_nes = concatMap scanNeutral scans scan_lam = singleBinOp $ map scanLambda scans in Scan scan_lam scan_nes -- | How to compute a single reduction result. data Reduce rep = Reduce { redComm :: Commutativity, redLambda :: Lambda rep, redNeutral :: [SubExp] } deriving (Eq, Ord, Show) -- | How many reduction results are produced by these 'Reduce's? redResults :: [Reduce rep] -> Int redResults = sum . map (length . redNeutral) -- | Combine multiple reduction operators to a single operator. singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep singleReduce reds = let red_nes = concatMap redNeutral reds red_lam = singleBinOp $ map redLambda reds in Reduce (mconcat (map redComm reds)) red_lam red_nes | The types produced by a single ' Screma ' , given the size of the -- input array. scremaType :: SubExp -> ScremaForm rep -> [Type] scremaType w (ScremaForm scans reds map_lam) = scan_tps ++ red_tps ++ map (`arrayOfRow` w) map_tps where scan_tps = map (`arrayOfRow` w) $ concatMap (lambdaReturnType . scanLambda) scans red_tps = concatMap (lambdaReturnType . redLambda) reds map_tps = drop (length scan_tps + length red_tps) $ lambdaReturnType map_lam -- | Construct a lambda that takes parameters of the given types and -- simply returns them unchanged. mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) mkIdentityLambda ts = do params <- mapM (newParam "x") ts pure Lambda { lambdaParams = params, lambdaBody = mkBody mempty $ varsRes $ map paramName params, lambdaReturnType = ts } -- | Is the given lambda an identity lambda? isIdentityLambda :: Lambda rep -> Bool isIdentityLambda lam = map resSubExp (bodyResult (lambdaBody lam)) == map (Var . paramName) (lambdaParams lam) -- | A lambda with no parameters that returns no values. nilFn :: Buildable rep => Lambda rep nilFn = Lambda mempty (mkBody mempty mempty) mempty | Construct a Screma with possibly multiple scans , and -- the given map function. scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep scanomapSOAC scans = ScremaForm scans [] | Construct a Screma with possibly multiple reductions , and -- the given map function. redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep redomapSOAC = ScremaForm [] | Construct a Screma with possibly multiple scans , and identity map -- function. scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) scanSOAC scans = scanomapSOAC scans <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . scanLambda) scans | Construct a Screma with possibly multiple reductions , and -- identity map function. reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) reduceSOAC reds = redomapSOAC reds <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . redLambda) reds | Construct a Screma corresponding to a map . mapSOAC :: Lambda rep -> ScremaForm rep mapSOAC = ScremaForm [] [] | Does this Screma correspond to a scan - map composition ? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) isScanomapSOAC (ScremaForm scans reds map_lam) = do guard $ null reds guard $ not $ null scans pure (scans, map_lam) | Does this Screma correspond to pure scan ? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] isScanSOAC form = do (scans, map_lam) <- isScanomapSOAC form guard $ isIdentityLambda map_lam pure scans | Does this Screma correspond to a reduce - map composition ? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) isRedomapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ not $ null reds pure (reds, map_lam) | Does this Screma correspond to a pure reduce ? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] isReduceSOAC form = do (reds, map_lam) <- isRedomapSOAC form guard $ isIdentityLambda map_lam pure reds | Does this Screma correspond to a simple map , without any -- reduction or scan results? isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) isMapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ null reds pure map_lam | Return the " main " lambda of the Screma . For a map , this is -- equivalent to 'isMapSOAC'. Note that the meaning of the return value of this lambda depends crucially on exactly which Screma this -- is. The parameters will correspond exactly to elements of the -- input arrays, however. scremaLambda :: ScremaForm rep -> Lambda rep scremaLambda (ScremaForm _ _ map_lam) = map_lam -- | @groupScatterResults <output specification> <results>@ -- Groups the index values and result values of < results > according to the -- <output specification>. -- -- This function is used for extracting and grouping the results of a scatter . In the SOAC representation , the lambda inside a ' Scatter ' returns all indices and values as one big list . This function groups each value with its corresponding indices ( as determined by the t'Shape ' of the output array ) . -- -- The elements of the resulting list correspond to the shape and name of the -- output parameters, in addition to a list of values written to that output -- parameter, along with the array indices marking where to write them to. -- -- See 'Scatter' for more information. groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] groupScatterResults output_spec results = let (shapes, ns, arrays) = unzip3 output_spec in groupScatterResults' output_spec results & chunks ns & zip3 shapes arrays -- | @groupScatterResults' <output specification> <results>@ -- Groups the index values and result values of < results > according to the output specification . This is the simpler version of @groupScatterResults@ , -- which doesn't return any information about shapes or output arrays. -- -- See 'groupScatterResults' for more information, groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] groupScatterResults' output_spec results = let (indices, values) = splitScatterResults output_spec results (shapes, ns, _) = unzip3 output_spec chunk_sizes = concat $ zipWith (\shp n -> replicate n $ length shp) shapes ns in zip (chunks chunk_sizes indices) values -- | @splitScatterResults <output specification> <results>@ -- -- Splits the results array into indices and values according to the output -- specification. -- -- See 'groupScatterResults' for more information. splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) splitScatterResults output_spec results = let (shapes, ns, _) = unzip3 output_spec num_indices = sum $ zipWith (*) ns $ map length shapes in splitAt num_indices results | Like ' Mapper ' , but just for ' SOAC 's . data SOACMapper frep trep m = SOACMapper { mapOnSOACSubExp :: SubExp -> m SubExp, mapOnSOACLambda :: Lambda frep -> m (Lambda trep), mapOnSOACVName :: VName -> m VName } | A mapper that simply returns the SOAC verbatim . identitySOACMapper :: Monad m => SOACMapper rep rep m identitySOACMapper = SOACMapper { mapOnSOACSubExp = pure, mapOnSOACLambda = pure, mapOnSOACVName = pure } -- | Map a monadic action across the immediate children of a SOAC . The mapping does not descend recursively into subexpressions -- and is done left-to-right. mapSOACM :: Monad m => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) mapSOACM tv (JVP lam args vec) = JVP <$> mapOnSOACLambda tv lam <*> mapM (mapOnSOACSubExp tv) args <*> mapM (mapOnSOACSubExp tv) vec mapSOACM tv (VJP lam args vec) = VJP <$> mapOnSOACLambda tv lam <*> mapM (mapOnSOACSubExp tv) args <*> mapM (mapOnSOACSubExp tv) vec mapSOACM tv (Stream size arrs accs lam) = Stream <$> mapOnSOACSubExp tv size <*> mapM (mapOnSOACVName tv) arrs <*> mapM (mapOnSOACSubExp tv) accs <*> mapOnSOACLambda tv lam mapSOACM tv (Scatter w ivs lam as) = Scatter <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) ivs <*> mapOnSOACLambda tv lam <*> mapM ( \(aw, an, a) -> (,,) <$> mapM (mapOnSOACSubExp tv) aw <*> pure an <*> mapOnSOACVName tv a ) as mapSOACM tv (Hist w arrs ops bucket_fun) = Hist <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> mapM ( \(HistOp shape rf op_arrs nes op) -> HistOp <$> mapM (mapOnSOACSubExp tv) shape <*> mapOnSOACSubExp tv rf <*> mapM (mapOnSOACVName tv) op_arrs <*> mapM (mapOnSOACSubExp tv) nes <*> mapOnSOACLambda tv op ) ops <*> mapOnSOACLambda tv bucket_fun mapSOACM tv (Screma w arrs (ScremaForm scans reds map_lam)) = Screma <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> ( ScremaForm <$> forM scans ( \(Scan red_lam red_nes) -> Scan <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> forM reds ( \(Reduce comm red_lam red_nes) -> Reduce comm <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> mapOnSOACLambda tv map_lam ) -- | A helper for defining 'TraverseOpStms'. traverseSOACStms :: Monad m => OpStmsTraverser m (SOAC rep) rep traverseSOACStms f = mapSOACM mapper where mapper = identitySOACMapper {mapOnSOACLambda = traverseLambdaStms f} instance ASTRep rep => FreeIn (Scan rep) where freeIn' (Scan lam ne) = freeIn' lam <> freeIn' ne instance ASTRep rep => FreeIn (Reduce rep) where freeIn' (Reduce _ lam ne) = freeIn' lam <> freeIn' ne instance ASTRep rep => FreeIn (ScremaForm rep) where freeIn' (ScremaForm scans reds lam) = freeIn' scans <> freeIn' reds <> freeIn' lam instance ASTRep rep => FreeIn (HistOp rep) where freeIn' (HistOp w rf dests nes lam) = freeIn' w <> freeIn' rf <> freeIn' dests <> freeIn' nes <> freeIn' lam instance ASTRep rep => FreeIn (SOAC rep) where freeIn' = flip execState mempty . mapSOACM free where walk f x = modify (<> f x) >> pure x free = SOACMapper { mapOnSOACSubExp = walk freeIn', mapOnSOACLambda = walk freeIn', mapOnSOACVName = walk freeIn' } instance ASTRep rep => Substitute (SOAC rep) where substituteNames subst = runIdentity . mapSOACM substitute where substitute = SOACMapper { mapOnSOACSubExp = pure . substituteNames subst, mapOnSOACLambda = pure . substituteNames subst, mapOnSOACVName = pure . substituteNames subst } instance ASTRep rep => Rename (SOAC rep) where rename = mapSOACM renamer where renamer = SOACMapper rename rename rename | The type of a SOAC . soacType :: Typed (LParamInfo rep) => SOAC rep -> [Type] soacType (JVP lam _ _) = lambdaReturnType lam ++ lambdaReturnType lam soacType (VJP lam _ _) = lambdaReturnType lam ++ map paramType (lambdaParams lam) soacType (Stream outersize _ accs lam) = map (substNamesInType substs) rtp where nms = map paramName $ take (1 + length accs) params substs = M.fromList $ zip nms (outersize : accs) Lambda params _ rtp = lam soacType (Scatter _w _ivs lam dests) = zipWith arrayOfShape val_ts ws where indexes = sum $ zipWith (*) ns $ map length ws val_ts = drop indexes $ lambdaReturnType lam (ws, ns, _) = unzip3 dests soacType (Hist _ _ ops _bucket_fun) = do op <- ops map (`arrayOfShape` histShape op) (lambdaReturnType $ histOp op) soacType (Screma w _arrs form) = scremaType w form instance ASTRep rep => TypedOp (SOAC rep) where opType = pure . staticShapes . soacType instance Aliased rep => AliasedOp (SOAC rep) where opAliases = map (const mempty) . soacType consumedInOp JVP {} = mempty consumedInOp VJP {} = mempty -- Only map functions can consume anything. The operands to scan -- and reduce functions are always considered "fresh". consumedInOp (Screma _ arrs (ScremaForm _ _ map_lam)) = mapNames consumedArray $ consumedByLambda map_lam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName $ lambdaParams map_lam) arrs consumedInOp (Stream _ arrs accs lam) = namesFromList $ subExpVars $ map consumedArray $ namesToList $ consumedByLambda lam where consumedArray v = fromMaybe (Var v) $ lookup v paramsToInput -- Drop the chunk parameter, which cannot alias anything. paramsToInput = zip (map paramName $ drop 1 $ lambdaParams lam) (accs ++ map Var arrs) consumedInOp (Scatter _ _ _ as) = namesFromList $ map (\(_, _, a) -> a) as consumedInOp (Hist _ _ ops _) = namesFromList $ concatMap histDest ops mapHistOp :: (Lambda frep -> Lambda trep) -> HistOp frep -> HistOp trep mapHistOp f (HistOp w rf dests nes lam) = HistOp w rf dests nes $ f lam instance CanBeAliased SOAC where addOpAliases aliases (JVP lam args vec) = JVP (Alias.analyseLambda aliases lam) args vec addOpAliases aliases (VJP lam args vec) = VJP (Alias.analyseLambda aliases lam) args vec addOpAliases aliases (Stream size arr accs lam) = Stream size arr accs $ Alias.analyseLambda aliases lam addOpAliases aliases (Scatter len arrs lam dests) = Scatter len arrs (Alias.analyseLambda aliases lam) dests addOpAliases aliases (Hist w arrs ops bucket_fun) = Hist w arrs (map (mapHistOp (Alias.analyseLambda aliases)) ops) (Alias.analyseLambda aliases bucket_fun) addOpAliases aliases (Screma w arrs (ScremaForm scans reds map_lam)) = Screma w arrs $ ScremaForm (map onScan scans) (map onRed reds) (Alias.analyseLambda aliases map_lam) where onRed red = red {redLambda = Alias.analyseLambda aliases $ redLambda red} onScan scan = scan {scanLambda = Alias.analyseLambda aliases $ scanLambda scan} instance ASTRep rep => IsOp (SOAC rep) where safeOp _ = False cheapOp _ = False substNamesInType :: M.Map VName SubExp -> Type -> Type substNamesInType _ t@Prim {} = t substNamesInType _ t@Acc {} = t substNamesInType _ (Mem space) = Mem space substNamesInType subs (Array btp shp u) = let shp' = Shape $ map (substNamesInSubExp subs) (shapeDims shp) in Array btp shp' u substNamesInSubExp :: M.Map VName SubExp -> SubExp -> SubExp substNamesInSubExp _ e@(Constant _) = e substNamesInSubExp subs (Var idd) = M.findWithDefault (Var idd) idd subs instance CanBeWise SOAC where addOpWisdom = runIdentity . mapSOACM (SOACMapper pure (pure . informLambda) pure) instance RepTypes rep => ST.IndexOp (SOAC rep) where indexOp vtable k soac [i] = do (lam, se, arr_params, arrs) <- lambdaAndSubExp soac let arr_indexes = M.fromList $ catMaybes $ zipWith arrIndex arr_params arrs arr_indexes' = foldl expandPrimExpTable arr_indexes $ bodyStms $ lambdaBody lam case se of SubExpRes _ (Var v) -> uncurry (flip ST.Indexed) <$> M.lookup v arr_indexes' _ -> Nothing where lambdaAndSubExp (Screma _ arrs (ScremaForm scans reds map_lam)) = nthMapOut (scanResults scans + redResults reds) map_lam arrs lambdaAndSubExp _ = Nothing nthMapOut num_accs lam arrs = do se <- maybeNth (num_accs + k) $ bodyResult $ lambdaBody lam pure (lam, se, drop num_accs $ lambdaParams lam, arrs) arrIndex p arr = do ST.Indexed cs pe <- ST.index' arr [i] vtable pure (paramName p, (pe, cs)) expandPrimExpTable table stm | [v] <- patNames $ stmPat stm, Just (pe, cs) <- runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm, all (`ST.elem` vtable) (unCerts $ stmCerts stm) = M.insert v (pe, stmCerts stm <> cs) table | otherwise = table asPrimExp table v | Just (e, cs) <- M.lookup v table = tell cs >> pure e | Just (Prim pt) <- ST.lookupType v vtable = pure $ LeafExp v pt | otherwise = lift Nothing indexOp _ _ _ _ = Nothing | Type - check a SOAC . typeCheckSOAC :: TC.Checkable rep => SOAC (Aliases rep) -> TC.TypeM rep () typeCheckSOAC (VJP lam args vec) = do args' <- mapM TC.checkArg args TC.checkLambda lam $ map TC.noArgAliases args' vec_ts <- mapM TC.checkSubExp vec unless (vec_ts == lambdaReturnType lam) $ TC.bad . TC.TypeError . docText $ "Return type" </> PP.indent 2 (pretty (lambdaReturnType lam)) </> "does not match type of seed vector" </> PP.indent 2 (pretty vec_ts) typeCheckSOAC (JVP lam args vec) = do args' <- mapM TC.checkArg args TC.checkLambda lam $ map TC.noArgAliases args' vec_ts <- mapM TC.checkSubExp vec unless (vec_ts == map TC.argType args') $ TC.bad . TC.TypeError . docText $ "Parameter type" </> PP.indent 2 (pretty $ map TC.argType args') </> "does not match type of seed vector" </> PP.indent 2 (pretty vec_ts) typeCheckSOAC (Stream size arrexps accexps lam) = do TC.require [Prim int64] size accargs <- mapM TC.checkArg accexps arrargs <- mapM lookupType arrexps _ <- TC.checkSOACArrayArgs size arrexps let chunk = head $ lambdaParams lam let asArg t = (t, mempty) inttp = Prim int64 lamarrs' = map (`setOuterSize` Var (paramName chunk)) arrargs let acc_len = length accexps let lamrtp = take acc_len $ lambdaReturnType lam unless (map TC.argType accargs == lamrtp) $ TC.bad . TC.TypeError $ "Stream with inconsistent accumulator type in lambda." -- just get the dflow of lambda on the fakearg, which does not alias -- arr, so we can later check that aliases of arr are not used inside lam. let fake_lamarrs' = map asArg lamarrs' TC.checkLambda lam $ asArg inttp : accargs ++ fake_lamarrs' typeCheckSOAC (Scatter w arrs lam as) = do -- Requirements: -- 0 . @lambdaReturnType@ of must be a list -- [index types..., value types, ...]. -- -- 1. The number of index types and value types must be equal to the number of return values from @lam@. -- -- 2. Each index type must have the type i64. -- -- 3. Each array in @as@ and the value types must have the same type -- -- 4. Each array in @as@ is consumed. This is not really a check, but more -- of a requirement, so that e.g. the source is not hoisted out of a -- loop, which will mean it cannot be consumed. -- -- 5. Each of arrs must be an array matching a corresponding lambda -- parameters. -- -- Code: First check the input size . TC.require [Prim int64] w -- 0. let (as_ws, as_ns, _as_vs) = unzip3 as indexes = sum $ zipWith (*) as_ns $ map length as_ws rts = lambdaReturnType lam rtsI = take indexes rts rtsV = drop indexes rts 1 . unless (length rts == sum as_ns + sum (zipWith (*) as_ns $ map length as_ws)) $ TC.bad $ TC.TypeError "Scatter: number of index types, value types and array outputs do not match." 2 . forM_ rtsI $ \rtI -> unless (Prim int64 == rtI) $ TC.bad $ TC.TypeError "Scatter: Index return type must be i64." forM_ (zip (chunks as_ns rtsV) as) $ \(rtVs, (aw, _, a)) -> do -- All lengths must have type i64. mapM_ (TC.require [Prim int64]) aw 3 . forM_ rtVs $ \rtV -> TC.requireI [arrayOfShape rtV aw] a 4 . TC.consume =<< TC.lookupAliases a 5 . arrargs <- TC.checkSOACArrayArgs w arrs TC.checkLambda lam arrargs typeCheckSOAC (Hist w arrs ops bucket_fun) = do TC.require [Prim int64] w -- Check the operators. forM_ ops $ \(HistOp dest_shape rf dests nes op) -> do nes' <- mapM TC.checkArg nes mapM_ (TC.require [Prim int64]) dest_shape TC.require [Prim int64] rf -- Operator type must match the type of neutral elements. TC.checkLambda op $ map TC.noArgAliases $ nes' ++ nes' let nes_t = map TC.argType nes' unless (nes_t == lambdaReturnType op) $ TC.bad . TC.TypeError $ "Operator has return type " <> prettyTuple (lambdaReturnType op) <> " but neutral element has type " <> prettyTuple nes_t -- Arrays must have proper type. forM_ (zip nes_t dests) $ \(t, dest) -> do TC.requireI [t `arrayOfShape` dest_shape] dest TC.consume =<< TC.lookupAliases dest -- Types of input arrays must equal parameter types for bucket function. img' <- TC.checkSOACArrayArgs w arrs TC.checkLambda bucket_fun img' -- Return type of bucket function must be an index for each -- operation followed by the values to write. nes_ts <- concat <$> mapM (mapM subExpType . histNeutral) ops let bucket_ret_t = concatMap ((`replicate` Prim int64) . shapeRank . histShape) ops ++ nes_ts unless (bucket_ret_t == lambdaReturnType bucket_fun) $ TC.bad . TC.TypeError $ "Bucket function has return type " <> prettyTuple (lambdaReturnType bucket_fun) <> " but should have type " <> prettyTuple bucket_ret_t typeCheckSOAC (Screma w arrs (ScremaForm scans reds map_lam)) = do TC.require [Prim int64] w arrs' <- TC.checkSOACArrayArgs w arrs TC.checkLambda map_lam arrs' scan_nes' <- fmap concat $ forM scans $ \(Scan scan_lam scan_nes) -> do scan_nes' <- mapM TC.checkArg scan_nes let scan_t = map TC.argType scan_nes' TC.checkLambda scan_lam $ map TC.noArgAliases $ scan_nes' ++ scan_nes' unless (scan_t == lambdaReturnType scan_lam) $ TC.bad . TC.TypeError $ "Scan function returns type " <> prettyTuple (lambdaReturnType scan_lam) <> " but neutral element has type " <> prettyTuple scan_t pure scan_nes' red_nes' <- fmap concat $ forM reds $ \(Reduce _ red_lam red_nes) -> do red_nes' <- mapM TC.checkArg red_nes let red_t = map TC.argType red_nes' TC.checkLambda red_lam $ map TC.noArgAliases $ red_nes' ++ red_nes' unless (red_t == lambdaReturnType red_lam) $ TC.bad . TC.TypeError $ "Reduce function returns type " <> prettyTuple (lambdaReturnType red_lam) <> " but neutral element has type " <> prettyTuple red_t pure red_nes' let map_lam_ts = lambdaReturnType map_lam unless ( take (length scan_nes' + length red_nes') map_lam_ts == map TC.argType (scan_nes' ++ red_nes') ) . TC.bad . TC.TypeError $ "Map function return type " <> prettyTuple map_lam_ts <> " wrong for given scan and reduction functions." instance RephraseOp SOAC where rephraseInOp r (VJP lam args vec) = VJP <$> rephraseLambda r lam <*> pure args <*> pure vec rephraseInOp r (JVP lam args vec) = JVP <$> rephraseLambda r lam <*> pure args <*> pure vec rephraseInOp r (Stream w arrs acc lam) = Stream w arrs acc <$> rephraseLambda r lam rephraseInOp r (Scatter w arrs lam dests) = Scatter w arrs <$> rephraseLambda r lam <*> pure dests rephraseInOp r (Hist w arrs ops lam) = Hist w arrs <$> mapM onOp ops <*> rephraseLambda r lam where onOp (HistOp dest_shape rf dests nes op) = HistOp dest_shape rf dests nes <$> rephraseLambda r op rephraseInOp r (Screma w arrs (ScremaForm scans red lam)) = Screma w arrs <$> ( ScremaForm <$> mapM onScan scans <*> mapM onRed red <*> rephraseLambda r lam ) where onScan (Scan op nes) = Scan <$> rephraseLambda r op <*> pure nes onRed (Reduce comm op nes) = Reduce comm <$> rephraseLambda r op <*> pure nes instance OpMetrics (Op rep) => OpMetrics (SOAC rep) where opMetrics (VJP lam _ _) = inside "VJP" $ lambdaMetrics lam opMetrics (JVP lam _ _) = inside "JVP" $ lambdaMetrics lam opMetrics (Stream _ _ _ lam) = inside "Stream" $ lambdaMetrics lam opMetrics (Scatter _len _ lam _) = inside "Scatter" $ lambdaMetrics lam opMetrics (Hist _ _ ops bucket_fun) = inside "Hist" $ mapM_ (lambdaMetrics . histOp) ops >> lambdaMetrics bucket_fun opMetrics (Screma _ _ (ScremaForm scans reds map_lam)) = inside "Screma" $ do mapM_ (lambdaMetrics . scanLambda) scans mapM_ (lambdaMetrics . redLambda) reds lambdaMetrics map_lam instance PrettyRep rep => PP.Pretty (SOAC rep) where pretty (VJP lam args vec) = "vjp" <> parens ( PP.align $ pretty lam <> comma </> PP.braces (commasep $ map pretty args) <> comma </> PP.braces (commasep $ map pretty vec) ) pretty (JVP lam args vec) = "jvp" <> parens ( PP.align $ pretty lam <> comma </> PP.braces (commasep $ map pretty args) <> comma </> PP.braces (commasep $ map pretty vec) ) pretty (Stream size arrs acc lam) = ppStream size arrs acc lam pretty (Scatter w arrs lam dests) = ppScatter w arrs lam dests pretty (Hist w arrs ops bucket_fun) = ppHist w arrs ops bucket_fun pretty (Screma w arrs (ScremaForm scans reds map_lam)) | null scans, null reds = "map" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> pretty map_lam ) | null scans = "redomap" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty reds) <> comma </> pretty map_lam ) | null reds = "scanomap" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty scans) <> comma </> pretty map_lam ) pretty (Screma w arrs form) = ppScrema w arrs form | Prettyprint the given Screma . ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc ann ppScrema w arrs (ScremaForm scans reds map_lam) = "screma" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty scans) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty reds) <> comma </> pretty map_lam ) | Prettyprint the given Stream . ppStream :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> [SubExp] -> Lambda rep -> Doc ann ppStream size arrs acc lam = "streamSeq" <> (parens . align) ( pretty size <> comma </> ppTuple' (map pretty arrs) <> comma </> ppTuple' (map pretty acc) <> comma </> pretty lam ) | Prettyprint the given Scatter . ppScatter :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> Lambda rep -> [(Shape, Int, VName)] -> Doc ann ppScatter w arrs lam dests = "scatter" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> pretty lam <> comma </> commasep (map pretty dests) ) instance PrettyRep rep => Pretty (Scan rep) where pretty (Scan scan_lam scan_nes) = pretty scan_lam <> comma </> PP.braces (commasep $ map pretty scan_nes) ppComm :: Commutativity -> Doc ann ppComm Noncommutative = mempty ppComm Commutative = "commutative " instance PrettyRep rep => Pretty (Reduce rep) where pretty (Reduce comm red_lam red_nes) = ppComm comm <> pretty red_lam <> comma </> PP.braces (commasep $ map pretty red_nes) | Prettyprint the given histogram operation . ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> [HistOp rep] -> Lambda rep -> Doc ann ppHist w arrs ops bucket_fun = "hist" <> parens ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppOp ops) <> comma </> pretty bucket_fun ) where ppOp (HistOp dest_w rf dests nes op) = pretty dest_w <> comma <+> pretty rf <> comma <+> PP.braces (commasep $ map pretty dests) <> comma </> ppTuple' (map pretty nes) <> comma </> pretty op
null
https://raw.githubusercontent.com/diku-dk/futhark/174e8d862def6f52d5c9a36fa3aa6e746049776e/src/Futhark/IR/SOACS/SOAC.hs
haskell
| Definition of /Second-Order Array Combinators/ (SOACs), which are the main form of parallelism in the early stages of the compiler. * Utility * Generic traversal Scatter maps values from a set of input arrays to indices and values of a set of output arrays. It is able to write multiple values to multiple outputs each of which may have multiple dimensions. <inputs> is a list of input arrays, all having size <length>, elements of which are applied to the <lambda> function. For instance, if there are <outputs> specifies the result of the <lambda> and which arrays to write to. Each element of the list consists of a <VName> specifying which array to scatter to, a <Shape> describing the shape of that array, and an <Int> describing how many elements should be written to that array for each invocation of the <lambda>. <lambda> is a function that takes inputs from <inputs> and returns values according to the output-specification in <outputs>. It returns values in the following manner: For each output in <outputs>, <lambda> returns <i> * <j> index values and <j> output values, where <i> is the number of dimensions (rank) of the given output, and <j> is the number of output values written to the given output. For example, given the following output specification: | @Hist <length> <input arrays> <dest-arrays-and-ops> <bucket fun>@ The final lambda produces indexes and values for the 'HistOp's. FIXME: this should not be here FIXME: this should not be here t'SubExp' is the size of the input arrays. | Information about computing a single histogram. | Race factor @RF@ means that only @1/RF@ bins are used. except the input arrays). | How to compute a single scan result. | How many reduction results are produced by these 'Scan's? | Combine multiple scan operators to a single operator. | How to compute a single reduction result. | How many reduction results are produced by these 'Reduce's? | Combine multiple reduction operators to a single operator. input array. | Construct a lambda that takes parameters of the given types and simply returns them unchanged. | Is the given lambda an identity lambda? | A lambda with no parameters that returns no values. the given map function. the given map function. function. identity map function. reduction or scan results? equivalent to 'isMapSOAC'. Note that the meaning of the return is. The parameters will correspond exactly to elements of the input arrays, however. | @groupScatterResults <output specification> <results>@ <output specification>. This function is used for extracting and grouping the results of a The elements of the resulting list correspond to the shape and name of the output parameters, in addition to a list of values written to that output parameter, along with the array indices marking where to write them to. See 'Scatter' for more information. | @groupScatterResults' <output specification> <results>@ which doesn't return any information about shapes or output arrays. See 'groupScatterResults' for more information, | @splitScatterResults <output specification> <results>@ Splits the results array into indices and values according to the output specification. See 'groupScatterResults' for more information. | Map a monadic action across the immediate children of a and is done left-to-right. | A helper for defining 'TraverseOpStms'. Only map functions can consume anything. The operands to scan and reduce functions are always considered "fresh". Drop the chunk parameter, which cannot alias anything. just get the dflow of lambda on the fakearg, which does not alias arr, so we can later check that aliases of arr are not used inside lam. Requirements: [index types..., value types, ...]. 1. The number of index types and value types must be equal to the number 2. Each index type must have the type i64. 3. Each array in @as@ and the value types must have the same type 4. Each array in @as@ is consumed. This is not really a check, but more of a requirement, so that e.g. the source is not hoisted out of a loop, which will mean it cannot be consumed. 5. Each of arrs must be an array matching a corresponding lambda parameters. Code: 0. All lengths must have type i64. Check the operators. Operator type must match the type of neutral elements. Arrays must have proper type. Types of input arrays must equal parameter types for bucket function. Return type of bucket function must be an index for each operation followed by the values to write.
# LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Futhark.IR.SOACS.SOAC ( SOAC (..), ScremaForm (..), HistOp (..), Scan (..), scanResults, singleScan, Reduce (..), redResults, singleReduce, scremaType, soacType, typeCheckSOAC, mkIdentityLambda, isIdentityLambda, nilFn, scanomapSOAC, redomapSOAC, scanSOAC, reduceSOAC, mapSOAC, isScanomapSOAC, isRedomapSOAC, isScanSOAC, isReduceSOAC, isMapSOAC, scremaLambda, ppScrema, ppHist, ppStream, ppScatter, groupScatterResults, groupScatterResults', splitScatterResults, SOACMapper (..), identitySOACMapper, mapSOACM, traverseSOACStms, ) where import Control.Category import Control.Monad.Identity import Control.Monad.State.Strict import Control.Monad.Writer import Data.Function ((&)) import Data.List (intersperse) import Data.Map.Strict qualified as M import Data.Maybe import Futhark.Analysis.Alias qualified as Alias import Futhark.Analysis.Metrics import Futhark.Analysis.PrimExp.Convert import Futhark.Analysis.SymbolTable qualified as ST import Futhark.Construct import Futhark.IR import Futhark.IR.Aliases (Aliases, CanBeAliased (..)) import Futhark.IR.Prop.Aliases import Futhark.IR.TypeCheck qualified as TC import Futhark.Optimise.Simplify.Rep import Futhark.Transform.Rename import Futhark.Transform.Substitute import Futhark.Util (chunks, maybeNth) import Futhark.Util.Pretty (Doc, align, comma, commasep, docText, parens, ppTuple', pretty, (<+>), (</>)) import Futhark.Util.Pretty qualified as PP import Prelude hiding (id, (.)) | A second - order array combinator ( SOAC ) . data SOAC rep = Stream SubExp [VName] [SubExp] (Lambda rep) | @Scatter < length > < inputs > < lambda > < outputs>@ two arrays , < lambda > will get two values as input , one from each array . [ , index_1 , ... , index_n , value_0 , value_1 , ... , value_m ] [ ( [ x1 , y1 , z1 ] , 2 , arr1 ) , ( [ x2 , y2 ] , 1 , arr2 ) ] < lambda > will produce 6 ( 3 * 2 ) index values and 2 output values for < arr1 > , and 2 ( 2 * 1 ) index values and 1 output value for arr2 . Additionally , the results are grouped , so the first 6 index values will correspond to the first two output values , and so on . For this example , < lambda > should return a total of 11 values , 8 index values and 3 output values . See also ' splitScatterResults ' . Scatter SubExp [VName] (Lambda rep) [(Shape, Int, VName)] Hist SubExp [VName] [HistOp rep] (Lambda rep) JVP (Lambda rep) [SubExp] [SubExp] VJP (Lambda rep) [SubExp] [SubExp] | A combination of scan , reduction , and map . The first Screma SubExp [VName] (ScremaForm rep) deriving (Eq, Ord, Show) data HistOp rep = HistOp { histShape :: Shape, histRaceFactor :: SubExp, histDest :: [VName], histNeutral :: [SubExp], histOp :: Lambda rep } deriving (Eq, Ord, Show) | The essential parts of a ' Screma ' factored out ( everything data ScremaForm rep = ScremaForm [Scan rep] [Reduce rep] (Lambda rep) deriving (Eq, Ord, Show) singleBinOp :: Buildable rep => [Lambda rep] -> Lambda rep singleBinOp lams = Lambda { lambdaParams = concatMap xParams lams ++ concatMap yParams lams, lambdaReturnType = concatMap lambdaReturnType lams, lambdaBody = mkBody (mconcat (map (bodyStms . lambdaBody) lams)) (concatMap (bodyResult . lambdaBody) lams) } where xParams lam = take (length (lambdaReturnType lam)) (lambdaParams lam) yParams lam = drop (length (lambdaReturnType lam)) (lambdaParams lam) data Scan rep = Scan { scanLambda :: Lambda rep, scanNeutral :: [SubExp] } deriving (Eq, Ord, Show) scanResults :: [Scan rep] -> Int scanResults = sum . map (length . scanNeutral) singleScan :: Buildable rep => [Scan rep] -> Scan rep singleScan scans = let scan_nes = concatMap scanNeutral scans scan_lam = singleBinOp $ map scanLambda scans in Scan scan_lam scan_nes data Reduce rep = Reduce { redComm :: Commutativity, redLambda :: Lambda rep, redNeutral :: [SubExp] } deriving (Eq, Ord, Show) redResults :: [Reduce rep] -> Int redResults = sum . map (length . redNeutral) singleReduce :: Buildable rep => [Reduce rep] -> Reduce rep singleReduce reds = let red_nes = concatMap redNeutral reds red_lam = singleBinOp $ map redLambda reds in Reduce (mconcat (map redComm reds)) red_lam red_nes | The types produced by a single ' Screma ' , given the size of the scremaType :: SubExp -> ScremaForm rep -> [Type] scremaType w (ScremaForm scans reds map_lam) = scan_tps ++ red_tps ++ map (`arrayOfRow` w) map_tps where scan_tps = map (`arrayOfRow` w) $ concatMap (lambdaReturnType . scanLambda) scans red_tps = concatMap (lambdaReturnType . redLambda) reds map_tps = drop (length scan_tps + length red_tps) $ lambdaReturnType map_lam mkIdentityLambda :: (Buildable rep, MonadFreshNames m) => [Type] -> m (Lambda rep) mkIdentityLambda ts = do params <- mapM (newParam "x") ts pure Lambda { lambdaParams = params, lambdaBody = mkBody mempty $ varsRes $ map paramName params, lambdaReturnType = ts } isIdentityLambda :: Lambda rep -> Bool isIdentityLambda lam = map resSubExp (bodyResult (lambdaBody lam)) == map (Var . paramName) (lambdaParams lam) nilFn :: Buildable rep => Lambda rep nilFn = Lambda mempty (mkBody mempty mempty) mempty | Construct a Screma with possibly multiple scans , and scanomapSOAC :: [Scan rep] -> Lambda rep -> ScremaForm rep scanomapSOAC scans = ScremaForm scans [] | Construct a Screma with possibly multiple reductions , and redomapSOAC :: [Reduce rep] -> Lambda rep -> ScremaForm rep redomapSOAC = ScremaForm [] | Construct a Screma with possibly multiple scans , and identity map scanSOAC :: (Buildable rep, MonadFreshNames m) => [Scan rep] -> m (ScremaForm rep) scanSOAC scans = scanomapSOAC scans <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . scanLambda) scans | Construct a Screma with possibly multiple reductions , and reduceSOAC :: (Buildable rep, MonadFreshNames m) => [Reduce rep] -> m (ScremaForm rep) reduceSOAC reds = redomapSOAC reds <$> mkIdentityLambda ts where ts = concatMap (lambdaReturnType . redLambda) reds | Construct a Screma corresponding to a map . mapSOAC :: Lambda rep -> ScremaForm rep mapSOAC = ScremaForm [] [] | Does this Screma correspond to a scan - map composition ? isScanomapSOAC :: ScremaForm rep -> Maybe ([Scan rep], Lambda rep) isScanomapSOAC (ScremaForm scans reds map_lam) = do guard $ null reds guard $ not $ null scans pure (scans, map_lam) | Does this Screma correspond to pure scan ? isScanSOAC :: ScremaForm rep -> Maybe [Scan rep] isScanSOAC form = do (scans, map_lam) <- isScanomapSOAC form guard $ isIdentityLambda map_lam pure scans | Does this Screma correspond to a reduce - map composition ? isRedomapSOAC :: ScremaForm rep -> Maybe ([Reduce rep], Lambda rep) isRedomapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ not $ null reds pure (reds, map_lam) | Does this Screma correspond to a pure reduce ? isReduceSOAC :: ScremaForm rep -> Maybe [Reduce rep] isReduceSOAC form = do (reds, map_lam) <- isRedomapSOAC form guard $ isIdentityLambda map_lam pure reds | Does this Screma correspond to a simple map , without any isMapSOAC :: ScremaForm rep -> Maybe (Lambda rep) isMapSOAC (ScremaForm scans reds map_lam) = do guard $ null scans guard $ null reds pure map_lam | Return the " main " lambda of the Screma . For a map , this is value of this lambda depends crucially on exactly which Screma this scremaLambda :: ScremaForm rep -> Lambda rep scremaLambda (ScremaForm _ _ map_lam) = map_lam Groups the index values and result values of < results > according to the scatter . In the SOAC representation , the lambda inside a ' Scatter ' returns all indices and values as one big list . This function groups each value with its corresponding indices ( as determined by the t'Shape ' of the output array ) . groupScatterResults :: [(Shape, Int, array)] -> [a] -> [(Shape, array, [([a], a)])] groupScatterResults output_spec results = let (shapes, ns, arrays) = unzip3 output_spec in groupScatterResults' output_spec results & chunks ns & zip3 shapes arrays Groups the index values and result values of < results > according to the output specification . This is the simpler version of @groupScatterResults@ , groupScatterResults' :: [(Shape, Int, array)] -> [a] -> [([a], a)] groupScatterResults' output_spec results = let (indices, values) = splitScatterResults output_spec results (shapes, ns, _) = unzip3 output_spec chunk_sizes = concat $ zipWith (\shp n -> replicate n $ length shp) shapes ns in zip (chunks chunk_sizes indices) values splitScatterResults :: [(Shape, Int, array)] -> [a] -> ([a], [a]) splitScatterResults output_spec results = let (shapes, ns, _) = unzip3 output_spec num_indices = sum $ zipWith (*) ns $ map length shapes in splitAt num_indices results | Like ' Mapper ' , but just for ' SOAC 's . data SOACMapper frep trep m = SOACMapper { mapOnSOACSubExp :: SubExp -> m SubExp, mapOnSOACLambda :: Lambda frep -> m (Lambda trep), mapOnSOACVName :: VName -> m VName } | A mapper that simply returns the SOAC verbatim . identitySOACMapper :: Monad m => SOACMapper rep rep m identitySOACMapper = SOACMapper { mapOnSOACSubExp = pure, mapOnSOACLambda = pure, mapOnSOACVName = pure } SOAC . The mapping does not descend recursively into subexpressions mapSOACM :: Monad m => SOACMapper frep trep m -> SOAC frep -> m (SOAC trep) mapSOACM tv (JVP lam args vec) = JVP <$> mapOnSOACLambda tv lam <*> mapM (mapOnSOACSubExp tv) args <*> mapM (mapOnSOACSubExp tv) vec mapSOACM tv (VJP lam args vec) = VJP <$> mapOnSOACLambda tv lam <*> mapM (mapOnSOACSubExp tv) args <*> mapM (mapOnSOACSubExp tv) vec mapSOACM tv (Stream size arrs accs lam) = Stream <$> mapOnSOACSubExp tv size <*> mapM (mapOnSOACVName tv) arrs <*> mapM (mapOnSOACSubExp tv) accs <*> mapOnSOACLambda tv lam mapSOACM tv (Scatter w ivs lam as) = Scatter <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) ivs <*> mapOnSOACLambda tv lam <*> mapM ( \(aw, an, a) -> (,,) <$> mapM (mapOnSOACSubExp tv) aw <*> pure an <*> mapOnSOACVName tv a ) as mapSOACM tv (Hist w arrs ops bucket_fun) = Hist <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> mapM ( \(HistOp shape rf op_arrs nes op) -> HistOp <$> mapM (mapOnSOACSubExp tv) shape <*> mapOnSOACSubExp tv rf <*> mapM (mapOnSOACVName tv) op_arrs <*> mapM (mapOnSOACSubExp tv) nes <*> mapOnSOACLambda tv op ) ops <*> mapOnSOACLambda tv bucket_fun mapSOACM tv (Screma w arrs (ScremaForm scans reds map_lam)) = Screma <$> mapOnSOACSubExp tv w <*> mapM (mapOnSOACVName tv) arrs <*> ( ScremaForm <$> forM scans ( \(Scan red_lam red_nes) -> Scan <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> forM reds ( \(Reduce comm red_lam red_nes) -> Reduce comm <$> mapOnSOACLambda tv red_lam <*> mapM (mapOnSOACSubExp tv) red_nes ) <*> mapOnSOACLambda tv map_lam ) traverseSOACStms :: Monad m => OpStmsTraverser m (SOAC rep) rep traverseSOACStms f = mapSOACM mapper where mapper = identitySOACMapper {mapOnSOACLambda = traverseLambdaStms f} instance ASTRep rep => FreeIn (Scan rep) where freeIn' (Scan lam ne) = freeIn' lam <> freeIn' ne instance ASTRep rep => FreeIn (Reduce rep) where freeIn' (Reduce _ lam ne) = freeIn' lam <> freeIn' ne instance ASTRep rep => FreeIn (ScremaForm rep) where freeIn' (ScremaForm scans reds lam) = freeIn' scans <> freeIn' reds <> freeIn' lam instance ASTRep rep => FreeIn (HistOp rep) where freeIn' (HistOp w rf dests nes lam) = freeIn' w <> freeIn' rf <> freeIn' dests <> freeIn' nes <> freeIn' lam instance ASTRep rep => FreeIn (SOAC rep) where freeIn' = flip execState mempty . mapSOACM free where walk f x = modify (<> f x) >> pure x free = SOACMapper { mapOnSOACSubExp = walk freeIn', mapOnSOACLambda = walk freeIn', mapOnSOACVName = walk freeIn' } instance ASTRep rep => Substitute (SOAC rep) where substituteNames subst = runIdentity . mapSOACM substitute where substitute = SOACMapper { mapOnSOACSubExp = pure . substituteNames subst, mapOnSOACLambda = pure . substituteNames subst, mapOnSOACVName = pure . substituteNames subst } instance ASTRep rep => Rename (SOAC rep) where rename = mapSOACM renamer where renamer = SOACMapper rename rename rename | The type of a SOAC . soacType :: Typed (LParamInfo rep) => SOAC rep -> [Type] soacType (JVP lam _ _) = lambdaReturnType lam ++ lambdaReturnType lam soacType (VJP lam _ _) = lambdaReturnType lam ++ map paramType (lambdaParams lam) soacType (Stream outersize _ accs lam) = map (substNamesInType substs) rtp where nms = map paramName $ take (1 + length accs) params substs = M.fromList $ zip nms (outersize : accs) Lambda params _ rtp = lam soacType (Scatter _w _ivs lam dests) = zipWith arrayOfShape val_ts ws where indexes = sum $ zipWith (*) ns $ map length ws val_ts = drop indexes $ lambdaReturnType lam (ws, ns, _) = unzip3 dests soacType (Hist _ _ ops _bucket_fun) = do op <- ops map (`arrayOfShape` histShape op) (lambdaReturnType $ histOp op) soacType (Screma w _arrs form) = scremaType w form instance ASTRep rep => TypedOp (SOAC rep) where opType = pure . staticShapes . soacType instance Aliased rep => AliasedOp (SOAC rep) where opAliases = map (const mempty) . soacType consumedInOp JVP {} = mempty consumedInOp VJP {} = mempty consumedInOp (Screma _ arrs (ScremaForm _ _ map_lam)) = mapNames consumedArray $ consumedByLambda map_lam where consumedArray v = fromMaybe v $ lookup v params_to_arrs params_to_arrs = zip (map paramName $ lambdaParams map_lam) arrs consumedInOp (Stream _ arrs accs lam) = namesFromList $ subExpVars $ map consumedArray $ namesToList $ consumedByLambda lam where consumedArray v = fromMaybe (Var v) $ lookup v paramsToInput paramsToInput = zip (map paramName $ drop 1 $ lambdaParams lam) (accs ++ map Var arrs) consumedInOp (Scatter _ _ _ as) = namesFromList $ map (\(_, _, a) -> a) as consumedInOp (Hist _ _ ops _) = namesFromList $ concatMap histDest ops mapHistOp :: (Lambda frep -> Lambda trep) -> HistOp frep -> HistOp trep mapHistOp f (HistOp w rf dests nes lam) = HistOp w rf dests nes $ f lam instance CanBeAliased SOAC where addOpAliases aliases (JVP lam args vec) = JVP (Alias.analyseLambda aliases lam) args vec addOpAliases aliases (VJP lam args vec) = VJP (Alias.analyseLambda aliases lam) args vec addOpAliases aliases (Stream size arr accs lam) = Stream size arr accs $ Alias.analyseLambda aliases lam addOpAliases aliases (Scatter len arrs lam dests) = Scatter len arrs (Alias.analyseLambda aliases lam) dests addOpAliases aliases (Hist w arrs ops bucket_fun) = Hist w arrs (map (mapHistOp (Alias.analyseLambda aliases)) ops) (Alias.analyseLambda aliases bucket_fun) addOpAliases aliases (Screma w arrs (ScremaForm scans reds map_lam)) = Screma w arrs $ ScremaForm (map onScan scans) (map onRed reds) (Alias.analyseLambda aliases map_lam) where onRed red = red {redLambda = Alias.analyseLambda aliases $ redLambda red} onScan scan = scan {scanLambda = Alias.analyseLambda aliases $ scanLambda scan} instance ASTRep rep => IsOp (SOAC rep) where safeOp _ = False cheapOp _ = False substNamesInType :: M.Map VName SubExp -> Type -> Type substNamesInType _ t@Prim {} = t substNamesInType _ t@Acc {} = t substNamesInType _ (Mem space) = Mem space substNamesInType subs (Array btp shp u) = let shp' = Shape $ map (substNamesInSubExp subs) (shapeDims shp) in Array btp shp' u substNamesInSubExp :: M.Map VName SubExp -> SubExp -> SubExp substNamesInSubExp _ e@(Constant _) = e substNamesInSubExp subs (Var idd) = M.findWithDefault (Var idd) idd subs instance CanBeWise SOAC where addOpWisdom = runIdentity . mapSOACM (SOACMapper pure (pure . informLambda) pure) instance RepTypes rep => ST.IndexOp (SOAC rep) where indexOp vtable k soac [i] = do (lam, se, arr_params, arrs) <- lambdaAndSubExp soac let arr_indexes = M.fromList $ catMaybes $ zipWith arrIndex arr_params arrs arr_indexes' = foldl expandPrimExpTable arr_indexes $ bodyStms $ lambdaBody lam case se of SubExpRes _ (Var v) -> uncurry (flip ST.Indexed) <$> M.lookup v arr_indexes' _ -> Nothing where lambdaAndSubExp (Screma _ arrs (ScremaForm scans reds map_lam)) = nthMapOut (scanResults scans + redResults reds) map_lam arrs lambdaAndSubExp _ = Nothing nthMapOut num_accs lam arrs = do se <- maybeNth (num_accs + k) $ bodyResult $ lambdaBody lam pure (lam, se, drop num_accs $ lambdaParams lam, arrs) arrIndex p arr = do ST.Indexed cs pe <- ST.index' arr [i] vtable pure (paramName p, (pe, cs)) expandPrimExpTable table stm | [v] <- patNames $ stmPat stm, Just (pe, cs) <- runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm, all (`ST.elem` vtable) (unCerts $ stmCerts stm) = M.insert v (pe, stmCerts stm <> cs) table | otherwise = table asPrimExp table v | Just (e, cs) <- M.lookup v table = tell cs >> pure e | Just (Prim pt) <- ST.lookupType v vtable = pure $ LeafExp v pt | otherwise = lift Nothing indexOp _ _ _ _ = Nothing | Type - check a SOAC . typeCheckSOAC :: TC.Checkable rep => SOAC (Aliases rep) -> TC.TypeM rep () typeCheckSOAC (VJP lam args vec) = do args' <- mapM TC.checkArg args TC.checkLambda lam $ map TC.noArgAliases args' vec_ts <- mapM TC.checkSubExp vec unless (vec_ts == lambdaReturnType lam) $ TC.bad . TC.TypeError . docText $ "Return type" </> PP.indent 2 (pretty (lambdaReturnType lam)) </> "does not match type of seed vector" </> PP.indent 2 (pretty vec_ts) typeCheckSOAC (JVP lam args vec) = do args' <- mapM TC.checkArg args TC.checkLambda lam $ map TC.noArgAliases args' vec_ts <- mapM TC.checkSubExp vec unless (vec_ts == map TC.argType args') $ TC.bad . TC.TypeError . docText $ "Parameter type" </> PP.indent 2 (pretty $ map TC.argType args') </> "does not match type of seed vector" </> PP.indent 2 (pretty vec_ts) typeCheckSOAC (Stream size arrexps accexps lam) = do TC.require [Prim int64] size accargs <- mapM TC.checkArg accexps arrargs <- mapM lookupType arrexps _ <- TC.checkSOACArrayArgs size arrexps let chunk = head $ lambdaParams lam let asArg t = (t, mempty) inttp = Prim int64 lamarrs' = map (`setOuterSize` Var (paramName chunk)) arrargs let acc_len = length accexps let lamrtp = take acc_len $ lambdaReturnType lam unless (map TC.argType accargs == lamrtp) $ TC.bad . TC.TypeError $ "Stream with inconsistent accumulator type in lambda." let fake_lamarrs' = map asArg lamarrs' TC.checkLambda lam $ asArg inttp : accargs ++ fake_lamarrs' typeCheckSOAC (Scatter w arrs lam as) = do 0 . @lambdaReturnType@ of must be a list of return values from @lam@. First check the input size . TC.require [Prim int64] w let (as_ws, as_ns, _as_vs) = unzip3 as indexes = sum $ zipWith (*) as_ns $ map length as_ws rts = lambdaReturnType lam rtsI = take indexes rts rtsV = drop indexes rts 1 . unless (length rts == sum as_ns + sum (zipWith (*) as_ns $ map length as_ws)) $ TC.bad $ TC.TypeError "Scatter: number of index types, value types and array outputs do not match." 2 . forM_ rtsI $ \rtI -> unless (Prim int64 == rtI) $ TC.bad $ TC.TypeError "Scatter: Index return type must be i64." forM_ (zip (chunks as_ns rtsV) as) $ \(rtVs, (aw, _, a)) -> do mapM_ (TC.require [Prim int64]) aw 3 . forM_ rtVs $ \rtV -> TC.requireI [arrayOfShape rtV aw] a 4 . TC.consume =<< TC.lookupAliases a 5 . arrargs <- TC.checkSOACArrayArgs w arrs TC.checkLambda lam arrargs typeCheckSOAC (Hist w arrs ops bucket_fun) = do TC.require [Prim int64] w forM_ ops $ \(HistOp dest_shape rf dests nes op) -> do nes' <- mapM TC.checkArg nes mapM_ (TC.require [Prim int64]) dest_shape TC.require [Prim int64] rf TC.checkLambda op $ map TC.noArgAliases $ nes' ++ nes' let nes_t = map TC.argType nes' unless (nes_t == lambdaReturnType op) $ TC.bad . TC.TypeError $ "Operator has return type " <> prettyTuple (lambdaReturnType op) <> " but neutral element has type " <> prettyTuple nes_t forM_ (zip nes_t dests) $ \(t, dest) -> do TC.requireI [t `arrayOfShape` dest_shape] dest TC.consume =<< TC.lookupAliases dest img' <- TC.checkSOACArrayArgs w arrs TC.checkLambda bucket_fun img' nes_ts <- concat <$> mapM (mapM subExpType . histNeutral) ops let bucket_ret_t = concatMap ((`replicate` Prim int64) . shapeRank . histShape) ops ++ nes_ts unless (bucket_ret_t == lambdaReturnType bucket_fun) $ TC.bad . TC.TypeError $ "Bucket function has return type " <> prettyTuple (lambdaReturnType bucket_fun) <> " but should have type " <> prettyTuple bucket_ret_t typeCheckSOAC (Screma w arrs (ScremaForm scans reds map_lam)) = do TC.require [Prim int64] w arrs' <- TC.checkSOACArrayArgs w arrs TC.checkLambda map_lam arrs' scan_nes' <- fmap concat $ forM scans $ \(Scan scan_lam scan_nes) -> do scan_nes' <- mapM TC.checkArg scan_nes let scan_t = map TC.argType scan_nes' TC.checkLambda scan_lam $ map TC.noArgAliases $ scan_nes' ++ scan_nes' unless (scan_t == lambdaReturnType scan_lam) $ TC.bad . TC.TypeError $ "Scan function returns type " <> prettyTuple (lambdaReturnType scan_lam) <> " but neutral element has type " <> prettyTuple scan_t pure scan_nes' red_nes' <- fmap concat $ forM reds $ \(Reduce _ red_lam red_nes) -> do red_nes' <- mapM TC.checkArg red_nes let red_t = map TC.argType red_nes' TC.checkLambda red_lam $ map TC.noArgAliases $ red_nes' ++ red_nes' unless (red_t == lambdaReturnType red_lam) $ TC.bad . TC.TypeError $ "Reduce function returns type " <> prettyTuple (lambdaReturnType red_lam) <> " but neutral element has type " <> prettyTuple red_t pure red_nes' let map_lam_ts = lambdaReturnType map_lam unless ( take (length scan_nes' + length red_nes') map_lam_ts == map TC.argType (scan_nes' ++ red_nes') ) . TC.bad . TC.TypeError $ "Map function return type " <> prettyTuple map_lam_ts <> " wrong for given scan and reduction functions." instance RephraseOp SOAC where rephraseInOp r (VJP lam args vec) = VJP <$> rephraseLambda r lam <*> pure args <*> pure vec rephraseInOp r (JVP lam args vec) = JVP <$> rephraseLambda r lam <*> pure args <*> pure vec rephraseInOp r (Stream w arrs acc lam) = Stream w arrs acc <$> rephraseLambda r lam rephraseInOp r (Scatter w arrs lam dests) = Scatter w arrs <$> rephraseLambda r lam <*> pure dests rephraseInOp r (Hist w arrs ops lam) = Hist w arrs <$> mapM onOp ops <*> rephraseLambda r lam where onOp (HistOp dest_shape rf dests nes op) = HistOp dest_shape rf dests nes <$> rephraseLambda r op rephraseInOp r (Screma w arrs (ScremaForm scans red lam)) = Screma w arrs <$> ( ScremaForm <$> mapM onScan scans <*> mapM onRed red <*> rephraseLambda r lam ) where onScan (Scan op nes) = Scan <$> rephraseLambda r op <*> pure nes onRed (Reduce comm op nes) = Reduce comm <$> rephraseLambda r op <*> pure nes instance OpMetrics (Op rep) => OpMetrics (SOAC rep) where opMetrics (VJP lam _ _) = inside "VJP" $ lambdaMetrics lam opMetrics (JVP lam _ _) = inside "JVP" $ lambdaMetrics lam opMetrics (Stream _ _ _ lam) = inside "Stream" $ lambdaMetrics lam opMetrics (Scatter _len _ lam _) = inside "Scatter" $ lambdaMetrics lam opMetrics (Hist _ _ ops bucket_fun) = inside "Hist" $ mapM_ (lambdaMetrics . histOp) ops >> lambdaMetrics bucket_fun opMetrics (Screma _ _ (ScremaForm scans reds map_lam)) = inside "Screma" $ do mapM_ (lambdaMetrics . scanLambda) scans mapM_ (lambdaMetrics . redLambda) reds lambdaMetrics map_lam instance PrettyRep rep => PP.Pretty (SOAC rep) where pretty (VJP lam args vec) = "vjp" <> parens ( PP.align $ pretty lam <> comma </> PP.braces (commasep $ map pretty args) <> comma </> PP.braces (commasep $ map pretty vec) ) pretty (JVP lam args vec) = "jvp" <> parens ( PP.align $ pretty lam <> comma </> PP.braces (commasep $ map pretty args) <> comma </> PP.braces (commasep $ map pretty vec) ) pretty (Stream size arrs acc lam) = ppStream size arrs acc lam pretty (Scatter w arrs lam dests) = ppScatter w arrs lam dests pretty (Hist w arrs ops bucket_fun) = ppHist w arrs ops bucket_fun pretty (Screma w arrs (ScremaForm scans reds map_lam)) | null scans, null reds = "map" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> pretty map_lam ) | null scans = "redomap" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty reds) <> comma </> pretty map_lam ) | null reds = "scanomap" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty scans) <> comma </> pretty map_lam ) pretty (Screma w arrs form) = ppScrema w arrs form | Prettyprint the given Screma . ppScrema :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> ScremaForm rep -> Doc ann ppScrema w arrs (ScremaForm scans reds map_lam) = "screma" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty scans) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map pretty reds) <> comma </> pretty map_lam ) | Prettyprint the given Stream . ppStream :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> [SubExp] -> Lambda rep -> Doc ann ppStream size arrs acc lam = "streamSeq" <> (parens . align) ( pretty size <> comma </> ppTuple' (map pretty arrs) <> comma </> ppTuple' (map pretty acc) <> comma </> pretty lam ) | Prettyprint the given Scatter . ppScatter :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> Lambda rep -> [(Shape, Int, VName)] -> Doc ann ppScatter w arrs lam dests = "scatter" <> (parens . align) ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> pretty lam <> comma </> commasep (map pretty dests) ) instance PrettyRep rep => Pretty (Scan rep) where pretty (Scan scan_lam scan_nes) = pretty scan_lam <> comma </> PP.braces (commasep $ map pretty scan_nes) ppComm :: Commutativity -> Doc ann ppComm Noncommutative = mempty ppComm Commutative = "commutative " instance PrettyRep rep => Pretty (Reduce rep) where pretty (Reduce comm red_lam red_nes) = ppComm comm <> pretty red_lam <> comma </> PP.braces (commasep $ map pretty red_nes) | Prettyprint the given histogram operation . ppHist :: (PrettyRep rep, Pretty inp) => SubExp -> [inp] -> [HistOp rep] -> Lambda rep -> Doc ann ppHist w arrs ops bucket_fun = "hist" <> parens ( pretty w <> comma </> ppTuple' (map pretty arrs) <> comma </> PP.braces (mconcat $ intersperse (comma <> PP.line) $ map ppOp ops) <> comma </> pretty bucket_fun ) where ppOp (HistOp dest_w rf dests nes op) = pretty dest_w <> comma <+> pretty rf <> comma <+> PP.braces (commasep $ map pretty dests) <> comma </> ppTuple' (map pretty nes) <> comma </> pretty op
f044e230897776a33079e68dc6ab9c23c343b790bf4815e76fe5755472a64689
ghc/ghc
T22510.hs
# LANGUAGE MagicHash , UnboxedTuples , UnboxedSums , ScopedTypeVariables , TypeApplications , AllowAmbiguousTypes # module Main where import Type.Reflection import Data.Proxy import GHC.Types import GHC.Prim moduleOf :: forall a . Typeable a => String moduleOf = case someTypeRep (Proxy @a) of SomeTypeRep tr -> (show tr ++ ": " ++ (tyConModule $ typeRepTyCon tr)) main = do These are in GHC.Types putStrLn $ moduleOf @Levity putStrLn $ moduleOf @'Lifted putStrLn $ moduleOf @RuntimeRep putStrLn $ moduleOf @'IntRep putStrLn $ moduleOf @'BoxedRep putStrLn $ moduleOf @'Lifted putStrLn $ moduleOf @VecCount putStrLn $ moduleOf @'Vec2 putStrLn $ moduleOf @VecElem putStrLn $ moduleOf @'Int8ElemRep -- This is from GHC.Tuple putStrLn $ moduleOf @((),()) -- These are in GHC.Prim putStrLn $ moduleOf @(# () , () #) -- putStrLn $ moduleOf @(# () | () #) -- putStrLn $ moduleOf @(Int64#) putStrLn $ moduleOf @(Word64#) putStrLn $ moduleOf @TYPE putStrLn $ moduleOf @CONSTRAINT
null
https://raw.githubusercontent.com/ghc/ghc/aacf616df0b4059e6b177ecb64624ae6fb1d1c87/testsuite/tests/typecheck/should_run/T22510.hs
haskell
This is from GHC.Tuple These are in GHC.Prim putStrLn $ moduleOf @(# () | () #)
# LANGUAGE MagicHash , UnboxedTuples , UnboxedSums , ScopedTypeVariables , TypeApplications , AllowAmbiguousTypes # module Main where import Type.Reflection import Data.Proxy import GHC.Types import GHC.Prim moduleOf :: forall a . Typeable a => String moduleOf = case someTypeRep (Proxy @a) of SomeTypeRep tr -> (show tr ++ ": " ++ (tyConModule $ typeRepTyCon tr)) main = do These are in GHC.Types putStrLn $ moduleOf @Levity putStrLn $ moduleOf @'Lifted putStrLn $ moduleOf @RuntimeRep putStrLn $ moduleOf @'IntRep putStrLn $ moduleOf @'BoxedRep putStrLn $ moduleOf @'Lifted putStrLn $ moduleOf @VecCount putStrLn $ moduleOf @'Vec2 putStrLn $ moduleOf @VecElem putStrLn $ moduleOf @'Int8ElemRep putStrLn $ moduleOf @((),()) putStrLn $ moduleOf @(# () , () #) putStrLn $ moduleOf @(Int64#) putStrLn $ moduleOf @(Word64#) putStrLn $ moduleOf @TYPE putStrLn $ moduleOf @CONSTRAINT
483095668ab86b14b92a96a0a1f52a87cb165a67da3812aa39bbaa01fdff4ae9
OCamlPro/liquidity
liquidOCamlPrinter.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , OCamlPro (* Fabrice Le Fessant, INRIA Saclay *) , University of Pennsylvania (* *) Copyright 2007 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) module Parser = LiquidOCamlParser Original Code from Ber - metaocaml , modified for 3.12.0 and fixed (* Printing code expressions *) Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing open Asttypes open Parser open Format open Location open Longident open Parsetree open Ast_helper let keyword token = LiquidOCamlLexer.keyword_of_token token let token keyword = LiquidOCamlLexer.token_of_keyword keyword let prefix_symbols = [ '!'; '?'; '~' ] ;; let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%' ] (* type fixity = Infix| Prefix *) let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!=" ] let is_special_infix_string s = try match token s with | OR | INFIXOP3 _ | INFIXOP4 _ -> true | _ -> false with Not_found -> List.mem s [ ":="; "!="; "::" ] determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | s when is_special_infix_string s -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_};_} -> fixity_of_string l | _ -> `Normal let is_infix = function | `Infix _ -> true | _ -> false (* which identifiers are in fact operators needing parentheses *) let needs_parens txt = is_infix (fixity_of_string txt) || List.mem txt.[0] prefix_symbols (* some infixes need spaces around parens to avoid clashes with comment syntax *) let needs_spaces txt = txt.[0]='*' || txt.[String.length txt - 1] = '*' (* add parentheses to binders when they are in fact infix or prefix operators *) let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" (* variance encoding: need to sync up with the [parser.mly] *) let type_variance = function | Invariant -> "" | Covariant -> "+" | Contravariant -> "-" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);_} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]);_}));_} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?firstf: (unit -> space_formatter) -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?firstf ?last fu f a -> let last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> let first = match first with Some x -> x | None -> match firstf with | None -> ("": _ format6) | Some f -> f () in pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, None) -> pp f "%S" i | Pconst_string (i, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (i.[0]='-') (fun f -> pp f "%s") f i | Pconst_integer (s, Some '\232') -> pp f "%s" s | Pconst_integer (s, Some '\233') -> pp f "%s" s | Pconst_integer (s, Some '\234') -> pp f "%s" s | Pconst_integer (s, Some '\235') -> pp f "%s" s | Pconst_integer (s, Some '\236') -> pp f "%s" s | Pconst_integer (s, Some '\237') -> pp f "%s" s | Pconst_integer (i, Some m) -> paren (i.[0]='-') (fun f (i, m) -> if m = '\231' then pp f "%s%s" i (LiquidOptions.curreny ()) else pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (i.[0]='-') (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (i.[0]='-') (fun f (i,_m) -> if m = '\231' then pp f "%s%s" i (LiquidOptions.curreny ()) else pp f "%s%c" i m) f (i,m) (* trailing space*) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "%s@;" (keyword MUTABLE) let virtual_flag f = function | Concrete -> () | Virtual -> pp f "%s@;" (keyword VIRTUAL) (* trailing space added *) let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "%s " (keyword REC) let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "%s " (keyword NONREC) | Recursive -> () let direction_flag f = function | Upto -> pp f "%s@ " (keyword TO) | Downto -> pp f "%s@ " (keyword DOWNTO) let private_flag f = function | Public -> () | Private -> pp f "%s@ " (keyword PRIVATE) let constant_string f s = pp f "%S" s let tyvar f str = pp f "'%s" str let tyvar_loc f str = pp f "'%s" str.txt let string_quot f x = pp f "`%s" x (* c ['a,'b] *) let rec class_params_def ctxt f = function | [] -> () | l -> pp f "[%a] " (* space *) (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Nolabel -> core_type1 ctxt f c (* otherwise parenthesize *) | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;'%s@]" (core_type1 ctxt) ct s | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> pp f "%a" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> pp f (* "%a%a@;" *) "%a%a" (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let type_variant_helper f x = match x with | Rtag (l, attrs, _, ctl) -> pp f "@[<2>%a%a@;%a@]" string_quot l.txt (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) attrs | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | [], Open -> pp f ">" (* Cf #7200: print [>] correctly *) | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> "" | (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*) | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f = function | Otag (l, attrs, ct) -> pp f "@[<hov2>%s: %a@ %a@ @]" l.txt Cf # 7200 | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(%s@ %a)@]" (keyword MODULE) longident_loc lid |_ -> pp f "@[<hov2>(%s@ %a@ with@ %a)@]" (keyword MODULE) longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x (********************pattern********************) be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = only consider ( ( A|B)|C ) | {ppat_desc= Ppat_or (p1,p2);_} -> list_of_pattern (p2::acc) p1 | x -> x::acc in if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt (* RA*) | Ppat_or _ -> (* *) pp f "@[<hov0>%a@]" (list ~sep:"@,|" (pattern ctxt)) (list_of_pattern [] x) | _ -> pattern1 ctxt f x and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ({ppat_desc = Ppat_tuple([pat1; pat2]);_})); _} -> pp f "%a::%a" (simple_pattern ctxt) pat1 pattern_list_helper pat2 (*RA*) | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some x -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | None -> pp f "%a@;"longident_loc li ) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), _) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack (s) -> pp f "(%s@ %s)@ " (keyword MODULE) s.txt | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p.ppat_desc) with | ({txt=Lident s;_ },Ppat_var {txt;_} ) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (pattern1 ctxt) p | Ppat_exception p -> pp f "@[<2>%s@;%a@]" (keyword EXCEPTION) (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), _) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> (* single case pattern parens needed here *) pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p.ppat_desc with | Ppat_var {txt;_} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p.ppat_desc with | Ppat_var {txt;_} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let print left right print_index indexes rem_args = match func, rem_args with | "get", [] -> pp f "@[%a.%s%a%s@]" (simple_expr ctxt) a left (list ~sep:"," print_index) indexes right; true | "set", [v] -> pp f "@[%a.%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a left (list ~sep:"," print_index) indexes right (simple_expr ctxt) v; true | _ -> false in match path, other_args with | Lident "Array", i :: rest -> print "(" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print "[" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print "{" "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print "{" "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print "{" "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print "{" "}" (simple_expr ctxt) indexes rest | _ -> false end | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>%s@;%a@;->@;%a@]" (keyword FUN) (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_function l -> pp f "@[<hv>%s%a@]" (keyword FUNCTION) (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>%s %a@]@ %s@]%a@]" (keyword MATCH) (expression reset_ctxt) e (keyword WITH) (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>%s@ %a@]@ @[<0>%s%a@]@]" (* "try@;@[<2>%a@]@\nwith@\n%a"*) (keyword TRY) (expression reset_ctxt) e (keyword WITH) (case_list ctxt) l | Pexp_let (rf, l, e) -> (* pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no identation here, a new line*) *) rec_flag rf pp f "@[<2>%a %s@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (keyword IN) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with (* See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal *) |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l (* reset here only because [function,match,try,sequence] are lower priority *) end (e,l) end | Pexp_construct (li, Some eo) when not (is_simple_construct (view_expr x))-> (* Not efficient FIXME*) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> (* @;@[<2>else@ %a@]@] *) let fmt:(_,_,_)format = Scanf.format_from_string (Printf.sprintf "@[<hv0>@[<2>%s@ %%a@]@;@[<2>%s@ %%a@]%%a@]" (keyword IF) (keyword THEN) ) "%a%a%a" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>%s@;%a@]" (keyword ELSE) (expression (under_semi ctxt)) x | None -> () (* pp f "()" *)) eo | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2);_} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>%s@ %a@]" (keyword NEW) longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>%s@ %s@ %s@ =@ %a@ %s@ %a@]" (keyword LET) (keyword MODULE) s.txt (module_expr reset_ctxt) me (keyword IN) (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>%s@ %s@ %a@ %s@ %a@]" (keyword LET) (keyword EXCEPTION) (extension_constructor ctxt) cd (keyword IN) (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>%s@ %a@]" (keyword ASSERT) (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>%s@ %a@]" (keyword LAZY) (simple_expr ctxt) e (* Pexp_poly: impossible but we should print it anyway, rather than assert false *) | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (ovf, lid, e) -> pp f "@[<2>%s %s%s %a %s@;%a@]" (keyword LET) (keyword OPEN) (override ovf) longident_loc lid (keyword IN) (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x (* used in [Pexp_apply] *) and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li (* (match view_fixity_of_exp x with *) (* |`Normal -> longident_loc f li *) (* | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) *) | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(%s@;%a)" (keyword MODULE) (module_expr ctxt) me | Pexp_newtype (lid, e) -> pp f "%s@;(%s@;%s)@;->@;%a" (keyword FUN) (keyword TYPE) lid.txt (expression ctxt) e | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (option (core_type ctxt) ~first:" : " ~last:" ") cto1 (* no sep hint*) (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e.pexp_desc with | Pexp_ident {txt;_} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in pp f "@[<hv0>@[<hv2>{@;%a%a@]@;}@]"(* "@[<hov2>{%a%a}@]" *) (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> pp f "@[<2>%s@;%a@;%s@;%a@;%s@]" (keyword WHILE) (expression ctxt) e1 (keyword DO) (expression ctxt) e2 (keyword DONE) | Pexp_for (s, e1, e2, df, e3) -> let expression = expression ctxt in pp f "@[<hv0>@[<hv2>@[<2>%s %a =@;%a@;%a%a@;%s@]@;%a@]@;%s@]" (keyword FOR) (pattern ctxt) s expression e1 direction_flag df expression e2 (keyword DO) expression e3 (keyword DONE) | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f (s, e) = pp f "@[<2>[@@%s@ %a]@]" s.txt (payload ctxt) e and item_attribute ctxt f (s, e) = pp f "@[<2>[@@@@%s@ %a]@]" s.txt (payload ctxt) e and floating_attribute ctxt f (s, e) = pp f "@[<2>[@@@@@@%s@ %a]@]" s.txt (payload ctxt) e and value_description ctxt f x = (* note: value_description has an attribute field, but they're already printed by the callers this method *) pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f ext = pp f "@[<hov2>%s@ %a@]" (keyword EXCEPTION) (extension_constructor ctxt) ext and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = let class_type_field f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>%s@ %a@]%a" (keyword INHERIT) (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>%s @ %a%a%s@ :@ %a@]%a" (keyword VAL) mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>%s %a %a%s :@;%a@]%a" (keyword METHOD) private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>%s@ %a@ =@ %a@]%a" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes in pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f ct -> match ct.ptyp_desc with | Ptyp_any -> () | _ -> pp f " (%a)" (core_type ctxt) ct) ct (list class_type_field ~sep:"@;") l (* call [class_signature] called by [class_signature] *) and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (ovf, lid, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override ovf) longident_loc lid (class_type ctxt) e (* [class type a = object end] *) and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration (Printf.sprintf "%s %s" (keyword CLASS) (keyword TYPE)) f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration (Printf.sprintf "%s %s" (keyword CLASS) (keyword TYPE))) x (list ~sep:"@," (class_type_declaration (keyword AND))) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>%s@ %s@ %a%a@]%a" (keyword INHERIT) (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>%s%s %a%s =@;%a@]%a" (keyword VAL) (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>%s %s %a %s :@;%a@]%a" (keyword METHOD) (keyword VIRTUAL) private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>%s %s %a%s :@ %a@]%a" (keyword VAL) (keyword VIRTUAL) mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s;ppat_loc=Location.none;ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>%s%s %a%a@]%a" (keyword METHOD) (override ovf) private_flag pf (fun f e -> match e.pexp_desc with | Pexp_poly (e, Some ct) -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | Pexp_poly (e,None) -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>%s %a =@;%a@]%a" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>%s@ %a@]%a" (keyword INITIALIZER) (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>%s%a@;%a@]@;%s@]" (keyword OBJECT) (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l (keyword END) and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (ovf, lid, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override ovf) longident_loc lid (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (_, None, mt2) -> pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (s, Some mt1, mt2) -> if s.txt = "_" then pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 else pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" s.txt (module_type ctxt) mt1 (module_type ctxt) mt2 | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> let with_constraint f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a =@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "%s %a =@ %a" (keyword MODULE) longident_loc li longident_loc li2; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a :=@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "%s %a :=@ %a" (keyword MODULE) longident_loc li longident_loc li2 in pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list with_constraint ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(%s %a)" (keyword MODULE) longident_loc li; | Pmty_signature (s) -> pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *) (list (signature_item ctxt)) s (* FIXME wrong indentation*) | Pmty_typeof me -> pp f "@[<hov2>%s@ type@ of@ %a@]" (keyword MODULE) (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>%s@ %s@ =@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>%s@ %s@ :@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_lid (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>%s@ type@ %s%a@]%a" (keyword MODULE) s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" pmd.pmd_name.txt (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>%s@ rec@ %s:@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>%s@;@[<0>%a@]@;<1 -2>%s@]" (keyword STRUCT) (list (structure_item ctxt) ~sep:"@\n") s (keyword END) | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (_, None, me) -> pp f "%s ()@;->@;%a" (keyword FUNCTOR) (module_expr ctxt) me | Pmod_functor (s, Some mt, me) -> pp f "%s@ (%s@ :@ %a)@;->@;%a" (keyword FUNCTOR) s.txt (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(%s@ %a)" (keyword VAL) (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":"; core_type ctxt f x | PSig x -> pp f ":"; signature ctxt f x | PPat (x, None) -> pp f "?"; pattern ctxt f x | PPat (x, Some e) -> pp f "?"; pattern ctxt f x; pp f " %s " (keyword WHEN); expression ctxt f e (* transform [f = fun g h -> ..] to [f g h = ... ] could be improved *) and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = (* .pvb_attributes have already been printed by the caller, #bindings *) let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, { pexp_desc = Pexp_constraint (e, rty) }) -> if label=Nolabel then pp f "%a@ : %a@ %a" (simple_pattern ctxt) p (core_type ctxt) rty pp_print_pexp_function e else pp f "%a@ : %a@ %a" (label_exp ctxt) (label,eo,p) (core_type ctxt) rty pp_print_pexp_function e | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(%s@ %s)@ %a" (keyword TYPE) str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p.ppat_desc with | Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}) -> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e.pexp_desc with | Pexp_newtype (tyvar, e) -> gadt_exp (tyvar :: tyvars) e | Pexp_constraint (e, ct) -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match (x.pexp_desc,p.ppat_desc) with special case for the first begin match ty.ptyp_desc with | Ptyp_poly _ -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | (_, Ppat_var _) -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end (* [in] is not printed *) and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]@ %a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding (keyword LET) rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding (keyword LET) rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper me = match me.pmod_desc with | Pmod_functor(s,mt,me') when me.pmod_attributes = [] -> if mt = None then pp f "()" else Misc.may (pp f "(%s:%a)" s.txt (module_type ctxt)) mt; module_helper me' | _ -> me in pp f "@[<hov2>%s %s%a@]%a" (keyword MODULE) x.pmb_name.txt (fun f me -> let me = module_helper me in match me.pmod_desc with | Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)) when me.pmod_attributes = [] -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>%s%s@;%a@]%a" (keyword OPEN) (override od.popen_override) longident_loc od.popen_lid (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>%s@ %s@ %s%a@]%a" (keyword MODULE) (keyword TYPE) s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc cl = match cl.pcl_desc with | Pcl_fun (l, eo, p, cl') when cl.pcl_attributes = [] -> loop ((l,eo,p) :: acc) cl' | _ -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl.pcl_desc with | Pcl_constraint (cl', ct) when cl.pcl_attributes = [] -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration (keyword CLASS) f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration (keyword CLASS)) x (list ~sep:"@," (class_declaration (keyword AND))) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>%s@ %a@ :@ %a@]%a" (keyword EXTERNAL) protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>%s@ %a@]%a" (keyword INCLUDE) (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ %s@ %s:%a@ =@ %a@]%a" (keyword AND) pmb.pmb_name.txt (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | _ -> assert false in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>%s@ %s@ %s:%a@ =@ %a@]%a@ %a@]" (keyword MODULE) (keyword REC) pmb.pmb_name.txt (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, a) = pp f "%s%a" (type_variance a) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l and type_def_list ctxt f (rf, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else " =" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl (keyword TYPE) rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl (keyword TYPE) rf) x (list ~sep:"@," (type_decl (keyword AND) Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = (* type_declaration has an attribute field, but it's been printed by the caller of this method *) let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;%s" (keyword PRIVATE) in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> pp f "%t%t@\n%a" intro priv (list ~sep:"@\n" constructor_declaration) xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ %s@ %a@ =@ %a@]" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>%s %a%a += %a@ %a@]%a" (keyword TYPE) (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;%s@;%a" (keyword OF) (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;%s@;%a" (keyword OF) (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a@;%a" name (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(l, r) -> constructor_declaration ctxt f (x.pext_name.txt, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s%a@;=@;%a" x.pext_name.txt (attributes ctxt) x.pext_attributes longident_loc li and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs ( option (expression ctxt) ~firstf:(fun () -> Scanf.format_from_string (Printf.sprintf "@;%s@;" (keyword WHEN)) "")) pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e.pexp_desc with | Pexp_ident {txt=Lident l;_} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x with | Pdir_none -> () | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s (* pp_open_hvbox f 0; *) (* pp_print_list structure_item f s ; *) pp_close_box f ( ) ; | Ptop_dir (s, da) -> pp f "@[<hov2>#%s@ %a@]" s directive_argument da (* pp f "@[<hov2>#%s@ %a@]" s directive_argument da *) let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt let exp_ast ast = let fmt = Format.str_formatter in Printast.expression 0 fmt ast; Format.flush_str_formatter () let contract_ast ast = let fmt = Format.str_formatter in Printast.structure 0 fmt ast; Format.flush_str_formatter ()
null
https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/liquidity/ocaml/liquidOCamlPrinter.ml
ocaml
************************************************************************ OCaml Fabrice Le Fessant, INRIA Saclay en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Printing code expressions type fixity = Infix| Prefix which identifiers are in fact operators needing parentheses some infixes need spaces around parens to avoid clashes with comment syntax add parentheses to binders when they are in fact infix or prefix operators variance encoding: need to sync up with the [parser.mly] trailing space trailing space added c ['a,'b] space otherwise parenthesize "%a%a@;" Cf #7200: print [>] correctly FIXME desugar the syntax sugar *******************pattern******************* RA RA single case pattern parens needed here "try@;@[<2>%a@]@\nwith@\n%a" pp f "@[<2>let %a%a in@;<1 -2>%a@]" (*no identation here, a new line See #7200: avoid turning (~- 1) into (- 1) which is parsed as an int literal reset here only because [function,match,try,sequence] are lower priority Not efficient FIXME @;@[<2>else@ %a@]@] pp f "()" Pexp_poly: impossible but we should print it anyway, rather than assert false used in [Pexp_apply] (match view_fixity_of_exp x with |`Normal -> longident_loc f li | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) no sep hint "@[<hov2>{%a%a}@]" note: value_description has an attribute field, but they're already printed by the callers this method call [class_signature] called by [class_signature] [class type a = object end] "@[<hov>sig@ %a@ end@]" FIXME wrong indentation transform [f = fun g h -> ..] to [f g h = ... ] could be improved .pvb_attributes have already been printed by the caller, #bindings [in] is not printed type_declaration has an attribute field, but it's been printed by the caller of this method pp_open_hvbox f 0; pp_print_list structure_item f s ; pp f "@[<hov2>#%s@ %a@]" s directive_argument da
, OCamlPro , University of Pennsylvania Copyright 2007 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the module Parser = LiquidOCamlParser Original Code from Ber - metaocaml , modified for 3.12.0 and fixed Authors : , Extensive Rewrite : : University of Pennsylvania TODO more fine - grained precedence pretty - printing open Asttypes open Parser open Format open Location open Longident open Parsetree open Ast_helper let keyword token = LiquidOCamlLexer.keyword_of_token token let token keyword = LiquidOCamlLexer.token_of_keyword keyword let prefix_symbols = [ '!'; '?'; '~' ] ;; let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%' ] let special_infix_strings = ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!=" ] let is_special_infix_string s = try match token s with | OR | INFIXOP3 _ | INFIXOP4 _ -> true | _ -> false with Not_found -> List.mem s [ ":="; "!="; "::" ] determines if the string is an infix string . checks backwards , first allowing a renaming postfix ( " _ 102 " ) which may have resulted from - > Texp - > translation , then checking if all the characters in the beginning of the string are valid infix characters . checks backwards, first allowing a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp translation, then checking if all the characters in the beginning of the string are valid infix characters. *) let fixity_of_string = function | s when is_special_infix_string s -> `Infix s | s when List.mem s.[0] infix_symbols -> `Infix s | s when List.mem s.[0] prefix_symbols -> `Prefix s | _ -> `Normal let view_fixity_of_exp = function | {pexp_desc = Pexp_ident {txt=Lident l;_};_} -> fixity_of_string l | _ -> `Normal let is_infix = function | `Infix _ -> true | _ -> false let needs_parens txt = is_infix (fixity_of_string txt) || List.mem txt.[0] prefix_symbols let needs_spaces txt = txt.[0]='*' || txt.[String.length txt - 1] = '*' let protect_ident ppf txt = let format : (_, _, _) format = if not (needs_parens txt) then "%s" else if needs_spaces txt then "(@;%s@;)" else "(%s)" in fprintf ppf format txt let protect_longident ppf print_longident longprefix txt = let format : (_, _, _) format = if not (needs_parens txt) then "%a.%s" else if needs_spaces txt then "%a.(@;%s@;)" else "%a.(%s)" in fprintf ppf format print_longident longprefix txt type space_formatter = (unit, Format.formatter, unit) format let override = function | Override -> "!" | Fresh -> "" let type_variance = function | Invariant -> "" | Covariant -> "+" | Contravariant -> "-" type construct = [ `cons of expression list | `list of expression list | `nil | `normal | `simple of Longident.t | `tuple ] let view_expr x = match x.pexp_desc with | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil | Pexp_construct ( {txt= Lident"::";_},Some _) -> let rec loop exp acc = match exp with | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);_} -> (List.rev acc,true) | {pexp_desc= Pexp_construct ({txt=Lident "::";_}, Some ({pexp_desc= Pexp_tuple([e1;e2]);_}));_} -> loop e2 (e1::acc) | e -> (List.rev (e::acc),false) in let (ls,b) = loop x [] in if b then `list ls else `cons ls | Pexp_construct (x,None) -> `simple (x.txt) | _ -> `normal let is_simple_construct :construct -> bool = function | `nil | `tuple | `list _ | `simple _ -> true | `cons _ | `normal -> false let pp = fprintf type ctxt = { pipe : bool; semi : bool; ifthenelse : bool; } let reset_ctxt = { pipe=false; semi=false; ifthenelse=false } let under_pipe ctxt = { ctxt with pipe=true } let under_semi ctxt = { ctxt with semi=true } let under_ifthenelse ctxt = { ctxt with ifthenelse=true } let reset_semi = with semi = false } let reset_ifthenelse = with ifthenelse = false } let = with pipe = false } let reset_semi ctxt = { ctxt with semi=false } let reset_ifthenelse ctxt = { ctxt with ifthenelse=false } let reset_pipe ctxt = { ctxt with pipe=false } *) let list : 'a . ?sep:space_formatter -> ?first:space_formatter -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit = fun ?sep ?first ?last fu f xs -> let first = match first with Some x -> x |None -> ("": _ format6) and last = match last with Some x -> x |None -> ("": _ format6) and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in let aux f = function | [] -> () | [x] -> fu f x | xs -> let rec loop f = function | [x] -> fu f x | x::xs -> fu f x; pp f sep; loop f xs; | _ -> assert false in begin pp f first; loop f xs; pp f last; end in aux f xs let option : 'a. ?first:space_formatter -> ?firstf: (unit -> space_formatter) -> ?last:space_formatter -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit = fun ?first ?firstf ?last fu f a -> let last = match last with Some x -> x | None -> ("": _ format6) in match a with | None -> () | Some x -> let first = match first with Some x -> x | None -> match firstf with | None -> ("": _ format6) | Some f -> f () in pp f first; fu f x; pp f last let paren: 'a . ?first:space_formatter -> ?last:space_formatter -> bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit = fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x -> if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")") else fu f x let rec longident f = function | Lident s -> protect_ident f s | Ldot(y,s) -> protect_longident f longident y s | Lapply (y,s) -> pp f "%a(%a)" longident y longident s let longident_loc f x = pp f "%a" longident x.txt let constant f = function | Pconst_char i -> pp f "%C" i | Pconst_string (i, None) -> pp f "%S" i | Pconst_string (i, Some delim) -> pp f "{%s|%s|%s}" delim i delim | Pconst_integer (i, None) -> paren (i.[0]='-') (fun f -> pp f "%s") f i | Pconst_integer (s, Some '\232') -> pp f "%s" s | Pconst_integer (s, Some '\233') -> pp f "%s" s | Pconst_integer (s, Some '\234') -> pp f "%s" s | Pconst_integer (s, Some '\235') -> pp f "%s" s | Pconst_integer (s, Some '\236') -> pp f "%s" s | Pconst_integer (s, Some '\237') -> pp f "%s" s | Pconst_integer (i, Some m) -> paren (i.[0]='-') (fun f (i, m) -> if m = '\231' then pp f "%s%s" i (LiquidOptions.curreny ()) else pp f "%s%c" i m) f (i,m) | Pconst_float (i, None) -> paren (i.[0]='-') (fun f -> pp f "%s") f i | Pconst_float (i, Some m) -> paren (i.[0]='-') (fun f (i,_m) -> if m = '\231' then pp f "%s%s" i (LiquidOptions.curreny ()) else pp f "%s%c" i m) f (i,m) let mutable_flag f = function | Immutable -> () | Mutable -> pp f "%s@;" (keyword MUTABLE) let virtual_flag f = function | Concrete -> () | Virtual -> pp f "%s@;" (keyword VIRTUAL) let rec_flag f rf = match rf with | Nonrecursive -> () | Recursive -> pp f "%s " (keyword REC) let nonrec_flag f rf = match rf with | Nonrecursive -> pp f "%s " (keyword NONREC) | Recursive -> () let direction_flag f = function | Upto -> pp f "%s@ " (keyword TO) | Downto -> pp f "%s@ " (keyword DOWNTO) let private_flag f = function | Public -> () | Private -> pp f "%s@ " (keyword PRIVATE) let constant_string f s = pp f "%S" s let tyvar f str = pp f "'%s" str let tyvar_loc f str = pp f "'%s" str.txt let string_quot f x = pp f "`%s" x let rec class_params_def ctxt f = function | [] -> () | l -> (list (type_param ctxt) ~sep:",") l and type_with_label ctxt f (label, c) = match label with | Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c | Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c and core_type ctxt f x = if x.ptyp_attributes <> [] then begin pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]} (attributes ctxt) x.ptyp_attributes end else match x.ptyp_desc with | Ptyp_arrow (l, ct1, ct2) -> FIXME remove parens later (type_with_label ctxt) (l,ct1) (core_type ctxt) ct2 | Ptyp_alias (ct, s) -> pp f "@[<2>%a@;as@;'%s@]" (core_type1 ctxt) ct s | Ptyp_poly (sl, ct) -> pp f "@[<2>%a%a@]" (fun f l -> pp f "%a" (fun f l -> match l with | [] -> () | _ -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") l) l) sl (core_type ctxt) ct | _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x and core_type1 ctxt f x = if x.ptyp_attributes <> [] then core_type ctxt f x else match x.ptyp_desc with | Ptyp_any -> pp f "_"; | Ptyp_var s -> tyvar f s; | Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l | Ptyp_constr (li, l) -> (fun f l -> match l with |[] -> () |[x]-> pp f "%a@;" (core_type1 ctxt) x | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l) l longident_loc li | Ptyp_variant (l, closed, low) -> let type_variant_helper f x = match x with | Rtag (l, attrs, _, ctl) -> pp f "@[<2>%a%a@;%a@]" string_quot l.txt (fun f l -> match l with |[] -> () | _ -> pp f "@;of@;%a" (list (core_type ctxt) ~sep:"&") ctl) ctl (attributes ctxt) attrs | Rinherit ct -> core_type ctxt f ct in pp f "@[<2>[%a%a]@]" (fun f l -> match l, closed with | [], Closed -> () | _ -> pp f "%s@;%a" (match (closed,low) with | (Closed,None) -> "" | (Open,_) -> ">") (list type_variant_helper ~sep:"@;<1 -2>| ") l) l (fun f low -> match low with |Some [] |None -> () |Some xs -> pp f ">@ %a" (list string_quot) xs) low | Ptyp_object (l, o) -> let core_field_type f = function | Otag (l, attrs, ct) -> pp f "@[<hov2>%s: %a@ %a@ @]" l.txt Cf # 7200 | Oinherit ct -> pp f "@[<hov2>%a@ @]" (core_type ctxt) ct in let field_var f = function | Asttypes.Closed -> () | Asttypes.Open -> match l with | [] -> pp f ".." | _ -> pp f " ;.." in pp f "@[<hov2><@ %a%a@ > @]" (list core_field_type ~sep:";") l Cf # 7200 FIXME pp f "@[<hov2>%a#%a@]" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l longident_loc li | Ptyp_package (lid, cstrs) -> let aux f (s, ct) = pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in (match cstrs with |[] -> pp f "@[<hov2>(%s@ %a)@]" (keyword MODULE) longident_loc lid |_ -> pp f "@[<hov2>(%s@ %a@ with@ %a)@]" (keyword MODULE) longident_loc lid (list aux ~sep:"@ and@ ") cstrs) | Ptyp_extension e -> extension ctxt f e | _ -> paren true (core_type ctxt) f x be cautious when use [ pattern ] , [ ] is preferred and pattern ctxt f x = only consider ( ( A|B)|C ) | {ppat_desc= Ppat_or (p1,p2);_} -> list_of_pattern (p2::acc) p1 | x -> x::acc in if x.ppat_attributes <> [] then begin pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]} (attributes ctxt) x.ppat_attributes end else match x.ppat_desc with | Ppat_alias (p, s) -> pp f "@[<hov0>%a@]" (list ~sep:"@,|" (pattern ctxt)) (list_of_pattern [] x) | _ -> pattern1 ctxt f x and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit = let rec pattern_list_helper f = function | {ppat_desc = Ppat_construct ({ txt = Lident("::") ;_}, Some ({ppat_desc = Ppat_tuple([pat1; pat2]);_})); _} -> | p -> pattern1 ctxt f p in if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> simple_pattern ctxt f x | Ppat_construct (({txt;_} as li), po) -> FIXME The third field always false if txt = Lident "::" then pp f "%a" pattern_list_helper x else (match po with | Some x -> pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x | None -> pp f "%a@;"longident_loc li ) | _ -> simple_pattern ctxt f x and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit = if x.ppat_attributes <> [] then pattern ctxt f x else match x.ppat_desc with | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), _) -> pp f "%s" x | Ppat_any -> pp f "_"; | Ppat_var ({txt = txt;_}) -> protect_ident f txt | Ppat_array l -> pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l | Ppat_unpack (s) -> pp f "(%s@ %s)@ " (keyword MODULE) s.txt | Ppat_type li -> pp f "#%a" longident_loc li | Ppat_record (l, closed) -> let longident_x_pattern f (li, p) = match (li,p.ppat_desc) with | ({txt=Lident s;_ },Ppat_var {txt;_} ) when s = txt -> pp f "@[<2>%a@]" longident_loc li | _ -> pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p in begin match closed with | Closed -> pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l | _ -> pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l end | Ppat_tuple l -> | Ppat_constant (c) -> pp f "%a" constant c | Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2 | Ppat_variant (l,None) -> pp f "`%s" l | Ppat_constraint (p, ct) -> pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct | Ppat_lazy p -> pp f "@[<2>(lazy@;%a)@]" (pattern1 ctxt) p | Ppat_exception p -> pp f "@[<2>%s@;%a@]" (keyword EXCEPTION) (pattern1 ctxt) p | Ppat_extension e -> extension ctxt f e | Ppat_open (lid, p) -> let with_paren = match p.ppat_desc with | Ppat_array _ | Ppat_record _ | Ppat_construct (({txt=Lident ("()"|"[]");_}), _) -> false | _ -> true in pp f "@[<2>%a.%a @]" longident_loc lid (paren with_paren @@ pattern1 ctxt) p | _ -> paren true (pattern ctxt) f x and label_exp ctxt f (l,opt,p) = match l with | Nolabel -> pp f "%a@ " (simple_pattern ctxt) p | Optional rest -> begin match p.ppat_desc with | Ppat_var {txt;_} when txt = rest -> (match opt with | Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o | None -> pp f "?%s@ " rest) | _ -> (match opt with | Some o -> pp f "?%s:(%a=@;%a)@;" rest (pattern1 ctxt) p (expression ctxt) o | None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p) end | Labelled l -> match p.ppat_desc with | Ppat_var {txt;_} when txt = l -> pp f "~%s@;" l | _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p and sugar_expr ctxt f e = if e.pexp_attributes <> [] then false else match e.pexp_desc with | Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _}; pexp_attributes=[]; _}, args) when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin match id, List.map snd args with | Lident "!", [e] -> pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true | Ldot (path, ("get"|"set" as func)), a :: other_args -> begin let print left right print_index indexes rem_args = match func, rem_args with | "get", [] -> pp f "@[%a.%s%a%s@]" (simple_expr ctxt) a left (list ~sep:"," print_index) indexes right; true | "set", [v] -> pp f "@[%a.%s%a%s@ <-@;<1 2>%a@]" (simple_expr ctxt) a left (list ~sep:"," print_index) indexes right (simple_expr ctxt) v; true | _ -> false in match path, other_args with | Lident "Array", i :: rest -> print "(" ")" (expression ctxt) [i] rest | Lident "String", i :: rest -> print "[" "]" (expression ctxt) [i] rest | Ldot (Lident "Bigarray", "Array1"), i1 :: rest -> print "{" "}" (simple_expr ctxt) [i1] rest | Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest -> print "{" "}" (simple_expr ctxt) [i1; i2] rest | Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest -> print "{" "}" (simple_expr ctxt) [i1; i2; i3] rest | Ldot (Lident "Bigarray", "Genarray"), {pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest -> print "{" "}" (simple_expr ctxt) indexes rest | _ -> false end | _ -> false end | _ -> false and expression ctxt f x = if x.pexp_attributes <> [] then pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes else match x.pexp_desc with | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _ when ctxt.pipe || ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse -> paren true (expression reset_ctxt) f x | Pexp_let _ | Pexp_letmodule _ | Pexp_open _ | Pexp_letexception _ when ctxt.semi -> paren true (expression reset_ctxt) f x | Pexp_fun (l, e0, p, e) -> pp f "@[<2>%s@;%a@;->@;%a@]" (keyword FUN) (label_exp ctxt) (l, e0, p) (expression ctxt) e | Pexp_function l -> pp f "@[<hv>%s%a@]" (keyword FUNCTION) (case_list ctxt) l | Pexp_match (e, l) -> pp f "@[<hv0>@[<hv0>@[<2>%s %a@]@ %s@]%a@]" (keyword MATCH) (expression reset_ctxt) e (keyword WITH) (case_list ctxt) l | Pexp_try (e, l) -> pp f "@[<0>@[<hv2>%s@ %a@]@ @[<0>%s%a@]@]" (keyword TRY) (expression reset_ctxt) e (keyword WITH) (case_list ctxt) l | Pexp_let (rf, l, e) -> rec_flag rf pp f "@[<2>%a %s@;<1 -2>%a@]" (bindings reset_ctxt) (rf,l) (keyword IN) (expression ctxt) e | Pexp_apply (e, l) -> begin if not (sugar_expr ctxt f x) then match view_fixity_of_exp e with | `Infix s -> begin match l with | [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] -> FIXME associativity label_x_expression_param pp f "@[<2>%a@;%s@;%a@]" (label_x_expression_param reset_ctxt) arg1 s (label_x_expression_param ctxt) arg2 | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | `Prefix s -> let s = if List.mem s ["~+";"~-";"~+.";"~-."] && (match l with |[(_,{pexp_desc=Pexp_constant _})] -> false | _ -> true) then String.sub s 1 (String.length s -1) else s in begin match l with | [(Nolabel, x)] -> pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x | _ -> pp f "@[<2>%a %a@]" (simple_expr ctxt) e (list (label_x_expression_param ctxt)) l end | _ -> pp f "@[<hov2>%a@]" begin fun f (e,l) -> pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l end (e,l) end | Pexp_construct (li, Some eo) (match view_expr x with | `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;" | `normal -> pp f "@[<2>%a@;%a@]" longident_loc li (simple_expr ctxt) eo | _ -> assert false) | Pexp_setfield (e1, li, e2) -> pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 | Pexp_ifthenelse (e1, e2, eo) -> let fmt:(_,_,_)format = Scanf.format_from_string (Printf.sprintf "@[<hv0>@[<2>%s@ %%a@]@;@[<2>%s@ %%a@]%%a@]" (keyword IF) (keyword THEN) ) "%a%a%a" in let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2 (fun f eo -> match eo with | Some x -> pp f "@;@[<2>%s@;%a@]" (keyword ELSE) (expression (under_semi ctxt)) x | Pexp_sequence _ -> let rec sequence_helper acc = function | {pexp_desc=Pexp_sequence(e1,e2);_} -> sequence_helper (e1::acc) e2 | v -> List.rev (v::acc) in let lst = sequence_helper [] x in pp f "@[<hv>%a@]" (list (expression (under_semi ctxt)) ~sep:";@;") lst | Pexp_new (li) -> pp f "@[<hov2>%s@ %a@]" (keyword NEW) longident_loc li; | Pexp_setinstvar (s, e) -> pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e FIXME let string_x_expression f (s, e) = pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in pp f "@[<hov2>{<%a>}@]" (list string_x_expression ~sep:";" ) l; | Pexp_letmodule (s, me, e) -> pp f "@[<hov2>%s@ %s@ %s@ =@ %a@ %s@ %a@]" (keyword LET) (keyword MODULE) s.txt (module_expr reset_ctxt) me (keyword IN) (expression ctxt) e | Pexp_letexception (cd, e) -> pp f "@[<hov2>%s@ %s@ %a@ %s@ %a@]" (keyword LET) (keyword EXCEPTION) (extension_constructor ctxt) cd (keyword IN) (expression ctxt) e | Pexp_assert e -> pp f "@[<hov2>%s@ %a@]" (keyword ASSERT) (simple_expr ctxt) e | Pexp_lazy (e) -> pp f "@[<hov2>%s@ %a@]" (keyword LAZY) (simple_expr ctxt) e | Pexp_poly (e, None) -> pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e | Pexp_poly (e, Some ct) -> pp f "@[<hov2>(!poly!@ %a@ : %a)@]" (simple_expr ctxt) e (core_type ctxt) ct | Pexp_open (ovf, lid, e) -> pp f "@[<2>%s %s%s %a %s@;%a@]" (keyword LET) (keyword OPEN) (override ovf) longident_loc lid (keyword IN) (expression ctxt) e | Pexp_variant (l,Some eo) -> pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo | Pexp_extension e -> extension ctxt f e | Pexp_unreachable -> pp f "." | _ -> expression1 ctxt f x and expression1 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_object cs -> pp f "%a" (class_structure ctxt) cs | _ -> expression2 ctxt f x and expression2 ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_field (e, li) -> pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt | _ -> simple_expr ctxt f x and simple_expr ctxt f x = if x.pexp_attributes <> [] then expression ctxt f x else match x.pexp_desc with | Pexp_construct _ when is_simple_construct (view_expr x) -> (match view_expr x with | `nil -> pp f "[]" | `tuple -> pp f "()" | `list xs -> pp f "@[<hv0>[%a]@]" (list (expression (under_semi ctxt)) ~sep:";@;") xs | `simple x -> longident f x | _ -> assert false) | Pexp_ident li -> longident_loc f li | Pexp_constant c -> constant f c; | Pexp_pack me -> pp f "(%s@;%a)" (keyword MODULE) (module_expr ctxt) me | Pexp_newtype (lid, e) -> pp f "%s@;(%s@;%s)@;->@;%a" (keyword FUN) (keyword TYPE) lid.txt (expression ctxt) e | Pexp_tuple l -> pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l | Pexp_constraint (e, ct) -> pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_coerce (e, cto1, ct) -> pp f "(%a%a :> %a)" (expression ctxt) e (core_type ctxt) ct | Pexp_variant (l, None) -> pp f "`%s" l | Pexp_record (l, eo) -> let longident_x_expression f ( li, e) = match e.pexp_desc with | Pexp_ident {txt;_} when li.txt = txt -> pp f "@[<hov2>%a@]" longident_loc li | _ -> pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e in (option ~last:" with@;" (simple_expr ctxt)) eo (list longident_x_expression ~sep:";@;") l | Pexp_array (l) -> pp f "@[<0>@[<2>[|%a|]@]@]" (list (simple_expr (under_semi ctxt)) ~sep:";") l | Pexp_while (e1, e2) -> pp f "@[<2>%s@;%a@;%s@;%a@;%s@]" (keyword WHILE) (expression ctxt) e1 (keyword DO) (expression ctxt) e2 (keyword DONE) | Pexp_for (s, e1, e2, df, e3) -> let expression = expression ctxt in pp f "@[<hv0>@[<hv2>@[<2>%s %a =@;%a@;%a%a@;%s@]@;%a@]@;%s@]" (keyword FOR) (pattern ctxt) s expression e1 direction_flag df expression e2 (keyword DO) expression e3 (keyword DONE) | _ -> paren true (expression ctxt) f x and attributes ctxt f l = List.iter (attribute ctxt f) l and item_attributes ctxt f l = List.iter (item_attribute ctxt f) l and attribute ctxt f (s, e) = pp f "@[<2>[@@%s@ %a]@]" s.txt (payload ctxt) e and item_attribute ctxt f (s, e) = pp f "@[<2>[@@@@%s@ %a]@]" s.txt (payload ctxt) e and floating_attribute ctxt f (s, e) = pp f "@[<2>[@@@@@@%s@ %a]@]" s.txt (payload ctxt) e and value_description ctxt f x = pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type (fun f x -> if x.pval_prim <> [] then pp f "@ =@ %a" (list constant_string) x.pval_prim ) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e and item_extension ctxt f (s, e) = pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e and exception_declaration ctxt f ext = pp f "@[<hov2>%s@ %a@]" (keyword EXCEPTION) (extension_constructor ctxt) ext and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} = let class_type_field f x = match x.pctf_desc with | Pctf_inherit (ct) -> pp f "@[<2>%s@ %a@]%a" (keyword INHERIT) (class_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_val (s, mf, vf, ct) -> pp f "@[<2>%s @ %a%a%s@ :@ %a@]%a" (keyword VAL) mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_method (s, pf, vf, ct) -> pp f "@[<2>%s %a %a%s :@;%a@]%a" (keyword METHOD) private_flag pf virtual_flag vf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pctf_attributes | Pctf_constraint (ct1, ct2) -> pp f "@[<2>%s@ %a@ =@ %a@]%a" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pctf_attributes | Pctf_attribute a -> floating_attribute ctxt f a | Pctf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pctf_attributes in pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]" (fun f ct -> match ct.ptyp_desc with | Ptyp_any -> () | _ -> pp f " (%a)" (core_type ctxt) ct) ct (list class_type_field ~sep:"@;") l and class_type ctxt f x = match x.pcty_desc with | Pcty_signature cs -> class_signature ctxt f cs; attributes ctxt f x.pcty_attributes | Pcty_constr (li, l) -> pp f "%a%a%a" (fun f l -> match l with | [] -> () | _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l longident_loc li (attributes ctxt) x.pcty_attributes | Pcty_arrow (l, co, cl) -> FIXME remove parens later (type_with_label ctxt) (l,co) (class_type ctxt) cl | Pcty_extension e -> extension ctxt f e; attributes ctxt f x.pcty_attributes | Pcty_open (ovf, lid, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override ovf) longident_loc lid (class_type ctxt) e and class_type_declaration_list ctxt f l = let class_type_declaration kwd f x = let { pci_params=ls; pci_name={ txt; _ }; _ } = x in pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in match l with | [] -> () | [x] -> class_type_declaration (Printf.sprintf "%s %s" (keyword CLASS) (keyword TYPE)) f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_type_declaration (Printf.sprintf "%s %s" (keyword CLASS) (keyword TYPE))) x (list ~sep:"@," (class_type_declaration (keyword AND))) xs and class_field ctxt f x = match x.pcf_desc with | Pcf_inherit (ovf, ce, so) -> pp f "@[<2>%s@ %s@ %a%a@]%a" (keyword INHERIT) (override ovf) (class_expr ctxt) ce (fun f so -> match so with | None -> (); | Some (s) -> pp f "@ as %s" s.txt ) so (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_concrete (ovf, e)) -> pp f "@[<2>%s%s %a%s =@;%a@]%a" (keyword VAL) (override ovf) mutable_flag mf s.txt (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_virtual ct) -> pp f "@[<2>%s %s %a %s :@;%a@]%a" (keyword METHOD) (keyword VIRTUAL) private_flag pf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_val (s, mf, Cfk_virtual ct) -> pp f "@[<2>%s %s %a%s :@ %a@]%a" (keyword VAL) (keyword VIRTUAL) mutable_flag mf s.txt (core_type ctxt) ct (item_attributes ctxt) x.pcf_attributes | Pcf_method (s, pf, Cfk_concrete (ovf, e)) -> let bind e = binding ctxt f {pvb_pat= {ppat_desc=Ppat_var s;ppat_loc=Location.none;ppat_attributes=[]}; pvb_expr=e; pvb_attributes=[]; pvb_loc=Location.none; } in pp f "@[<2>%s%s %a%a@]%a" (keyword METHOD) (override ovf) private_flag pf (fun f e -> match e.pexp_desc with | Pexp_poly (e, Some ct) -> pp f "%s :@;%a=@;%a" s.txt (core_type ctxt) ct (expression ctxt) e | Pexp_poly (e,None) -> bind e | _ -> bind e) e (item_attributes ctxt) x.pcf_attributes | Pcf_constraint (ct1, ct2) -> pp f "@[<2>%s %a =@;%a@]%a" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2 (item_attributes ctxt) x.pcf_attributes | Pcf_initializer (e) -> pp f "@[<2>%s@ %a@]%a" (keyword INITIALIZER) (expression ctxt) e (item_attributes ctxt) x.pcf_attributes | Pcf_attribute a -> floating_attribute ctxt f a | Pcf_extension e -> item_extension ctxt f e; item_attributes ctxt f x.pcf_attributes and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } = pp f "@[<hv0>@[<hv2>%s%a@;%a@]@;%s@]" (keyword OBJECT) (fun f p -> match p.ppat_desc with | Ppat_any -> () | Ppat_constraint _ -> pp f " %a" (pattern ctxt) p | _ -> pp f " (%a)" (pattern ctxt) p) p (list (class_field ctxt)) l (keyword END) and class_expr ctxt f x = if x.pcl_attributes <> [] then begin pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]} (attributes ctxt) x.pcl_attributes end else match x.pcl_desc with | Pcl_structure (cs) -> class_structure ctxt f cs | Pcl_fun (l, eo, p, e) -> pp f "fun@ %a@ ->@ %a" (label_exp ctxt) (l,eo,p) (class_expr ctxt) e | Pcl_let (rf, l, ce) -> pp f "%a@ in@ %a" (bindings ctxt) (rf,l) (class_expr ctxt) ce | Pcl_apply (ce, l) -> Cf : # 7200 (class_expr ctxt) ce (list (label_x_expression_param ctxt)) l | Pcl_constr (li, l) -> pp f "%a%a" (fun f l-> if l <>[] then pp f "[%a]@ " (list (core_type ctxt) ~sep:",") l) l longident_loc li | Pcl_constraint (ce, ct) -> pp f "(%a@ :@ %a)" (class_expr ctxt) ce (class_type ctxt) ct | Pcl_extension e -> extension ctxt f e | Pcl_open (ovf, lid, e) -> pp f "@[<2>let open%s %a in@;%a@]" (override ovf) longident_loc lid (class_expr ctxt) e and module_type ctxt f x = if x.pmty_attributes <> [] then begin pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]} (attributes ctxt) x.pmty_attributes end else match x.pmty_desc with | Pmty_functor (_, None, mt2) -> pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2 | Pmty_functor (s, Some mt1, mt2) -> if s.txt = "_" then pp f "@[<hov2>%a@ ->@ %a@]" (module_type1 ctxt) mt1 (module_type ctxt) mt2 else pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" s.txt (module_type ctxt) mt1 (module_type ctxt) mt2 | Pmty_with (mt, []) -> module_type ctxt f mt | Pmty_with (mt, l) -> let with_constraint f = function | Pwith_type (li, ({ptype_params= ls ;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a =@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_module (li, li2) -> pp f "%s %a =@ %a" (keyword MODULE) longident_loc li longident_loc li2; | Pwith_typesubst (li, ({ptype_params=ls;_} as td)) -> let ls = List.map fst ls in pp f "type@ %a %a :=@ %a" (list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") ls longident_loc li (type_declaration ctxt) td | Pwith_modsubst (li, li2) -> pp f "%s %a :=@ %a" (keyword MODULE) longident_loc li longident_loc li2 in pp f "@[<hov2>%a@ with@ %a@]" (module_type1 ctxt) mt (list with_constraint ~sep:"@ and@ ") l | _ -> module_type1 ctxt f x and module_type1 ctxt f x = if x.pmty_attributes <> [] then module_type ctxt f x else match x.pmty_desc with | Pmty_ident li -> pp f "%a" longident_loc li; | Pmty_alias li -> pp f "(%s %a)" (keyword MODULE) longident_loc li; | Pmty_signature (s) -> | Pmty_typeof me -> pp f "@[<hov2>%s@ type@ of@ %a@]" (keyword MODULE) (module_expr ctxt) me | Pmty_extension e -> extension ctxt f e | _ -> paren true (module_type ctxt) f x and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x and signature_item ctxt f x : unit = match x.psig_desc with | Psig_type (rf, l) -> type_def_list ctxt f (rf, l) | Psig_value vd -> let intro = if vd.pval_prim = [] then "val" else "external" in pp f "@[<2>%s@ %a@ :@ %a@]%a" intro protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Psig_typext te -> type_extension ctxt f te | Psig_exception ed -> exception_declaration ctxt f ed | Psig_class l -> let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) = pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (class_type ctxt) x.pci_expr (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_description "class" f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_description "class") x (list ~sep:"@," (class_description "and")) xs end | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias; pmty_attributes=[]; _};_} as pmd) -> pp f "@[<hov>%s@ %s@ =@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt longident_loc alias (item_attributes ctxt) pmd.pmd_attributes | Psig_module pmd -> pp f "@[<hov>%s@ %s@ :@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt (module_type ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes | Psig_open od -> pp f "@[<hov2>open%s@ %a@]%a" (override od.popen_override) longident_loc od.popen_lid (item_attributes ctxt) od.popen_attributes | Psig_include incl -> pp f "@[<hov2>include@ %a@]%a" (module_type ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>%s@ type@ %s%a@]%a" (keyword MODULE) s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Psig_class_type (l) -> class_type_declaration_list ctxt f l | Psig_recmodule decls -> let rec string_x_module_type_list f ?(first=true) l = match l with | [] -> () ; | pmd :: tl -> if not first then pp f "@ @[<hov2>and@ %s:@ %a@]%a" pmd.pmd_name.txt (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes else pp f "@[<hov2>%s@ rec@ %s:@ %a@]%a" (keyword MODULE) pmd.pmd_name.txt (module_type1 ctxt) pmd.pmd_type (item_attributes ctxt) pmd.pmd_attributes; string_x_module_type_list f ~first:false tl in string_x_module_type_list f decls | Psig_attribute a -> floating_attribute ctxt f a | Psig_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and module_expr ctxt f x = if x.pmod_attributes <> [] then pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]} (attributes ctxt) x.pmod_attributes else match x.pmod_desc with | Pmod_structure (s) -> pp f "@[<hv2>%s@;@[<0>%a@]@;<1 -2>%s@]" (keyword STRUCT) (list (structure_item ctxt) ~sep:"@\n") s (keyword END) | Pmod_constraint (me, mt) -> pp f "@[<hov2>(%a@ :@ %a)@]" (module_expr ctxt) me (module_type ctxt) mt | Pmod_ident (li) -> pp f "%a" longident_loc li; | Pmod_functor (_, None, me) -> pp f "%s ()@;->@;%a" (keyword FUNCTOR) (module_expr ctxt) me | Pmod_functor (s, Some mt, me) -> pp f "%s@ (%s@ :@ %a)@;->@;%a" (keyword FUNCTOR) s.txt (module_type ctxt) mt (module_expr ctxt) me | Pmod_apply (me1, me2) -> pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2 Cf : # 7200 | Pmod_unpack e -> pp f "(%s@ %a)" (keyword VAL) (expression ctxt) e | Pmod_extension e -> extension ctxt f e and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x and payload ctxt f = function | PStr [{pstr_desc = Pstr_eval (e, attrs)}] -> pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | PStr x -> structure ctxt f x | PTyp x -> pp f ":"; core_type ctxt f x | PSig x -> pp f ":"; signature ctxt f x | PPat (x, None) -> pp f "?"; pattern ctxt f x | PPat (x, Some e) -> pp f "?"; pattern ctxt f x; pp f " %s " (keyword WHEN); expression ctxt f e and binding ctxt f {pvb_pat=p; pvb_expr=x; _} = let rec pp_print_pexp_function f x = if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x else match x.pexp_desc with | Pexp_fun (label, eo, p, { pexp_desc = Pexp_constraint (e, rty) }) -> if label=Nolabel then pp f "%a@ : %a@ %a" (simple_pattern ctxt) p (core_type ctxt) rty pp_print_pexp_function e else pp f "%a@ : %a@ %a" (label_exp ctxt) (label,eo,p) (core_type ctxt) rty pp_print_pexp_function e | Pexp_fun (label, eo, p, e) -> if label=Nolabel then pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e else pp f "%a@ %a" (label_exp ctxt) (label,eo,p) pp_print_pexp_function e | Pexp_newtype (str,e) -> pp f "(%s@ %s)@ %a" (keyword TYPE) str.txt pp_print_pexp_function e | _ -> pp f "=@;%a" (expression ctxt) x in let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in let is_desugared_gadt p e = let gadt_pattern = match p.ppat_desc with | Ppat_constraint({ppat_desc=Ppat_var _} as pat, {ptyp_desc=Ptyp_poly (args_tyvars, rt)}) -> Some (pat, args_tyvars, rt) | _ -> None in let rec gadt_exp tyvars e = match e.pexp_desc with | Pexp_newtype (tyvar, e) -> gadt_exp (tyvar :: tyvars) e | Pexp_constraint (e, ct) -> Some (List.rev tyvars, e, ct) | _ -> None in let gadt_exp = gadt_exp [] e in match gadt_pattern, gadt_exp with | Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct) when tyvars_str pt_tyvars = tyvars_str e_tyvars -> let ety = Typ.varify_constructors e_tyvars e_ct in if ety = pt_ct then Some (p, pt_tyvars, e_ct, e) else None | _ -> None in if x.pexp_attributes <> [] then pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x else match is_desugared_gadt p x with | Some (p, tyvars, ct, e) -> begin pp f "%a@;: type@;%a.%a@;=@;%a" (simple_pattern ctxt) p (list pp_print_string ~sep:"@;") (tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e end | None -> begin match (x.pexp_desc,p.ppat_desc) with special case for the first begin match ty.ptyp_desc with | Ptyp_poly _ -> pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x | _ -> pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p (core_type ctxt) ty (expression ctxt) x end | (_, Ppat_var _) -> pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x | _ -> pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x end and bindings ctxt f (rf,l) = let binding kwd rf f x = pp f "@[<2>%s %a%a@]@ %a" kwd rec_flag rf (binding ctxt) x (item_attributes ctxt) x.pvb_attributes in match l with | [] -> () | [x] -> binding (keyword LET) rf f x | x::xs -> pp f "@[<v>%a@,%a@]" (binding (keyword LET) rf) x (list ~sep:"@," (binding "and" Nonrecursive)) xs and structure_item ctxt f x = match x.pstr_desc with | Pstr_eval (e, attrs) -> pp f "@[<hov2>;;%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs | Pstr_type (_, []) -> assert false | Pstr_type (rf, l) -> type_def_list ctxt f (rf, l) | Pstr_value (rf, l) -> pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l pp f "@[<2>%a@]" (bindings ctxt) (rf,l) | Pstr_typext te -> type_extension ctxt f te | Pstr_exception ed -> exception_declaration ctxt f ed | Pstr_module x -> let rec module_helper me = match me.pmod_desc with | Pmod_functor(s,mt,me') when me.pmod_attributes = [] -> if mt = None then pp f "()" else Misc.may (pp f "(%s:%a)" s.txt (module_type ctxt)) mt; module_helper me' | _ -> me in pp f "@[<hov2>%s %s%a@]%a" (keyword MODULE) x.pmb_name.txt (fun f me -> let me = module_helper me in match me.pmod_desc with | Pmod_constraint (me', ({pmty_desc=(Pmty_ident (_) | Pmty_signature (_));_} as mt)) when me.pmod_attributes = [] -> pp f " :@;%a@;=@;%a@;" (module_type ctxt) mt (module_expr ctxt) me' | _ -> pp f " =@ %a" (module_expr ctxt) me ) x.pmb_expr (item_attributes ctxt) x.pmb_attributes | Pstr_open od -> pp f "@[<2>%s%s@;%a@]%a" (keyword OPEN) (override od.popen_override) longident_loc od.popen_lid (item_attributes ctxt) od.popen_attributes | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} -> pp f "@[<hov2>%s@ %s@ %s%a@]%a" (keyword MODULE) (keyword TYPE) s.txt (fun f md -> match md with | None -> () | Some mt -> pp_print_space f () ; pp f "@ =@ %a" (module_type ctxt) mt ) md (item_attributes ctxt) attrs | Pstr_class l -> let extract_class_args cl = let rec loop acc cl = match cl.pcl_desc with | Pcl_fun (l, eo, p, cl') when cl.pcl_attributes = [] -> loop ((l,eo,p) :: acc) cl' | _ -> List.rev acc, cl in let args, cl = loop [] cl in let constr, cl = match cl.pcl_desc with | Pcl_constraint (cl', ct) when cl.pcl_attributes = [] -> Some ct, cl' | _ -> None, cl in args, constr, cl in let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in let class_declaration kwd f ({pci_params=ls; pci_name={txt;_}; _} as x) = let args, constr, cl = extract_class_args x.pci_expr in pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd virtual_flag x.pci_virt (class_params_def ctxt) ls txt (list (label_exp ctxt)) args (option class_constraint) constr (class_expr ctxt) cl (item_attributes ctxt) x.pci_attributes in begin match l with | [] -> () | [x] -> class_declaration (keyword CLASS) f x | x :: xs -> pp f "@[<v>%a@,%a@]" (class_declaration (keyword CLASS)) x (list ~sep:"@," (class_declaration (keyword AND))) xs end | Pstr_class_type l -> class_type_declaration_list ctxt f l | Pstr_primitive vd -> pp f "@[<hov2>%s@ %a@ :@ %a@]%a" (keyword EXTERNAL) protect_ident vd.pval_name.txt (value_description ctxt) vd (item_attributes ctxt) vd.pval_attributes | Pstr_include incl -> pp f "@[<hov2>%s@ %a@]%a" (keyword INCLUDE) (module_expr ctxt) incl.pincl_mod (item_attributes ctxt) incl.pincl_attributes 3.07 let aux f = function | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) -> pp f "@[<hov2>@ %s@ %s:%a@ =@ %a@]%a" (keyword AND) pmb.pmb_name.txt (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes | _ -> assert false in begin match decls with | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 -> pp f "@[<hv>@[<hov2>%s@ %s@ %s:%a@ =@ %a@]%a@ %a@]" (keyword MODULE) (keyword REC) pmb.pmb_name.txt (module_type ctxt) typ (module_expr ctxt) expr (item_attributes ctxt) pmb.pmb_attributes (fun f l2 -> List.iter (aux f) l2) l2 | _ -> assert false end | Pstr_attribute a -> floating_attribute ctxt f a | Pstr_extension(e, a) -> item_extension ctxt f e; item_attributes ctxt f a and type_param ctxt f (ct, a) = pp f "%s%a" (type_variance a) (core_type ctxt) ct and type_params ctxt f = function | [] -> () | l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l and type_def_list ctxt f (rf, l) = let type_decl kwd rf f x = let eq = if (x.ptype_kind = Ptype_abstract) && (x.ptype_manifest = None) then "" else " =" in pp f "@[<2>%s %a%a%s%s%a@]%a" kwd nonrec_flag rf (type_params ctxt) x.ptype_params x.ptype_name.txt eq (type_declaration ctxt) x (item_attributes ctxt) x.ptype_attributes in match l with | [] -> assert false | [x] -> type_decl (keyword TYPE) rf f x | x :: xs -> pp f "@[<v>%a@,%a@]" (type_decl (keyword TYPE) rf) x (list ~sep:"@," (type_decl (keyword AND) Recursive)) xs and record_declaration ctxt f lbls = let type_record_field f pld = pp f "@[<2>%a%s:@;%a@;%a@]" mutable_flag pld.pld_mutable pld.pld_name.txt (core_type ctxt) pld.pld_type (attributes ctxt) pld.pld_attributes in pp f "{@\n%a}" (list type_record_field ~sep:";@\n" ) lbls and type_declaration ctxt f x = let priv f = match x.ptype_private with | Public -> () | Private -> pp f "@;%s" (keyword PRIVATE) in let manifest f = match x.ptype_manifest with | None -> () | Some y -> if x.ptype_kind = Ptype_abstract then pp f "%t@;%a" priv (core_type ctxt) y else pp f "@;%a" (core_type ctxt) y in let constructor_declaration f pcd = pp f "|@;"; constructor_declaration ctxt f (pcd.pcd_name.txt, pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes) in let repr f = let intro f = if x.ptype_manifest = None then () else pp f "@;=" in match x.ptype_kind with | Ptype_variant xs -> pp f "%t%t@\n%a" intro priv (list ~sep:"@\n" constructor_declaration) xs | Ptype_abstract -> () | Ptype_record l -> pp f "%t%t@;%a" intro priv (record_declaration ctxt) l | Ptype_open -> pp f "%t%t@;.." intro priv in let constraints f = List.iter (fun (ct1,ct2,_) -> pp f "@[<hov2>@ %s@ %a@ =@ %a@]" (keyword CONSTRAINT) (core_type ctxt) ct1 (core_type ctxt) ct2) x.ptype_cstrs in pp f "%t%t%t" manifest repr constraints and type_extension ctxt f x = let extension_constructor f x = pp f "@\n|@;%a" (extension_constructor ctxt) x in pp f "@[<2>%s %a%a += %a@ %a@]%a" (keyword TYPE) (fun f -> function | [] -> () | l -> pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l) x.ptyext_params longident_loc x.ptyext_path Cf : # 7200 (list ~sep:"" extension_constructor) x.ptyext_constructors (item_attributes ctxt) x.ptyext_attributes and constructor_declaration ctxt f (name, args, res, attrs) = let name = match name with | "::" -> "(::)" | s -> s in match res with | None -> pp f "%s%a@;%a" name (fun f -> function | Pcstr_tuple [] -> () | Pcstr_tuple l -> pp f "@;%s@;%a" (keyword OF) (list (core_type1 ctxt) ~sep:"@;*@;") l | Pcstr_record l -> pp f "@;%s@;%a" (keyword OF) (record_declaration ctxt) l ) args (attributes ctxt) attrs | Some r -> pp f "%s:@;%a@;%a" name (fun f -> function | Pcstr_tuple [] -> core_type1 ctxt f r | Pcstr_tuple l -> pp f "%a@;->@;%a" (list (core_type1 ctxt) ~sep:"*@;") l (core_type1 ctxt) r | Pcstr_record l -> pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r ) args (attributes ctxt) attrs and extension_constructor ctxt f x = Cf : # 7200 match x.pext_kind with | Pext_decl(l, r) -> constructor_declaration ctxt f (x.pext_name.txt, l, r, x.pext_attributes) | Pext_rebind li -> pp f "%s%a@;=@;%a" x.pext_name.txt (attributes ctxt) x.pext_attributes longident_loc li and case_list ctxt f l : unit = let aux f {pc_lhs; pc_guard; pc_rhs} = pp f "@;| @[<2>%a%a@;->@;%a@]" (pattern ctxt) pc_lhs ( option (expression ctxt) ~firstf:(fun () -> Scanf.format_from_string (Printf.sprintf "@;%s@;" (keyword WHEN)) "")) pc_guard (expression (under_pipe ctxt)) pc_rhs in list aux f l ~sep:"" and label_x_expression_param ctxt f (l,e) = let simple_name = match e.pexp_desc with | Pexp_ident {txt=Lident l;_} -> Some l | _ -> None in match l with level 2 | Optional str -> if Some str = simple_name then pp f "?%s" str else pp f "?%s:%a" str (simple_expr ctxt) e | Labelled lbl -> if Some lbl = simple_name then pp f "~%s" lbl else pp f "~%s:%a" lbl (simple_expr ctxt) e and directive_argument f x = match x with | Pdir_none -> () | Pdir_string (s) -> pp f "@ %S" s | Pdir_int (n, None) -> pp f "@ %s" n | Pdir_int (n, Some m) -> pp f "@ %s%c" n m | Pdir_ident (li) -> pp f "@ %a" longident li | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b) let toplevel_phrase f x = match x with | Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s pp_close_box f ( ) ; | Ptop_dir (s, da) -> pp f "@[<hov2>#%s@ %a@]" s directive_argument da let expression f x = pp f "@[%a@]" (expression reset_ctxt) x let top_phrase f x = pp_print_newline f (); toplevel_phrase f x; pp f ";;"; pp_print_newline f () let core_type = core_type reset_ctxt let pattern = pattern reset_ctxt let signature = signature reset_ctxt let structure = structure reset_ctxt let exp_ast ast = let fmt = Format.str_formatter in Printast.expression 0 fmt ast; Format.flush_str_formatter () let contract_ast ast = let fmt = Format.str_formatter in Printast.structure 0 fmt ast; Format.flush_str_formatter ()
81abd68b915fb4c1a07a7a81c460ee68180b950bb91867c053e292f35f843f12
FlowForwarding/LINC-Switch
linc_us4_oe_packet_tests.erl
%%------------------------------------------------------------------------------ Copyright 2012 FlowForwarding.org %% 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. %%----------------------------------------------------------------------------- @author Erlang Solutions Ltd. < > 2012 FlowForwarding.org -module(linc_us4_oe_packet_tests). -import(linc_us4_oe_test_utils, [mock/1, unmock/1, check_if_called/1, check_output_on_ports/0]). -include_lib("of_protocol/include/of_protocol.hrl"). -include_lib("of_protocol/include/ofp_v4.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("pkt/include/pkt.hrl"). -include_lib("linc/include/linc_oe.hrl"). -include("linc_us4_oe.hrl"). -define(MOCKED, []). -define(INIT_VAL, 100). -define(NEW_VAL, 200). -define(INIT_VAL(Bits), <<100:Bits>>). -define(NEW_VAL(Bits), <<200:Bits>>). %% Tests ----------------------------------------------------------------------- basic_packet_edit_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: Ethernet", ethernet()}, {"Edit packet: VLAN", vlan()}, {"Edit packet: ARP", arp()}, {"Edit packet: SCTP", sctp()}, {"Edit packet: ICMPv4", icmp_v4()}, {"Edit packet: ICMPv6", icmp_v6()}, {"Edit packet: TCP", tcp()}, {"Edit packet: UDP", udp()}, {"Edit packet: MPLS", mpls()}, {"Edit packet: IPv4", ip_v4()}, {"Edit packet: IPv6", ip_v6()} ]}. corner_cases_packet_edit_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: no header", no_header()}, {"Edit packet: bad field", bad_field()}, {"Edit packet: duplicated header", duplicated_header()}, {"Edit packet: nested header", nested_header()}, {"Edit packet: skip header", skip_header()}, {"Edit packet: outermost header", outermost_header()} ]}. optical_extension_set_field_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: set OCH channel number (lambda)", fun och_channel_number_should_be_set/0}, {"Edit packet: replace OCH channel number (lambda)", fun och_channel_number_should_be_replaced/0}, {"Edit optical record: remove OCH optical data from packet", fun och_optical_data_should_be_removed_from_packet/0}]}. och_channel_number_should_be_set() -> %% GIVEN Channel = <<1:16>>, FieldToSet = #ofp_field{name = och_sigid, value = <<0:16, Channel/binary, 0:16>>}, ExpectedPkt = [#och_sigid{channel_number = Channel} | EthPkt = []], %% WHEN ActualPkt = linc_us4_oe_packet:set_field(FieldToSet, EthPkt), %% THEN ?assertEqual(ExpectedPkt, ActualPkt). och_channel_number_should_be_replaced() -> %% GIVEN NewChannel = <<2:16>>, FieldToSet = #ofp_field{name = och_sigid, value = <<0:16, NewChannel/binary, 0:16>>}, ExpectedPkt = [#och_sigid{channel_number = NewChannel} | []], OldChannel = <<1:16>>, EthPkt = [#och_sigid{channel_number = OldChannel}], %% WHEN ActualPkt = linc_us4_oe_packet:set_field(FieldToSet, EthPkt), %% THEN ?assertEqual(ExpectedPkt, ActualPkt). och_optical_data_should_be_removed_from_packet() -> %% GIVEN OpticalPacket = [#och_sigtype{value = <<"Specialized">>}, #och_sigid{channel_number = <<"Kona">>} | ExpectedEthPakcet = []], %% WHEN EthPacket = linc_us4_oe_packet:strip_optical_headers(OpticalPacket), %% THEN ?assertEqual(ExpectedEthPakcet, EthPacket). no_header() -> EmptyHeader = {[], {eth_type, ?NEW_VAL(16)}, []}, set_field([EmptyHeader]). bad_field() -> Packet = [#ether{type = ?INIT_VAL}], BadField = {Packet, {bad_field, ?NEW_VAL(16)}, Packet}, set_field([BadField]). duplicated_header() -> Packet = [#ether{type = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#ether{type = ?NEW_VAL}, #ether{type = ?INIT_VAL}], DuplicatedHeader = {Packet, {eth_type, ?NEW_VAL(16)}, NewPacket}, set_field([DuplicatedHeader]). nested_header() -> Packet = [#arp{op = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#arp{op = ?INIT_VAL}, #ether{type = ?NEW_VAL}], EditField = {eth_type, ?NEW_VAL(16)}, set_field([{Packet, EditField, NewPacket}]). skip_header() -> ?_test( begin Packet = [#ether{type = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#ether{type = ?INIT_VAL}, #ether{type = ?NEW_VAL}], SkipCount = 1, EditFun = fun(T) -> T#ether{type = ?NEW_VAL} end, Packet2 = linc_us4_oe_packet:find_and_edit_skip(Packet, ether, EditFun, SkipCount), ?assertEqual(NewPacket, Packet2) end). outermost_header() -> [ begin EmptyOutermostHeader = {[], {ip_proto, ?NEW_VAL(8)}, []}, set_field([EmptyOutermostHeader]) end, ?_test( begin Packet = [#ether{}, #ipv4{}], Header = ipv4, Header2 = linc_us4_oe_packet:find_outermost_header(Packet, [ipv4]), ?assertEqual(Header, Header2) end) ]. ethernet() -> EthType = {[#ether{type = ?INIT_VAL}], {eth_type, ?NEW_VAL(16)}, [#ether{type = ?NEW_VAL}]}, EthDst = {[#ether{dhost = ?INIT_VAL(48)}], {eth_dst, ?NEW_VAL(48)}, [#ether{dhost = ?NEW_VAL(48)}]}, EthSrc = {[#ether{shost = ?INIT_VAL(48)}], {eth_src, ?NEW_VAL(48)}, [#ether{shost = ?NEW_VAL(48)}]}, set_field([EthType, EthDst, EthSrc]). vlan() -> VlanVid = {[#ieee802_1q_tag{vid = <<(16#30A):12>>}], The least significat bit of 16#01 indicates vlan presence bit {vlan_vid, <<(16#01 bor 16#30B):13>>}, [#ieee802_1q_tag{vid = <<(16#30B):12>>}]}, VlanPcp = {[#ieee802_1q_tag{pcp = 1}], {vlan_pcp, <<2:3>>}, [#ieee802_1q_tag{pcp = 2}]}, set_field([VlanVid, VlanPcp]). arp() -> ArpOp = {[#arp{op = ?INIT_VAL}], {arp_op, ?NEW_VAL(16)}, [#arp{op = ?NEW_VAL}]}, ArpSpa = {[#arp{sip = ?INIT_VAL(32)}], {arp_spa, ?NEW_VAL(32)}, [#arp{sip = ?NEW_VAL(32)}]}, ArpTpa = {[#arp{tip = ?INIT_VAL(32)}], {arp_tpa, ?NEW_VAL(32)}, [#arp{tip = ?NEW_VAL(32)}]}, ArpSha = {[#arp{sha = ?INIT_VAL(48)}], {arp_sha, ?NEW_VAL(48)}, [#arp{sha = ?NEW_VAL(48)}]}, ArpTha = {[#arp{tha = ?INIT_VAL(48)}], {arp_tha, ?NEW_VAL(48)}, [#arp{tha = ?NEW_VAL(48)}]}, set_field([ArpOp, ArpSpa, ArpTpa, ArpSha, ArpTha]). sctp() -> SctpSrc = {[#sctp{sport = ?INIT_VAL}], {sctp_src, ?NEW_VAL(16)}, [#sctp{sport = ?NEW_VAL}]}, SctpDst = {[#sctp{dport = ?INIT_VAL}], {sctp_dst, ?NEW_VAL(16)}, [#sctp{dport = ?NEW_VAL}]}, set_field([SctpSrc, SctpDst]). icmp_v4() -> %% The default value for #icmp.un is a binary, but the encoding %% function only accepts integers. Icmp = #icmp{un = 0}, Icmp4Type = {[Icmp#icmp{type = ?INIT_VAL}], {icmpv4_type, ?NEW_VAL(8)}, [Icmp#icmp{type = ?NEW_VAL}]}, Icmp4Code = {[#icmp{code = ?INIT_VAL}], {icmpv4_code, ?NEW_VAL(8)}, [#icmp{code = ?NEW_VAL}]}, set_field([Icmp4Type, Icmp4Code]). icmp_v6() -> Icmp6Type = {[#icmpv6{type = ?INIT_VAL}], {icmpv6_type, ?NEW_VAL(8)}, [#icmpv6{type = ?NEW_VAL}]}, Icmp6Code = {[#icmpv6{code = ?INIT_VAL}], {icmpv6_code, ?NEW_VAL(8)}, [#icmpv6{code = ?NEW_VAL}]}, set_field([Icmp6Type, Icmp6Code]). tcp() -> TcpSrc = {[#tcp{sport = ?INIT_VAL}], {tcp_src, ?NEW_VAL(16)}, [#tcp{sport = ?NEW_VAL}]}, TcpDst = {[#tcp{dport = ?INIT_VAL}], {tcp_dst, ?NEW_VAL(16)}, [#tcp{dport = ?NEW_VAL}]}, set_field([TcpSrc, TcpDst]). udp() -> UdpSrc = {[#udp{sport = ?INIT_VAL}], {udp_src, ?NEW_VAL(16)}, [#udp{sport = ?NEW_VAL}]}, UdpDst = {[#udp{dport = ?INIT_VAL}], {udp_dst, ?NEW_VAL(16)}, [#udp{dport = ?NEW_VAL}]}, set_field([UdpSrc, UdpDst]). mpls() -> MplsLabel = {[#mpls_tag{stack = [#mpls_stack_entry{label = ?INIT_VAL(20)}, #mpls_stack_entry{label = ?INIT_VAL(20)}]}], {mpls_label, ?NEW_VAL(20)}, [#mpls_tag{stack = [#mpls_stack_entry{label = ?NEW_VAL(20)}, #mpls_stack_entry{label = ?INIT_VAL(20)}]}]}, MplsTc = {[#mpls_tag{stack = [#mpls_stack_entry{qos = 0, pri = 0, ecn = 0}, #mpls_stack_entry{qos = 0, pri = 0, ecn = 0} ]}], {mpls_tc, <<1:1,1:1,1:1>>}, [#mpls_tag{stack = [#mpls_stack_entry{qos = 1, pri = 1, ecn = 1}, #mpls_stack_entry{qos = 0, pri = 0, ecn = 0} ]}]}, set_field([MplsLabel, MplsTc]). ip_v4() -> Ip4Proto = {[#ipv4{p = ?INIT_VAL}], {ip_proto, ?NEW_VAL(8)}, [#ipv4{p = ?NEW_VAL}]}, Ip4Dscp = {[#ipv4{dscp = 1}], {ip_dscp, <<2:6>>}, [#ipv4{dscp = 2}]}, Ip4Ecn = {[#ipv4{ecn = 1}], {ip_ecn, <<2:2>>}, [#ipv4{ecn = 2}]}, Ip4Src = {[#ipv4{saddr = ?INIT_VAL(32)}], {ipv4_src, ?NEW_VAL(32)}, [#ipv4{saddr = ?NEW_VAL(32)}]}, Ip4Dst = {[#ipv4{daddr = ?INIT_VAL(32)}], {ipv4_dst, ?NEW_VAL(32)}, [#ipv4{daddr = ?NEW_VAL(32)}]}, set_field([Ip4Proto, Ip4Dscp, Ip4Ecn, Ip4Src, Ip4Dst]). ip_v6() -> The # ipv6 record has no default values for the saddr and daddr %% fields. Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, Ip6Proto = {[Ipv6#ipv6{next = ?INIT_VAL}], {ip_proto, ?NEW_VAL(8)}, [Ipv6#ipv6{next = ?NEW_VAL}]}, Ip6Dscp = {[Ipv6#ipv6{class = 0}], {ip_dscp, <<1:6>>}, [Ipv6#ipv6{class = 1 bsl 2}]}, Ip6Ecn = {[Ipv6#ipv6{class = 0}], {ip_ecn, <<1:2>>}, [Ipv6#ipv6{class = 1}]}, Ip6Src = {[Ipv6#ipv6{saddr = ?INIT_VAL(128)}], {ipv6_src, ?NEW_VAL(128)}, [Ipv6#ipv6{saddr = ?NEW_VAL(128)}]}, Ip6Dst = {[Ipv6#ipv6{daddr = ?INIT_VAL(128)}], {ipv6_dst, ?NEW_VAL(128)}, [Ipv6#ipv6{daddr = ?NEW_VAL(128)}]}, Ip6Flabel = {[Ipv6#ipv6{flow = ?INIT_VAL}], {ipv6_flabel, ?NEW_VAL(20)}, [Ipv6#ipv6{flow = ?NEW_VAL}]}, Ip6NdTarget1 = {[#ndp_ns{tgt_addr = ?INIT_VAL(128)}, #ndp_na{src_addr = ?INIT_VAL(128)}], {ipv6_nd_target, ?NEW_VAL(128)}, [#ndp_ns{tgt_addr = ?NEW_VAL(128)}, #ndp_na{src_addr = ?INIT_VAL(128)}]}, Ip6NdTarget2 = {[#ndp_na{src_addr = ?INIT_VAL(128)}, #ndp_ns{tgt_addr = ?INIT_VAL(128)}], {ipv6_nd_target, ?NEW_VAL(128)}, [#ndp_na{src_addr = ?NEW_VAL(128)}, #ndp_ns{tgt_addr = ?INIT_VAL(128)}]}, Ip6NdSll1 = {[#ndp_ns{sll = ?INIT_VAL(16)}, #ndp_na{tll = ?INIT_VAL(16)}], {ipv6_nd_sll, ?NEW_VAL(16)}, [#ndp_ns{sll = ?NEW_VAL(16)}, #ndp_na{tll = ?INIT_VAL(16)}]}, Ip6NdSll2 = {[#ndp_na{tll = ?INIT_VAL(16)}, #ndp_ns{sll = ?INIT_VAL(16)}], {ipv6_nd_sll, ?NEW_VAL(16)}, [#ndp_na{tll = ?NEW_VAL(16)}, #ndp_ns{sll = ?INIT_VAL(16)}]}, set_field([Ip6Proto, Ip6Dscp, Ip6Ecn, Ip6Src, Ip6Dst, Ip6Flabel, Ip6NdTarget1, Ip6NdTarget2, Ip6NdSll1, Ip6NdSll2]). %% Fixtures -------------------------------------------------------------------- setup() -> mock(?MOCKED). teardown(_) -> unmock(?MOCKED). set_field(TestData) -> [{"set field " ++ atom_to_list(Name), ?_test( begin only binaries are allowed in # ofp_field.value case Value of _ when is_bitstring(Value) -> ok end, %% check that the packet can be encoded before the change Packet =/= [] andalso (_ = encode(hd(Packet))), %% perform the change Field = #ofp_field{name = Name, value = Value}, Packet2 = linc_us4_oe_packet:set_field(Field, Packet), %% check that the packet can be encoded after the change Packet2 =/= [] andalso (_ = encode(hd(Packet2))), %% check that the result matches what we expected ?assertEqual(NewPacket, Packet2) end)} || {Packet, {Name, Value}, NewPacket} <- TestData]. encode(Packet = #ieee802_1q_tag{}) -> pkt:encapsulate([Packet, #ipv4{}, #tcp{}]); encode(Packet = #mpls_tag{}) -> pkt:encapsulate([Packet, #ipv4{}, #tcp{}]); encode(Packet = #ndp_na{}) -> Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, pkt:encapsulate([Ipv6, #icmpv6{}, Packet]); encode(Packet = #ndp_ns{}) -> Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, pkt:encapsulate([Ipv6, #icmpv6{}, Packet]); encode(Packet = #tcp{}) -> pkt_tcp:encapsulate(Packet, #ipv4{}, <<>>); encode(Packet = #udp{}) -> pkt_udp:encapsulate(Packet, #ipv4{}, <<>>); encode(_Packet = #sctp{}) -> %% pkt.erl cannot encode SCTP packets ignore; encode(Packet) when is_tuple(Packet) -> Type = element(1, Packet), pkt:Type(Packet).
null
https://raw.githubusercontent.com/FlowForwarding/LINC-Switch/9c28e7c8677c03440a62023292dd700fef0c3420/apps/linc_us4_oe/test/linc_us4_oe_packet_tests.erl
erlang
------------------------------------------------------------------------------ you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- Tests ----------------------------------------------------------------------- GIVEN WHEN THEN GIVEN WHEN THEN GIVEN WHEN THEN The default value for #icmp.un is a binary, but the encoding function only accepts integers. fields. Fixtures -------------------------------------------------------------------- check that the packet can be encoded before the change perform the change check that the packet can be encoded after the change check that the result matches what we expected pkt.erl cannot encode SCTP packets
Copyright 2012 FlowForwarding.org Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author Erlang Solutions Ltd. < > 2012 FlowForwarding.org -module(linc_us4_oe_packet_tests). -import(linc_us4_oe_test_utils, [mock/1, unmock/1, check_if_called/1, check_output_on_ports/0]). -include_lib("of_protocol/include/of_protocol.hrl"). -include_lib("of_protocol/include/ofp_v4.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("pkt/include/pkt.hrl"). -include_lib("linc/include/linc_oe.hrl"). -include("linc_us4_oe.hrl"). -define(MOCKED, []). -define(INIT_VAL, 100). -define(NEW_VAL, 200). -define(INIT_VAL(Bits), <<100:Bits>>). -define(NEW_VAL(Bits), <<200:Bits>>). basic_packet_edit_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: Ethernet", ethernet()}, {"Edit packet: VLAN", vlan()}, {"Edit packet: ARP", arp()}, {"Edit packet: SCTP", sctp()}, {"Edit packet: ICMPv4", icmp_v4()}, {"Edit packet: ICMPv6", icmp_v6()}, {"Edit packet: TCP", tcp()}, {"Edit packet: UDP", udp()}, {"Edit packet: MPLS", mpls()}, {"Edit packet: IPv4", ip_v4()}, {"Edit packet: IPv6", ip_v6()} ]}. corner_cases_packet_edit_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: no header", no_header()}, {"Edit packet: bad field", bad_field()}, {"Edit packet: duplicated header", duplicated_header()}, {"Edit packet: nested header", nested_header()}, {"Edit packet: skip header", skip_header()}, {"Edit packet: outermost header", outermost_header()} ]}. optical_extension_set_field_test_() -> {setup, fun setup/0, fun teardown/1, [{"Edit packet: set OCH channel number (lambda)", fun och_channel_number_should_be_set/0}, {"Edit packet: replace OCH channel number (lambda)", fun och_channel_number_should_be_replaced/0}, {"Edit optical record: remove OCH optical data from packet", fun och_optical_data_should_be_removed_from_packet/0}]}. och_channel_number_should_be_set() -> Channel = <<1:16>>, FieldToSet = #ofp_field{name = och_sigid, value = <<0:16, Channel/binary, 0:16>>}, ExpectedPkt = [#och_sigid{channel_number = Channel} | EthPkt = []], ActualPkt = linc_us4_oe_packet:set_field(FieldToSet, EthPkt), ?assertEqual(ExpectedPkt, ActualPkt). och_channel_number_should_be_replaced() -> NewChannel = <<2:16>>, FieldToSet = #ofp_field{name = och_sigid, value = <<0:16, NewChannel/binary, 0:16>>}, ExpectedPkt = [#och_sigid{channel_number = NewChannel} | []], OldChannel = <<1:16>>, EthPkt = [#och_sigid{channel_number = OldChannel}], ActualPkt = linc_us4_oe_packet:set_field(FieldToSet, EthPkt), ?assertEqual(ExpectedPkt, ActualPkt). och_optical_data_should_be_removed_from_packet() -> OpticalPacket = [#och_sigtype{value = <<"Specialized">>}, #och_sigid{channel_number = <<"Kona">>} | ExpectedEthPakcet = []], EthPacket = linc_us4_oe_packet:strip_optical_headers(OpticalPacket), ?assertEqual(ExpectedEthPakcet, EthPacket). no_header() -> EmptyHeader = {[], {eth_type, ?NEW_VAL(16)}, []}, set_field([EmptyHeader]). bad_field() -> Packet = [#ether{type = ?INIT_VAL}], BadField = {Packet, {bad_field, ?NEW_VAL(16)}, Packet}, set_field([BadField]). duplicated_header() -> Packet = [#ether{type = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#ether{type = ?NEW_VAL}, #ether{type = ?INIT_VAL}], DuplicatedHeader = {Packet, {eth_type, ?NEW_VAL(16)}, NewPacket}, set_field([DuplicatedHeader]). nested_header() -> Packet = [#arp{op = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#arp{op = ?INIT_VAL}, #ether{type = ?NEW_VAL}], EditField = {eth_type, ?NEW_VAL(16)}, set_field([{Packet, EditField, NewPacket}]). skip_header() -> ?_test( begin Packet = [#ether{type = ?INIT_VAL}, #ether{type = ?INIT_VAL}], NewPacket = [#ether{type = ?INIT_VAL}, #ether{type = ?NEW_VAL}], SkipCount = 1, EditFun = fun(T) -> T#ether{type = ?NEW_VAL} end, Packet2 = linc_us4_oe_packet:find_and_edit_skip(Packet, ether, EditFun, SkipCount), ?assertEqual(NewPacket, Packet2) end). outermost_header() -> [ begin EmptyOutermostHeader = {[], {ip_proto, ?NEW_VAL(8)}, []}, set_field([EmptyOutermostHeader]) end, ?_test( begin Packet = [#ether{}, #ipv4{}], Header = ipv4, Header2 = linc_us4_oe_packet:find_outermost_header(Packet, [ipv4]), ?assertEqual(Header, Header2) end) ]. ethernet() -> EthType = {[#ether{type = ?INIT_VAL}], {eth_type, ?NEW_VAL(16)}, [#ether{type = ?NEW_VAL}]}, EthDst = {[#ether{dhost = ?INIT_VAL(48)}], {eth_dst, ?NEW_VAL(48)}, [#ether{dhost = ?NEW_VAL(48)}]}, EthSrc = {[#ether{shost = ?INIT_VAL(48)}], {eth_src, ?NEW_VAL(48)}, [#ether{shost = ?NEW_VAL(48)}]}, set_field([EthType, EthDst, EthSrc]). vlan() -> VlanVid = {[#ieee802_1q_tag{vid = <<(16#30A):12>>}], The least significat bit of 16#01 indicates vlan presence bit {vlan_vid, <<(16#01 bor 16#30B):13>>}, [#ieee802_1q_tag{vid = <<(16#30B):12>>}]}, VlanPcp = {[#ieee802_1q_tag{pcp = 1}], {vlan_pcp, <<2:3>>}, [#ieee802_1q_tag{pcp = 2}]}, set_field([VlanVid, VlanPcp]). arp() -> ArpOp = {[#arp{op = ?INIT_VAL}], {arp_op, ?NEW_VAL(16)}, [#arp{op = ?NEW_VAL}]}, ArpSpa = {[#arp{sip = ?INIT_VAL(32)}], {arp_spa, ?NEW_VAL(32)}, [#arp{sip = ?NEW_VAL(32)}]}, ArpTpa = {[#arp{tip = ?INIT_VAL(32)}], {arp_tpa, ?NEW_VAL(32)}, [#arp{tip = ?NEW_VAL(32)}]}, ArpSha = {[#arp{sha = ?INIT_VAL(48)}], {arp_sha, ?NEW_VAL(48)}, [#arp{sha = ?NEW_VAL(48)}]}, ArpTha = {[#arp{tha = ?INIT_VAL(48)}], {arp_tha, ?NEW_VAL(48)}, [#arp{tha = ?NEW_VAL(48)}]}, set_field([ArpOp, ArpSpa, ArpTpa, ArpSha, ArpTha]). sctp() -> SctpSrc = {[#sctp{sport = ?INIT_VAL}], {sctp_src, ?NEW_VAL(16)}, [#sctp{sport = ?NEW_VAL}]}, SctpDst = {[#sctp{dport = ?INIT_VAL}], {sctp_dst, ?NEW_VAL(16)}, [#sctp{dport = ?NEW_VAL}]}, set_field([SctpSrc, SctpDst]). icmp_v4() -> Icmp = #icmp{un = 0}, Icmp4Type = {[Icmp#icmp{type = ?INIT_VAL}], {icmpv4_type, ?NEW_VAL(8)}, [Icmp#icmp{type = ?NEW_VAL}]}, Icmp4Code = {[#icmp{code = ?INIT_VAL}], {icmpv4_code, ?NEW_VAL(8)}, [#icmp{code = ?NEW_VAL}]}, set_field([Icmp4Type, Icmp4Code]). icmp_v6() -> Icmp6Type = {[#icmpv6{type = ?INIT_VAL}], {icmpv6_type, ?NEW_VAL(8)}, [#icmpv6{type = ?NEW_VAL}]}, Icmp6Code = {[#icmpv6{code = ?INIT_VAL}], {icmpv6_code, ?NEW_VAL(8)}, [#icmpv6{code = ?NEW_VAL}]}, set_field([Icmp6Type, Icmp6Code]). tcp() -> TcpSrc = {[#tcp{sport = ?INIT_VAL}], {tcp_src, ?NEW_VAL(16)}, [#tcp{sport = ?NEW_VAL}]}, TcpDst = {[#tcp{dport = ?INIT_VAL}], {tcp_dst, ?NEW_VAL(16)}, [#tcp{dport = ?NEW_VAL}]}, set_field([TcpSrc, TcpDst]). udp() -> UdpSrc = {[#udp{sport = ?INIT_VAL}], {udp_src, ?NEW_VAL(16)}, [#udp{sport = ?NEW_VAL}]}, UdpDst = {[#udp{dport = ?INIT_VAL}], {udp_dst, ?NEW_VAL(16)}, [#udp{dport = ?NEW_VAL}]}, set_field([UdpSrc, UdpDst]). mpls() -> MplsLabel = {[#mpls_tag{stack = [#mpls_stack_entry{label = ?INIT_VAL(20)}, #mpls_stack_entry{label = ?INIT_VAL(20)}]}], {mpls_label, ?NEW_VAL(20)}, [#mpls_tag{stack = [#mpls_stack_entry{label = ?NEW_VAL(20)}, #mpls_stack_entry{label = ?INIT_VAL(20)}]}]}, MplsTc = {[#mpls_tag{stack = [#mpls_stack_entry{qos = 0, pri = 0, ecn = 0}, #mpls_stack_entry{qos = 0, pri = 0, ecn = 0} ]}], {mpls_tc, <<1:1,1:1,1:1>>}, [#mpls_tag{stack = [#mpls_stack_entry{qos = 1, pri = 1, ecn = 1}, #mpls_stack_entry{qos = 0, pri = 0, ecn = 0} ]}]}, set_field([MplsLabel, MplsTc]). ip_v4() -> Ip4Proto = {[#ipv4{p = ?INIT_VAL}], {ip_proto, ?NEW_VAL(8)}, [#ipv4{p = ?NEW_VAL}]}, Ip4Dscp = {[#ipv4{dscp = 1}], {ip_dscp, <<2:6>>}, [#ipv4{dscp = 2}]}, Ip4Ecn = {[#ipv4{ecn = 1}], {ip_ecn, <<2:2>>}, [#ipv4{ecn = 2}]}, Ip4Src = {[#ipv4{saddr = ?INIT_VAL(32)}], {ipv4_src, ?NEW_VAL(32)}, [#ipv4{saddr = ?NEW_VAL(32)}]}, Ip4Dst = {[#ipv4{daddr = ?INIT_VAL(32)}], {ipv4_dst, ?NEW_VAL(32)}, [#ipv4{daddr = ?NEW_VAL(32)}]}, set_field([Ip4Proto, Ip4Dscp, Ip4Ecn, Ip4Src, Ip4Dst]). ip_v6() -> The # ipv6 record has no default values for the saddr and daddr Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, Ip6Proto = {[Ipv6#ipv6{next = ?INIT_VAL}], {ip_proto, ?NEW_VAL(8)}, [Ipv6#ipv6{next = ?NEW_VAL}]}, Ip6Dscp = {[Ipv6#ipv6{class = 0}], {ip_dscp, <<1:6>>}, [Ipv6#ipv6{class = 1 bsl 2}]}, Ip6Ecn = {[Ipv6#ipv6{class = 0}], {ip_ecn, <<1:2>>}, [Ipv6#ipv6{class = 1}]}, Ip6Src = {[Ipv6#ipv6{saddr = ?INIT_VAL(128)}], {ipv6_src, ?NEW_VAL(128)}, [Ipv6#ipv6{saddr = ?NEW_VAL(128)}]}, Ip6Dst = {[Ipv6#ipv6{daddr = ?INIT_VAL(128)}], {ipv6_dst, ?NEW_VAL(128)}, [Ipv6#ipv6{daddr = ?NEW_VAL(128)}]}, Ip6Flabel = {[Ipv6#ipv6{flow = ?INIT_VAL}], {ipv6_flabel, ?NEW_VAL(20)}, [Ipv6#ipv6{flow = ?NEW_VAL}]}, Ip6NdTarget1 = {[#ndp_ns{tgt_addr = ?INIT_VAL(128)}, #ndp_na{src_addr = ?INIT_VAL(128)}], {ipv6_nd_target, ?NEW_VAL(128)}, [#ndp_ns{tgt_addr = ?NEW_VAL(128)}, #ndp_na{src_addr = ?INIT_VAL(128)}]}, Ip6NdTarget2 = {[#ndp_na{src_addr = ?INIT_VAL(128)}, #ndp_ns{tgt_addr = ?INIT_VAL(128)}], {ipv6_nd_target, ?NEW_VAL(128)}, [#ndp_na{src_addr = ?NEW_VAL(128)}, #ndp_ns{tgt_addr = ?INIT_VAL(128)}]}, Ip6NdSll1 = {[#ndp_ns{sll = ?INIT_VAL(16)}, #ndp_na{tll = ?INIT_VAL(16)}], {ipv6_nd_sll, ?NEW_VAL(16)}, [#ndp_ns{sll = ?NEW_VAL(16)}, #ndp_na{tll = ?INIT_VAL(16)}]}, Ip6NdSll2 = {[#ndp_na{tll = ?INIT_VAL(16)}, #ndp_ns{sll = ?INIT_VAL(16)}], {ipv6_nd_sll, ?NEW_VAL(16)}, [#ndp_na{tll = ?NEW_VAL(16)}, #ndp_ns{sll = ?INIT_VAL(16)}]}, set_field([Ip6Proto, Ip6Dscp, Ip6Ecn, Ip6Src, Ip6Dst, Ip6Flabel, Ip6NdTarget1, Ip6NdTarget2, Ip6NdSll1, Ip6NdSll2]). setup() -> mock(?MOCKED). teardown(_) -> unmock(?MOCKED). set_field(TestData) -> [{"set field " ++ atom_to_list(Name), ?_test( begin only binaries are allowed in # ofp_field.value case Value of _ when is_bitstring(Value) -> ok end, Packet =/= [] andalso (_ = encode(hd(Packet))), Field = #ofp_field{name = Name, value = Value}, Packet2 = linc_us4_oe_packet:set_field(Field, Packet), Packet2 =/= [] andalso (_ = encode(hd(Packet2))), ?assertEqual(NewPacket, Packet2) end)} || {Packet, {Name, Value}, NewPacket} <- TestData]. encode(Packet = #ieee802_1q_tag{}) -> pkt:encapsulate([Packet, #ipv4{}, #tcp{}]); encode(Packet = #mpls_tag{}) -> pkt:encapsulate([Packet, #ipv4{}, #tcp{}]); encode(Packet = #ndp_na{}) -> Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, pkt:encapsulate([Ipv6, #icmpv6{}, Packet]); encode(Packet = #ndp_ns{}) -> Ipv6 = #ipv6{saddr = <<0:128>>, daddr = <<0:128>>}, pkt:encapsulate([Ipv6, #icmpv6{}, Packet]); encode(Packet = #tcp{}) -> pkt_tcp:encapsulate(Packet, #ipv4{}, <<>>); encode(Packet = #udp{}) -> pkt_udp:encapsulate(Packet, #ipv4{}, <<>>); encode(_Packet = #sctp{}) -> ignore; encode(Packet) when is_tuple(Packet) -> Type = element(1, Packet), pkt:Type(Packet).
7ffc7f7bf2b21b4241085d5ffd2a403170554c9b7adc07aca2d51234a3cdb2dd
forked-from-1kasper/anders
repl.ml
open Prettyprinter open Module open Error open Decl open Radio let help = "Available commands: <statement> infer type and normalize statement :q quit :r restart :h display this message Information about command line options can be found at ‘anders help’." let banner = Printf.sprintf "Anders Proof Assistant version %Ld.%Ld.%Ld This software is licensed under the ISC License. For more information, see LICENSE file." Fuze.year Fuze.month Fuze.patch let loaded : Files.t ref = ref Files.empty let main : command -> unit = function | Expr e -> let (t, v) = (infer e, eval e) in Printf.printf "TYPE: %s\nEVAL: %s\n" (showExp t) (showExp v) | Action "q" -> exit 0 | Action "r" -> loaded := Files.empty; raise Restart | Action "h" -> print_endline help | Command (s, _) | Action s -> raise (UnknownCommand s) | Nope -> () let repl () = print_endline ("\n" ^ banner ^ "\n\nFor help type ‘:h’.\n"); try while true do print_string "> "; let line = read_line () in handleErrors (fun s -> match Combinators.runParser Parser.repl (Combinators.ofString s) 0 with | Error err -> Printf.printf "Parse error:\n%s\n" err | Ok (_, c) -> main c) line () done with End_of_file -> ()
null
https://raw.githubusercontent.com/forked-from-1kasper/anders/233098bf3ecf2f4900d44216af534044c4c8544e/src/frontend/repl.ml
ocaml
open Prettyprinter open Module open Error open Decl open Radio let help = "Available commands: <statement> infer type and normalize statement :q quit :r restart :h display this message Information about command line options can be found at ‘anders help’." let banner = Printf.sprintf "Anders Proof Assistant version %Ld.%Ld.%Ld This software is licensed under the ISC License. For more information, see LICENSE file." Fuze.year Fuze.month Fuze.patch let loaded : Files.t ref = ref Files.empty let main : command -> unit = function | Expr e -> let (t, v) = (infer e, eval e) in Printf.printf "TYPE: %s\nEVAL: %s\n" (showExp t) (showExp v) | Action "q" -> exit 0 | Action "r" -> loaded := Files.empty; raise Restart | Action "h" -> print_endline help | Command (s, _) | Action s -> raise (UnknownCommand s) | Nope -> () let repl () = print_endline ("\n" ^ banner ^ "\n\nFor help type ‘:h’.\n"); try while true do print_string "> "; let line = read_line () in handleErrors (fun s -> match Combinators.runParser Parser.repl (Combinators.ofString s) 0 with | Error err -> Printf.printf "Parse error:\n%s\n" err | Ok (_, c) -> main c) line () done with End_of_file -> ()
ef9bcd016f97621e3306b28fe108e95fbdbf468b2c89a35165d629c7530698f1
nixeagle/cl-irc
parse-message.lisp
$ Id$ ;;;; $Source$ ;;;; See the LICENSE file for licensing information. (in-package :irc) (defun find-reply-name (reply-number &key (reply-names *reply-names*)) "Numeric replies in the IRC RFCs have more meaningful names. Given a numeric reply (`reply-number') this function will either return the symbol representing the reply or raise a continuable error (`no-such-reply') which gives you the opportunity to ignore the situation." (let ((name (assoc reply-number reply-names))) (if name (cadr name) (progn (cerror "Ignore unknown reply." 'no-such-reply :reply-number reply-number) :unknown-reply)))) (defun return-source (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the source part of the message. Returns nil if the source part is not present." (cut-between string #\: '(#\! #\Space) :start start)) (defun return-user (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the user part of the message. Returns nil if the user part is not present." (cut-between string #\! '(#\@ #\Space) :start start)) (defun return-host (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the host part of the message. Returns nil if the host part is not present." (cut-between string #\@ '(#\Space) :start start)) (defun return-command (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the command part of the message. Returns nil if the command part is not present." (if (eql (char string start) #\Space) (cut-between string #\Space '(#\Space) :start start) (cut-between string nil '(#\Space) :start start :cut-extra nil))) (defun return-arguments (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the arguments part of the message as a list. Returns nil if the arguments part is not present." (multiple-value-bind (end-position return-argument) (cut-before string " :" '(#\Return) :start start) (values end-position (tokenize-string return-argument :delimiters '(#\Space))))) (defun return-trailing-argument (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the trailing-argument part of the message. Returns nil if the trailing-argument part is not present." (cut-between string #\: '(#\Return) :start start)) (defun parse-raw-message (string &key (start 0)) "Assuming `string' is a valid IRC message, parse the message and return the values in the following order: - source - user - host - command - arguments - trailing-argument Any values not present will be represented as nil." (let ((index start) (returns nil)) (dolist (function '(return-source return-user return-host return-command return-arguments return-trailing-argument)) (multiple-value-bind (return-index return-string) (funcall function string :start index) (setf index return-index) (push return-string returns))) (apply #'values (reverse returns)))) (defun irc-error-reply-p (string) "Returns t if `string' is a string-representation of an IRC error reply message, nil otherwise." (unless (zerop (length string)) (if (and (every #'digit-char-p string) (member (char string 0) '(#\4 #\5))) t nil))) (defun numeric-reply-p (string) "Returns t if `string' is a string-representation of an IRC number reply, nil otherwise." (every #'digit-char-p string)) (defun ctcp-type-p (string type) "Is the `string' actually a representation of the CTCP `type'?" (if (string-equal (subseq string 1 (min (length string) (1+ (length (symbol-name type))))) type) type nil)) (defun dcc-type-p (string type) "Is the `string' actually a representation of the DCC `type'?" (case type (:dcc-chat-request (when (string-equal (char string 5) #\C) :dcc-chat-request)) (:dcc-send-request (when (string-equal (char string 5) #\S) :dcc-send-request)) (otherwise nil))) (defun ctcp-message-type (string) "If `string' is a CTCP message, return the type of the message or nil if this is a) not a CTCP message or b) a CTCP message we don't know about." (if (or (not (stringp string)) (zerop (length string)) (not (eql (char string 0) +soh+))) nil (case (char string 1) (#\A (ctcp-type-p string :action)) (#\C (ctcp-type-p string :clientinfo)) (#\D (or (dcc-type-p string :dcc-chat-request) (dcc-type-p string :dcc-send-request))) (#\F (ctcp-type-p string :finger)) (#\P (ctcp-type-p string :ping)) (#\S (ctcp-type-p string :source)) (#\T (ctcp-type-p string :time)) (#\U (ctcp-type-p string :userinfo)) (#\V (ctcp-type-p string :version)) (otherwise nil)))) (defun create-irc-message (string) "If `string' is a valid IRC message parse it and return an object of the correct type with its slots prefilled according to the information in the message." (multiple-value-bind (source user host command arguments trailing-argument) (parse-raw-message string) (let ((class 'irc-message) (ctcp (ctcp-message-type trailing-argument))) (when command (cond (nil ;(irc-error-reply-p command) ;; Disable for now, as it prevents adding hooks for some useful ;; error types (progn (setf command (find-reply-name (parse-integer command))) (setf class 'irc-error-reply))) ((numeric-reply-p command) (progn (setf command (find-reply-name (parse-integer command))) (setf class (find-irc-message-class command)))) (t (progn (setf command (intern (string-upcase command) (find-package :keyword))) (setf class (find-irc-message-class command)))))) (when ctcp (setf class (find-ctcp-message-class ctcp))) (let ((instance (make-instance class :source (or source "") :user (or user "") :host (or host "") :command (if command (string command) "") :arguments arguments :connection nil :trailing-argument (or trailing-argument "") :received-time (get-universal-time) :raw-message-string (or string "")))) (when ctcp (setf (ctcp-command instance) ctcp)) instance))))
null
https://raw.githubusercontent.com/nixeagle/cl-irc/efaea15f2962107ea9b1a2fad5cd9db492b4247b/tags/mode_tracking/parse-message.lisp
lisp
$Source$ See the LICENSE file for licensing information. (irc-error-reply-p command) Disable for now, as it prevents adding hooks for some useful error types
$ Id$ (in-package :irc) (defun find-reply-name (reply-number &key (reply-names *reply-names*)) "Numeric replies in the IRC RFCs have more meaningful names. Given a numeric reply (`reply-number') this function will either return the symbol representing the reply or raise a continuable error (`no-such-reply') which gives you the opportunity to ignore the situation." (let ((name (assoc reply-number reply-names))) (if name (cadr name) (progn (cerror "Ignore unknown reply." 'no-such-reply :reply-number reply-number) :unknown-reply)))) (defun return-source (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the source part of the message. Returns nil if the source part is not present." (cut-between string #\: '(#\! #\Space) :start start)) (defun return-user (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the user part of the message. Returns nil if the user part is not present." (cut-between string #\! '(#\@ #\Space) :start start)) (defun return-host (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the host part of the message. Returns nil if the host part is not present." (cut-between string #\@ '(#\Space) :start start)) (defun return-command (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the command part of the message. Returns nil if the command part is not present." (if (eql (char string start) #\Space) (cut-between string #\Space '(#\Space) :start start) (cut-between string nil '(#\Space) :start start :cut-extra nil))) (defun return-arguments (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the arguments part of the message as a list. Returns nil if the arguments part is not present." (multiple-value-bind (end-position return-argument) (cut-before string " :" '(#\Return) :start start) (values end-position (tokenize-string return-argument :delimiters '(#\Space))))) (defun return-trailing-argument (string &key (start 0)) "Assuming `string' is a valid IRC message this function returns the trailing-argument part of the message. Returns nil if the trailing-argument part is not present." (cut-between string #\: '(#\Return) :start start)) (defun parse-raw-message (string &key (start 0)) "Assuming `string' is a valid IRC message, parse the message and return the values in the following order: - source - user - host - command - arguments - trailing-argument Any values not present will be represented as nil." (let ((index start) (returns nil)) (dolist (function '(return-source return-user return-host return-command return-arguments return-trailing-argument)) (multiple-value-bind (return-index return-string) (funcall function string :start index) (setf index return-index) (push return-string returns))) (apply #'values (reverse returns)))) (defun irc-error-reply-p (string) "Returns t if `string' is a string-representation of an IRC error reply message, nil otherwise." (unless (zerop (length string)) (if (and (every #'digit-char-p string) (member (char string 0) '(#\4 #\5))) t nil))) (defun numeric-reply-p (string) "Returns t if `string' is a string-representation of an IRC number reply, nil otherwise." (every #'digit-char-p string)) (defun ctcp-type-p (string type) "Is the `string' actually a representation of the CTCP `type'?" (if (string-equal (subseq string 1 (min (length string) (1+ (length (symbol-name type))))) type) type nil)) (defun dcc-type-p (string type) "Is the `string' actually a representation of the DCC `type'?" (case type (:dcc-chat-request (when (string-equal (char string 5) #\C) :dcc-chat-request)) (:dcc-send-request (when (string-equal (char string 5) #\S) :dcc-send-request)) (otherwise nil))) (defun ctcp-message-type (string) "If `string' is a CTCP message, return the type of the message or nil if this is a) not a CTCP message or b) a CTCP message we don't know about." (if (or (not (stringp string)) (zerop (length string)) (not (eql (char string 0) +soh+))) nil (case (char string 1) (#\A (ctcp-type-p string :action)) (#\C (ctcp-type-p string :clientinfo)) (#\D (or (dcc-type-p string :dcc-chat-request) (dcc-type-p string :dcc-send-request))) (#\F (ctcp-type-p string :finger)) (#\P (ctcp-type-p string :ping)) (#\S (ctcp-type-p string :source)) (#\T (ctcp-type-p string :time)) (#\U (ctcp-type-p string :userinfo)) (#\V (ctcp-type-p string :version)) (otherwise nil)))) (defun create-irc-message (string) "If `string' is a valid IRC message parse it and return an object of the correct type with its slots prefilled according to the information in the message." (multiple-value-bind (source user host command arguments trailing-argument) (parse-raw-message string) (let ((class 'irc-message) (ctcp (ctcp-message-type trailing-argument))) (when command (cond (progn (setf command (find-reply-name (parse-integer command))) (setf class 'irc-error-reply))) ((numeric-reply-p command) (progn (setf command (find-reply-name (parse-integer command))) (setf class (find-irc-message-class command)))) (t (progn (setf command (intern (string-upcase command) (find-package :keyword))) (setf class (find-irc-message-class command)))))) (when ctcp (setf class (find-ctcp-message-class ctcp))) (let ((instance (make-instance class :source (or source "") :user (or user "") :host (or host "") :command (if command (string command) "") :arguments arguments :connection nil :trailing-argument (or trailing-argument "") :received-time (get-universal-time) :raw-message-string (or string "")))) (when ctcp (setf (ctcp-command instance) ctcp)) instance))))
d2949aceb24bab8a17b94463a5defba89a7f0d61e620435b77e34a1da3c9ab59
ghc/testsuite
tcfail201.hs
{-# LANGUAGE RankNTypes #-} -- Claus reported by email that GHCi , version 6.9.20080217 loops on this program -- -ghc/2008-June/043173.html -- So I'm adding it to the test suite so that we'll see it if it happens again module Foo where data HsDoc id = DocEmpty | DocParagraph (HsDoc id) gfoldl' :: (forall a b . c (a -> b) -> a -> c b) -> (forall g . g -> c g) -> a -> c a gfoldl' k z hsDoc = case hsDoc of DocEmpty -> z DocEmpty (DocParagraph hsDoc) -> z DocParagraph `k` hsDoc
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/tcfail201.hs
haskell
# LANGUAGE RankNTypes # Claus reported by email that -ghc/2008-June/043173.html So I'm adding it to the test suite so that we'll see it if it happens again
GHCi , version 6.9.20080217 loops on this program module Foo where data HsDoc id = DocEmpty | DocParagraph (HsDoc id) gfoldl' :: (forall a b . c (a -> b) -> a -> c b) -> (forall g . g -> c g) -> a -> c a gfoldl' k z hsDoc = case hsDoc of DocEmpty -> z DocEmpty (DocParagraph hsDoc) -> z DocParagraph `k` hsDoc
1715f7174ac1cbbecf0ff72d5e9a2f5620376bb687028ad5c1157716499e78a4
input-output-hk/cardano-wallet-legacy
Buildable.hs
-- | Utilities for dealing with 'Buildable' module Util.Buildable ( ShowThroughBuild(..) ) where import Formatting (bprint, sformat) import qualified Formatting as F import Formatting.Buildable (Buildable (..)) import Prelude (Show (..)) import Test.QuickCheck (Arbitrary (..)) import Universum newtype ShowThroughBuild a = STB { unSTB :: a } deriving (Eq, Ord) instance Buildable a => Buildable (ShowThroughBuild a) where build = bprint F.build . unSTB instance Buildable a => Show (ShowThroughBuild a) where show = toString . sformat F.build . unSTB instance Arbitrary a => Arbitrary (ShowThroughBuild a) where arbitrary = STB <$> arbitrary
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet-legacy/143e6d0dac0b28b3274600c6c49ec87e42ec9f37/test/unit/Util/Buildable.hs
haskell
| Utilities for dealing with 'Buildable'
module Util.Buildable ( ShowThroughBuild(..) ) where import Formatting (bprint, sformat) import qualified Formatting as F import Formatting.Buildable (Buildable (..)) import Prelude (Show (..)) import Test.QuickCheck (Arbitrary (..)) import Universum newtype ShowThroughBuild a = STB { unSTB :: a } deriving (Eq, Ord) instance Buildable a => Buildable (ShowThroughBuild a) where build = bprint F.build . unSTB instance Buildable a => Show (ShowThroughBuild a) where show = toString . sformat F.build . unSTB instance Arbitrary a => Arbitrary (ShowThroughBuild a) where arbitrary = STB <$> arbitrary
6b6d356b3e9447581f7c82e850e65f33297715d39dca0e87d07d855fc4c75b85
nuprl/gradual-typing-performance
scheme-tests.rkt
#lang scheme/base (require test-engine/scheme-tests "type-env-ext.rkt") (provide (all-from-out test-engine/scheme-tests))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/typed/test-engine/scheme-tests.rkt
racket
#lang scheme/base (require test-engine/scheme-tests "type-env-ext.rkt") (provide (all-from-out test-engine/scheme-tests))
103580e3771ce70018a4b47f20cb46547728762dc653f32968b9dc0e32056dc9
jordwalke/rehp
deadcode.mli
Js_of_ocaml compiler * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val f : Code.program -> Code.program * int array
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/compiler/lib/deadcode.mli
ocaml
Js_of_ocaml compiler * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val f : Code.program -> Code.program * int array
3af15e41873efe93a114464af4804c82e089061df8bd77d94a60c116acc1fa84
melange-re/melange
functor_ffi.ml
module Make ( S : sig type elt end ) = struct open S type 'a t external unsafe_get : elt t -> int -> elt = "" [@@bs.get_index] external get : elt t -> int -> elt Js.undefined = "" [@@bs.get_index] let opt_get f i = Js.Undefined.toOption @@ get f i end module Int_arr = Make ( struct type elt = int end) let f v : int * _ option = Int_arr.unsafe_get v 0 , Int_arr.opt_get v 1
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/functor_ffi.ml
ocaml
module Make ( S : sig type elt end ) = struct open S type 'a t external unsafe_get : elt t -> int -> elt = "" [@@bs.get_index] external get : elt t -> int -> elt Js.undefined = "" [@@bs.get_index] let opt_get f i = Js.Undefined.toOption @@ get f i end module Int_arr = Make ( struct type elt = int end) let f v : int * _ option = Int_arr.unsafe_get v 0 , Int_arr.opt_get v 1
821bcb95854abed31ad7238bbdc45ba884b2fe2d0ad0d847be6569144fb3d806
techascent/tech.ml.dataset
format_sequence.clj
(ns ^:no-doc tech.v3.dataset.format-sequence "This code provided initial by genmeblog after careful consideration of R print code" (:import [java.text DecimalFormat])) CN - I removed cl - format as a required dependency so that graal native executables would ;;both compile faster and be much smaller. (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;; maximum double power for precise calculations (def ^:private ^:const ^long kp-max 22) ;; powers for scientific notation (def ^:private tbl [1e-1, 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22]) (defn- left "What is the power of number" ^long [^double x] (-> x Math/log10 Math/floor unchecked-long inc)) (defn- find-nsig "Shift decimal places until non-zero value is found" ^long [^double alpha ^long digits] (loop [a alpha d digits] (let [a- (/ a 10.0)] (if (= a- (Math/floor a-)) (recur a- (dec d)) (max 1 d))))) (defn- right "Calculate maximum digits on the right side of the dot." ^long [^double x ^long digits] (let [alpha (Math/round (* x ^double (tbl (inc digits))))] (if (zero? alpha) 1 (find-nsig alpha digits)))) (defn- fix-left "Fix number of digits on the left side. For scientific notations and non-positive exponent (lft) it should be leading digits + sign." [^double x ^long lft e?] (let [sgn (if (neg? x) 1 0)] (if (or e? (not (pos? lft))) (+ sgn 1) (+ sgn lft)))) (defn- precision [^double x ^long digits ^long threshold] (if (zero? x) zero is reprezented as 0.0 constrain digits to 1 - 10 range r (Math/abs x) lft (left r) ;; digits on the left side of dot alft (Math/abs lft) e? (>= alft threshold) r-prec (cond (< alft threshold) r ;; normal number (< alft kp-max) (if (neg? lft) ;; scientific number (using table to shift values) (* r ^double (tbl (inc (- lft)))) (/ r ^double (tbl (inc lft)))) :else (/ r (Math/pow 10.0 (dec lft)))) ;; very big or very small case rght (right r-prec digits) ;; desired precision on the right side exp (if (> alft 100) 3 2) ;; size of the exponent lft (fix-left x lft e?)] [e? exp lft rght]))) (defn- fit-precision "Find best matching presision for given sequence." [xs ^long digits ^long threshold] (reduce (fn [[ce? ^long cexp ^long clft ^long crght ^long non-finite-len] x] (let [^double x (if (instance? Float x) (Double/valueOf (str x)) (or x ##NaN))] (if (Double/isFinite x) (let [[e? ^long exp ^long lft ^long rght] (precision x digits threshold)] (if (and e? (pos? threshold)) (reduced (fit-precision xs digits 0)) ;; switch to scientific notation [(or e? ce?) (max exp cexp) (max lft clft) (max rght crght) non-finite-len])) [ce? cexp clft crght (max non-finite-len (if (= x ##-Inf) 4 3))]))) [false Integer/MIN_VALUE Integer/MIN_VALUE Integer/MIN_VALUE 0] xs)) ;; public functions (defn formatter "Create formatter for given: * `xs` - sequence of doubles * `digits` - maximum precision * `threshold` - what is absolute power to switch to scientific notation Returns formatter." ([xs] (formatter xs 8)) ([xs ^long digits] (formatter xs digits 8)) ([xs ^long digits ^long threshold] (let [[e? ^long exp ^long lft ^long rght ^long non-finite-len] (fit-precision xs digits threshold) w (max non-finite-len (if e? 3 = " . " + sign of E + " E " 1 for " . " deci-format-str (apply str (concat ["0."] (repeat rght "0") (when e? ["E"]) (when e? (repeat exp "0")))) deci-format (DecimalFormat. deci-format-str) non-finite-format (str "%" w "s")] (fn [x] (let [^double x (or x ##NaN) finite? (Double/isFinite x) ^String unspaced (if (Double/isFinite x) (.format deci-format x) (cond (== ##Inf x) "Inf" (== ##-Inf x) "-Inf" :else "NaN"))] (String/format non-finite-format (object-array [(if (and e? finite? (== -1 (.lastIndexOf unspaced "E-"))) ;;Insert the + sign (.replace unspaced "E" "E+") unspaced)]))))))) (defn format-sequence "Format sequence of double for given: * `xs` - sequence of doubles * `digits` - maximum precision * `threshold` - what is absolute power to switch to scientific notation Returns sequence of strings." ([xs] (format-sequence xs 8)) ([xs ^long digits] (format-sequence xs digits 8)) ([xs ^long digits ^long threshold] (let [fmt (formatter xs digits threshold)] (map fmt xs))))
null
https://raw.githubusercontent.com/techascent/tech.ml.dataset/69b3035169453a23df70a19492fec47a2b1ddced/src/tech/v3/dataset/format_sequence.clj
clojure
both compile faster and be much smaller. maximum double power for precise calculations powers for scientific notation digits on the left side of dot normal number scientific number (using table to shift values) very big or very small case desired precision on the right side size of the exponent switch to scientific notation public functions Insert the + sign
(ns ^:no-doc tech.v3.dataset.format-sequence "This code provided initial by genmeblog after careful consideration of R print code" (:import [java.text DecimalFormat])) CN - I removed cl - format as a required dependency so that graal native executables would (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (def ^:private ^:const ^long kp-max 22) (def ^:private tbl [1e-1, 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22]) (defn- left "What is the power of number" ^long [^double x] (-> x Math/log10 Math/floor unchecked-long inc)) (defn- find-nsig "Shift decimal places until non-zero value is found" ^long [^double alpha ^long digits] (loop [a alpha d digits] (let [a- (/ a 10.0)] (if (= a- (Math/floor a-)) (recur a- (dec d)) (max 1 d))))) (defn- right "Calculate maximum digits on the right side of the dot." ^long [^double x ^long digits] (let [alpha (Math/round (* x ^double (tbl (inc digits))))] (if (zero? alpha) 1 (find-nsig alpha digits)))) (defn- fix-left "Fix number of digits on the left side. For scientific notations and non-positive exponent (lft) it should be leading digits + sign." [^double x ^long lft e?] (let [sgn (if (neg? x) 1 0)] (if (or e? (not (pos? lft))) (+ sgn 1) (+ sgn lft)))) (defn- precision [^double x ^long digits ^long threshold] (if (zero? x) zero is reprezented as 0.0 constrain digits to 1 - 10 range r (Math/abs x) alft (Math/abs lft) e? (>= alft threshold) r-prec (cond (* r ^double (tbl (inc (- lft)))) (/ r ^double (tbl (inc lft)))) lft (fix-left x lft e?)] [e? exp lft rght]))) (defn- fit-precision "Find best matching presision for given sequence." [xs ^long digits ^long threshold] (reduce (fn [[ce? ^long cexp ^long clft ^long crght ^long non-finite-len] x] (let [^double x (if (instance? Float x) (Double/valueOf (str x)) (or x ##NaN))] (if (Double/isFinite x) (let [[e? ^long exp ^long lft ^long rght] (precision x digits threshold)] (if (and e? (pos? threshold)) [(or e? ce?) (max exp cexp) (max lft clft) (max rght crght) non-finite-len])) [ce? cexp clft crght (max non-finite-len (if (= x ##-Inf) 4 3))]))) [false Integer/MIN_VALUE Integer/MIN_VALUE Integer/MIN_VALUE 0] xs)) (defn formatter "Create formatter for given: * `xs` - sequence of doubles * `digits` - maximum precision * `threshold` - what is absolute power to switch to scientific notation Returns formatter." ([xs] (formatter xs 8)) ([xs ^long digits] (formatter xs digits 8)) ([xs ^long digits ^long threshold] (let [[e? ^long exp ^long lft ^long rght ^long non-finite-len] (fit-precision xs digits threshold) w (max non-finite-len (if e? 3 = " . " + sign of E + " E " 1 for " . " deci-format-str (apply str (concat ["0."] (repeat rght "0") (when e? ["E"]) (when e? (repeat exp "0")))) deci-format (DecimalFormat. deci-format-str) non-finite-format (str "%" w "s")] (fn [x] (let [^double x (or x ##NaN) finite? (Double/isFinite x) ^String unspaced (if (Double/isFinite x) (.format deci-format x) (cond (== ##Inf x) "Inf" (== ##-Inf x) "-Inf" :else "NaN"))] (String/format non-finite-format (object-array [(if (and e? finite? (== -1 (.lastIndexOf unspaced "E-"))) (.replace unspaced "E" "E+") unspaced)]))))))) (defn format-sequence "Format sequence of double for given: * `xs` - sequence of doubles * `digits` - maximum precision * `threshold` - what is absolute power to switch to scientific notation Returns sequence of strings." ([xs] (format-sequence xs 8)) ([xs ^long digits] (format-sequence xs digits 8)) ([xs ^long digits ^long threshold] (let [fmt (formatter xs digits threshold)] (map fmt xs))))
076b9171edae44f0ce1d9082790f58ff11f09c49e6b2d49cc647357ff2b3c24f
metabase/metabase
logger_test.clj
(ns metabase.logger-test (:require [clojure.string :as str] [clojure.test :refer :all] #_{:clj-kondo/ignore [:discouraged-namespace]} [clojure.tools.logging :as log] [clojure.tools.logging.impl :as log.impl] [metabase.logger :as mb.logger] [metabase.test :as mt]) (:import (org.apache.logging.log4j.core Logger))) (set! *warn-on-reflection* true) (defn logger (^Logger [] (logger 'metabase.logger-test)) (^Logger [ns-symb] (log.impl/get-logger log/*logger-factory* ns-symb))) (deftest added-appender-tests (testing "appender is added to the logger" (is (contains? (.getAppenders (logger)) "metabase-appender") "Logger does not contain `metabase-appender` logger")) (testing "logging adds to in-memory ringbuffer" (mt/with-log-level :debug (log/debug "testing in-memory logger") (is (some (fn [{message :msg, :as entry}] (when (str/includes? (str message) "testing in-memory logger") entry)) (mb.logger/messages)) "In memory ring buffer did not receive log message"))) (testing "set isAdditive = false if parent logger is root to prevent logging to console (#26468)" (testing "make sure it's true to starts with" (is (.isAdditive (logger 'metabase)))) (testing "set to false if parent logger is root" (mt/with-log-level :warn (is (not (.isAdditive (logger 'metabase)))))) (testing "still true if the parent logger is not root" (mt/with-log-level [metabase.logger :warn] (is (.isAdditive (logger 'metabase.logger))))))) (deftest ^:parallel logger-test (testing "Using log4j2 logger" (is (= "org.apache.logging.log4j" (log.impl/name log/*logger-factory*)) "Not using log4j2 logger factory. This could add two orders of magnitude of time to logging calls"))) (deftest logger-respect-configured-log-level-test (testing "The appender that we programmatically added should respect the log levels in the config file" whether we 're in the REPL or in test mode this should not show up (log/debug "THIS SHOULD NOT SHOW UP") (is (not (some (fn [{message :msg, :as entry}] (when (str/includes? (str message) "THIS SHOULD NOT SHOW UP") entry)) (mb.logger/messages))))))
null
https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/test/metabase/logger_test.clj
clojure
(ns metabase.logger-test (:require [clojure.string :as str] [clojure.test :refer :all] #_{:clj-kondo/ignore [:discouraged-namespace]} [clojure.tools.logging :as log] [clojure.tools.logging.impl :as log.impl] [metabase.logger :as mb.logger] [metabase.test :as mt]) (:import (org.apache.logging.log4j.core Logger))) (set! *warn-on-reflection* true) (defn logger (^Logger [] (logger 'metabase.logger-test)) (^Logger [ns-symb] (log.impl/get-logger log/*logger-factory* ns-symb))) (deftest added-appender-tests (testing "appender is added to the logger" (is (contains? (.getAppenders (logger)) "metabase-appender") "Logger does not contain `metabase-appender` logger")) (testing "logging adds to in-memory ringbuffer" (mt/with-log-level :debug (log/debug "testing in-memory logger") (is (some (fn [{message :msg, :as entry}] (when (str/includes? (str message) "testing in-memory logger") entry)) (mb.logger/messages)) "In memory ring buffer did not receive log message"))) (testing "set isAdditive = false if parent logger is root to prevent logging to console (#26468)" (testing "make sure it's true to starts with" (is (.isAdditive (logger 'metabase)))) (testing "set to false if parent logger is root" (mt/with-log-level :warn (is (not (.isAdditive (logger 'metabase)))))) (testing "still true if the parent logger is not root" (mt/with-log-level [metabase.logger :warn] (is (.isAdditive (logger 'metabase.logger))))))) (deftest ^:parallel logger-test (testing "Using log4j2 logger" (is (= "org.apache.logging.log4j" (log.impl/name log/*logger-factory*)) "Not using log4j2 logger factory. This could add two orders of magnitude of time to logging calls"))) (deftest logger-respect-configured-log-level-test (testing "The appender that we programmatically added should respect the log levels in the config file" whether we 're in the REPL or in test mode this should not show up (log/debug "THIS SHOULD NOT SHOW UP") (is (not (some (fn [{message :msg, :as entry}] (when (str/includes? (str message) "THIS SHOULD NOT SHOW UP") entry)) (mb.logger/messages))))))
3edc66ed16a00f863dcabb4b579ef29b1910518bd7781f77dcdbba4da27f7488
haskellari/lukko
Lukko.hs
{-# LANGUAGE CPP #-} # LANGUAGE Trustworthy # -- | Open 'Handle' based locking module Lukko ( FileLockingNotSupported(..), Impl.fileLockingSupported, Impl.FileLockingSupported, FileLockingMethod (..), Impl.fileLockingMethod, LockMode(..), -- * File descriptors FD, fdOpen, fdClose, fdLock, fdTryLock, fdUnlock, -- * Handles handleToFd, hLock, hTryLock, hUnlock, ) where Parts of these software is derived from GHC sources distributed under BSD-3 - Clause license : The Glasgow Haskell Compiler License Copyright 2004 , The University Court of the University of Glasgow . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : - Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . - Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE 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 UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE 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 . distributed under BSD-3-Clause license: The Glasgow Haskell Compiler License Copyright 2004, The University Court of the University of Glasgow. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE 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 UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE 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. -} import Control.Monad (void) import System.IO (Handle) import Lukko.Internal.Types import qualified Lukko.Internal.FD as Impl #if defined(USE_OFD_LOCKING) import qualified Lukko.OFD as Impl #elif defined(USE_FLOCK) import qualified Lukko.FLock as Impl #elif defined(USE_WINDOWS_LOCK) import qualified Lukko.Windows as Impl #else import qualified Lukko.NoOp as Impl #endif ------------------------------------------------------------------------------- -- Handles ------------------------------------------------------------------------------- -- | If a 'Handle' references a file descriptor, attempt to lock contents of the -- underlying file in appropriate mode. If the file is already locked in -- incompatible mode, this function blocks until the lock is established. The -- lock is automatically released upon closing a 'Handle'. -- -- Things to be aware of: -- 1 ) This function may block inside a C call . If it does , in order to be able -- to interrupt it with asynchronous exceptions and/or for other threads to -- continue working, you MUST use threaded version of the runtime system. -- 2 ) The implementation uses ' LockFileEx ' on Windows , /open file descriptor/ locks on Linux , and ' flock ' otherwise , -- hence all of their caveats also apply here. -- 3 ) On non - Windows plaftorms that do n't support ' flock ' ( e.g. ) this -- function throws 'FileLockingNotImplemented'. We deliberately choose to not -- provide @fcntl@ based locking instead because of its broken semantics. -- hLock :: Handle -> LockMode -> IO () hLock = Impl.hLock | Non - blocking version of ' ' . hTryLock :: Handle -> LockMode -> IO Bool hTryLock = Impl.hTryLock | Release a lock taken with ' ' or ' hTryLock ' . hUnlock :: Handle -> IO () hUnlock = Impl.hUnlock ------------------------------------------------------------------------------- -- File descriptors ------------------------------------------------------------------------------- -- | Opaque /file descriptor/ -- -- An @int@ / 'CInt' on unix systems, -- and 'HANDLE' on windows. type FD = Impl.FD -- | Open file to be used for locking. fdOpen :: FilePath -> IO FD fdOpen = Impl.fdOpen -- | Close lock file. fdClose :: FD -> IO () fdClose = Impl.fdClose | Convert GHC ' Handle ' to lukko ' FD ' . handleToFd :: Handle -> IO FD handleToFd = Impl.handleToFd | Like ' ' , but work on " raw " file descriptor , -- as handled by 'fdOpen' and 'fdClose'. fdLock :: Impl.FD -> LockMode -> IO () fdLock = Impl.fdLock -- | Non-blocking version of 'fdLock'. fdTryLock :: Impl.FD -> LockMode -> IO Bool fdTryLock = Impl.fdTryLock -- | Release a lock taken with 'fdLock' or 'fdTryLock'. fdUnlock :: Impl.FD -> IO () fdUnlock = Impl.fdUnlock
null
https://raw.githubusercontent.com/haskellari/lukko/623a257210637b01e928090dccee88410d0b8e90/src/Lukko.hs
haskell
# LANGUAGE CPP # | Open 'Handle' based locking * File descriptors * Handles ----------------------------------------------------------------------------- Handles ----------------------------------------------------------------------------- | If a 'Handle' references a file descriptor, attempt to lock contents of the underlying file in appropriate mode. If the file is already locked in incompatible mode, this function blocks until the lock is established. The lock is automatically released upon closing a 'Handle'. Things to be aware of: to interrupt it with asynchronous exceptions and/or for other threads to continue working, you MUST use threaded version of the runtime system. hence all of their caveats also apply here. function throws 'FileLockingNotImplemented'. We deliberately choose to not provide @fcntl@ based locking instead because of its broken semantics. ----------------------------------------------------------------------------- File descriptors ----------------------------------------------------------------------------- | Opaque /file descriptor/ An @int@ / 'CInt' on unix systems, and 'HANDLE' on windows. | Open file to be used for locking. | Close lock file. as handled by 'fdOpen' and 'fdClose'. | Non-blocking version of 'fdLock'. | Release a lock taken with 'fdLock' or 'fdTryLock'.
# LANGUAGE Trustworthy # module Lukko ( FileLockingNotSupported(..), Impl.fileLockingSupported, Impl.FileLockingSupported, FileLockingMethod (..), Impl.fileLockingMethod, LockMode(..), FD, fdOpen, fdClose, fdLock, fdTryLock, fdUnlock, handleToFd, hLock, hTryLock, hUnlock, ) where Parts of these software is derived from GHC sources distributed under BSD-3 - Clause license : The Glasgow Haskell Compiler License Copyright 2004 , The University Court of the University of Glasgow . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : - Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . - Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE 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 UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE 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 . distributed under BSD-3-Clause license: The Glasgow Haskell Compiler License Copyright 2004, The University Court of the University of Glasgow. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW AND THE 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 UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE 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. -} import Control.Monad (void) import System.IO (Handle) import Lukko.Internal.Types import qualified Lukko.Internal.FD as Impl #if defined(USE_OFD_LOCKING) import qualified Lukko.OFD as Impl #elif defined(USE_FLOCK) import qualified Lukko.FLock as Impl #elif defined(USE_WINDOWS_LOCK) import qualified Lukko.Windows as Impl #else import qualified Lukko.NoOp as Impl #endif 1 ) This function may block inside a C call . If it does , in order to be able 2 ) The implementation uses ' LockFileEx ' on Windows , /open file descriptor/ locks on Linux , and ' flock ' otherwise , 3 ) On non - Windows plaftorms that do n't support ' flock ' ( e.g. ) this hLock :: Handle -> LockMode -> IO () hLock = Impl.hLock | Non - blocking version of ' ' . hTryLock :: Handle -> LockMode -> IO Bool hTryLock = Impl.hTryLock | Release a lock taken with ' ' or ' hTryLock ' . hUnlock :: Handle -> IO () hUnlock = Impl.hUnlock type FD = Impl.FD fdOpen :: FilePath -> IO FD fdOpen = Impl.fdOpen fdClose :: FD -> IO () fdClose = Impl.fdClose | Convert GHC ' Handle ' to lukko ' FD ' . handleToFd :: Handle -> IO FD handleToFd = Impl.handleToFd | Like ' ' , but work on " raw " file descriptor , fdLock :: Impl.FD -> LockMode -> IO () fdLock = Impl.fdLock fdTryLock :: Impl.FD -> LockMode -> IO Bool fdTryLock = Impl.fdTryLock fdUnlock :: Impl.FD -> IO () fdUnlock = Impl.fdUnlock
ea83910910411698116c5c8f4d51373de34bb5bfb761f18fe88a3677e8fc64e5
Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator
OperationGetOperationDescriptionSpec.hs
# LANGUAGE DuplicateRecordFields # {-# LANGUAGE OverloadedStrings #-} module OpenAPI.Generate.OperationGetOperationDescriptionSpec where import qualified Data.Map as Map import OpenAPI.Generate.Internal.Operation import OpenAPI.Generate.Types as OAT import Test.Hspec spec :: Spec spec = let emptyResponseObject = OAT.ResponsesObject { default' = Nothing, range1XX = Nothing, range2XX = Nothing, range3XX = Nothing, range4XX = Nothing, range5XX = Nothing, perStatusCode = Map.empty } testOperation = OAT.OperationObject { tags = [], summary = Nothing, description = Nothing, externalDocs = Nothing, operationId = Nothing, parameters = [], requestBody = Nothing, responses = emptyResponseObject, deprecated = False, security = [], servers = [] } testOperation2 = testOperation { summary = Just "my summary" } :: OAT.OperationObject testOperation3 = testOperation { description = Just "my description" } :: OAT.OperationObject testOperation4 = testOperation { summary = Just "my summary", description = Just "my description" } :: OAT.OperationObject in describe "getOperationDesciption" $ do it "should return an empty string" (getOperationDescription testOperation `shouldBe` "") it "should return description" (getOperationDescription testOperation2 `shouldBe` "my summary") it "should return summary" (getOperationDescription testOperation3 `shouldBe` "my description") it "should return description" (getOperationDescription testOperation4 `shouldBe` "my description")
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator/d9cc91717b773882be65ec290c020dd0adb7cc3b/openapi3-code-generator/test/OpenAPI/Generate/OperationGetOperationDescriptionSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DuplicateRecordFields # module OpenAPI.Generate.OperationGetOperationDescriptionSpec where import qualified Data.Map as Map import OpenAPI.Generate.Internal.Operation import OpenAPI.Generate.Types as OAT import Test.Hspec spec :: Spec spec = let emptyResponseObject = OAT.ResponsesObject { default' = Nothing, range1XX = Nothing, range2XX = Nothing, range3XX = Nothing, range4XX = Nothing, range5XX = Nothing, perStatusCode = Map.empty } testOperation = OAT.OperationObject { tags = [], summary = Nothing, description = Nothing, externalDocs = Nothing, operationId = Nothing, parameters = [], requestBody = Nothing, responses = emptyResponseObject, deprecated = False, security = [], servers = [] } testOperation2 = testOperation { summary = Just "my summary" } :: OAT.OperationObject testOperation3 = testOperation { description = Just "my description" } :: OAT.OperationObject testOperation4 = testOperation { summary = Just "my summary", description = Just "my description" } :: OAT.OperationObject in describe "getOperationDesciption" $ do it "should return an empty string" (getOperationDescription testOperation `shouldBe` "") it "should return description" (getOperationDescription testOperation2 `shouldBe` "my summary") it "should return summary" (getOperationDescription testOperation3 `shouldBe` "my description") it "should return description" (getOperationDescription testOperation4 `shouldBe` "my description")
eb28d99cc162e5cec0fd803fe9a69b002e8f054ea858d8d842b8c2033ae07652
steffan-westcott/clj-otel
logging.clj
(ns steffan-westcott.clj-otel.exporter.logging "Exporters that log telemetry data using `java.util.logging`. Intended for debugging only." (:import (io.opentelemetry.exporter.logging LoggingMetricExporter LoggingSpanExporter) (io.opentelemetry.sdk.metrics.data AggregationTemporality))) (defn span-exporter "Returns a span exporter that logs every span using `java.util.logging`." [] (LoggingSpanExporter/create)) (defn metric-exporter "Returns a metric exporter that logs every metric using `java.util.logging`. May take an option map as follows: | key | description | |--------------------------|-------------| |`:aggregation-temporality`| ^AggregationTemporality Time period over which metrics should be aggregated (default: `CUMULATIVE`)." ([] (LoggingMetricExporter/create)) ([{:keys [aggregation-temporality] :or {aggregation-temporality AggregationTemporality/CUMULATIVE}}] (LoggingMetricExporter/create aggregation-temporality)))
null
https://raw.githubusercontent.com/steffan-westcott/clj-otel/92975012560fb999fc46e73ec0d84e5b82fdeaab/clj-otel-exporter-logging/src/steffan_westcott/clj_otel/exporter/logging.clj
clojure
(ns steffan-westcott.clj-otel.exporter.logging "Exporters that log telemetry data using `java.util.logging`. Intended for debugging only." (:import (io.opentelemetry.exporter.logging LoggingMetricExporter LoggingSpanExporter) (io.opentelemetry.sdk.metrics.data AggregationTemporality))) (defn span-exporter "Returns a span exporter that logs every span using `java.util.logging`." [] (LoggingSpanExporter/create)) (defn metric-exporter "Returns a metric exporter that logs every metric using `java.util.logging`. May take an option map as follows: | key | description | |--------------------------|-------------| |`:aggregation-temporality`| ^AggregationTemporality Time period over which metrics should be aggregated (default: `CUMULATIVE`)." ([] (LoggingMetricExporter/create)) ([{:keys [aggregation-temporality] :or {aggregation-temporality AggregationTemporality/CUMULATIVE}}] (LoggingMetricExporter/create aggregation-temporality)))
43cf85b878e8e3ed3acf25b7143d0272c718ce23565d6c27f6853d43ae70e2f3
oakmac/snowflake-css
util.cljs
(ns com.oakmac.snowflake.client.util) ;;------------------------------------------------------------------------------ ;; Logging ;;------------------------------------------------------------------------------ (defn js-log "Logs a JavaScript thing." [js-thing] (js/console.log js-thing)) (defn log "Logs a Clojure thing." [clj-thing] (js-log (pr-str clj-thing))) ;;------------------------------------------------------------------------------ DOM ;;------------------------------------------------------------------------------ (defn by-id [id] (.getElementById js/document id))
null
https://raw.githubusercontent.com/oakmac/snowflake-css/e6e19c6a9e4686e0abccdf3bd0d1b1866eb6ee5a/00-old/src-cljs/client/com/oakmac/snowflake/client/util.cljs
clojure
------------------------------------------------------------------------------ Logging ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
(ns com.oakmac.snowflake.client.util) (defn js-log "Logs a JavaScript thing." [js-thing] (js/console.log js-thing)) (defn log "Logs a Clojure thing." [clj-thing] (js-log (pr-str clj-thing))) DOM (defn by-id [id] (.getElementById js/document id))
9af12ed134ab5e6cc3d63aa2b534482301ed97f222f8ab301823d181cab621c5
acl2/acl2
(+-OF---AND-0) (SLICE-OF-0 (100 3 (:REWRITE BVCHOP-IDENTITY)) (98 5 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (67 9 (:DEFINITION NATP)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (28 2 (:REWRITE LOGTAIL-BECOMES-0)) (20 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (11 11 (:REWRITE DEFAULT-<-2)) (11 11 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (9 9 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:DEFINITION POSP)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:TYPE-PRESCRIPTION POSP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (5 5 (:REWRITE UBP-LONGER-BETTER)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 1 (:REWRITE <-OF---AND--)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (INTEGERP-OF-SLICE) (NATP-OF-SLICE) (SLICE-WHEN-VAL-IS-NOT-AN-INTEGER (100 3 (:REWRITE BVCHOP-IDENTITY)) (82 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (57 7 (:DEFINITION NATP)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (20 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (15 15 (:REWRITE BOUND-WHEN-USB)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE DEFAULT-<-2)) (9 9 (:REWRITE DEFAULT-<-1)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 1 (:REWRITE <-OF---AND--)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (2 2 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (2 2 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP) (SLICE-TOO-HIGH-IS-0 (40 1 (:REWRITE BVCHOP-IDENTITY)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (23 3 (:DEFINITION NATP)) (20 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (9 9 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (7 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (6 6 (:REWRITE BOUND-WHEN-USB)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE +-OF---AND-0)) (4 1 (:DEFINITION POSP)) (3 3 (:TYPE-PRESCRIPTION NATP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-+-2)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-BECOMES-BVCHOP (172 4 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (138 10 (:DEFINITION NATP)) (81 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (70 8 (:REWRITE BVCHOP-IDENTITY)) (41 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (36 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (31 17 (:REWRITE DEFAULT-<-1)) (26 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (25 25 (:REWRITE BOUND-WHEN-USB)) (21 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (20 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (20 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (19 17 (:REWRITE DEFAULT-<-2)) (18 18 (:TYPE-PRESCRIPTION NATP)) (14 14 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (12 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (10 10 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (10 10 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (8 8 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE BVCHOP-SUBST-CONSTANT)) (8 8 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) ) (SLICE-OUT-OF-ORDER (119 1 (:REWRITE BVCHOP-IDENTITY)) (113 1 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (48 6 (:DEFINITION NATP)) (44 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (24 2 (:REWRITE COMMUTATIVITY-OF-+)) (19 2 (:REWRITE COMMUTATIVITY-2-OF-+)) (16 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 12 (:REWRITE BOUND-WHEN-USB)) (9 9 (:REWRITE DEFAULT-<-2)) (9 9 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE DEFAULT-+-2)) (9 9 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 1 (:REWRITE LOGTAIL-BECOMES-0)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (5 5 (:TYPE-PRESCRIPTION NATP)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (5 1 (:DEFINITION NFIX)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (4 1 (:DEFINITION POSP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (1 1 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (BVCHOP-OF-SLICE (1246 17 (:REWRITE BVCHOP-IDENTITY)) (1139 13 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (782 104 (:DEFINITION NATP)) (590 56 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (440 13 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (310 13 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (245 9 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (226 162 (:REWRITE DEFAULT-<-1)) (221 81 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (218 218 (:REWRITE BOUND-WHEN-USB)) (202 18 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (162 162 (:REWRITE DEFAULT-<-2)) (137 137 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (115 115 (:TYPE-PRESCRIPTION NATP)) (104 104 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (104 104 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (103 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (92 92 (:REWRITE DEFAULT-+-2)) (92 92 (:REWRITE DEFAULT-+-1)) (81 81 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (80 8 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (68 68 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (68 68 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (65 13 (:DEFINITION NFIX)) (64 8 (:REWRITE LOGTAIL-NON-NEG)) (64 8 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (60 15 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (56 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (52 17 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (50 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (46 46 (:REWRITE FOLD-CONSTS-IN-+)) (44 44 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (44 44 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (44 44 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (44 44 (:REWRITE UBP-LONGER-BETTER)) (43 43 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (43 43 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (34 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (34 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (32 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 28 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (28 28 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (20 20 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (20 20 (:LINEAR EXPT-BOUND-LINEAR)) (19 19 (:TYPE-PRESCRIPTION POSP)) (17 17 (:REWRITE BVCHOP-SUBST-CONSTANT)) (17 17 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (16 16 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (16 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (16 16 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 4 (:REWRITE LOGTAIL-BECOMES-0)) (16 4 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (16 4 (:REWRITE +-OF---AND-0)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (10 10 (:LINEAR EXPT-BOUND-LINEAR-2)) (8 2 (:DEFINITION POSP)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (LOGTAIL-OF-BVCHOP (1244 23 (:REWRITE MOD-WHEN-MULTIPLE)) (1066 26 (:REWRITE MOD-WHEN-<-OF-0)) (783 44 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE)) (741 23 (:REWRITE MOD-WHEN-<)) (532 44 (:REWRITE INTEGERP-OF-*)) (522 62 (:REWRITE DEFAULT-UNARY-/)) (439 13 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (406 44 (:REWRITE MULTIPLE-WHEN-MOD-0-CHEAP)) (403 202 (:REWRITE DEFAULT-<-2)) (396 125 (:REWRITE DEFAULT-*-2)) (391 125 (:REWRITE DEFAULT-*-1)) (352 202 (:REWRITE DEFAULT-<-1)) (300 22 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (229 3 (:REWRITE <-OF-FLOOR-AND-0)) (223 13 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (212 44 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP-ALT)) (166 166 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (148 23 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (114 42 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (112 23 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (105 13 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (94 24 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (93 9 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (84 29 (:REWRITE DEFAULT-+-2)) (82 82 (:REWRITE BOUND-WHEN-USB)) (77 77 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (59 23 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (59 23 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (47 9 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (39 39 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (38 24 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (38 24 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (36 36 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (34 29 (:REWRITE DEFAULT-+-1)) (32 9 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (31 23 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (30 1 (:LINEAR EXPT-HALF-LINEAR)) (26 26 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (26 1 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (25 25 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (24 24 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (18 18 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (18 18 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (18 18 (:LINEAR <-OF-*-AND-*-LINEAR)) (13 13 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (13 13 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (12 4 (:REWRITE <-OF-1-AND-EXPT-GEN)) (9 9 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) ) (SLICE-OF-BVCHOP-LOW (1450 32 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (476 14 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (285 285 (:REWRITE BOUND-WHEN-USB)) (240 212 (:REWRITE DEFAULT-<-1)) (222 182 (:REWRITE DEFAULT-+-2)) (212 212 (:REWRITE DEFAULT-<-2)) (182 182 (:REWRITE DEFAULT-+-1)) (160 32 (:DEFINITION NFIX)) (158 158 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (156 39 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (141 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (130 130 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (130 130 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (130 130 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (130 130 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (126 14 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (91 41 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (84 42 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (81 81 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (81 81 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (81 81 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (81 81 (:REWRITE UBP-LONGER-BETTER)) (81 37 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (80 40 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (80 28 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (70 14 (:REWRITE LOGTAIL-NON-NEG)) (70 14 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (63 63 (:REWRITE +-COMBINE-CONSTANTS)) (56 28 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (48 48 (:TYPE-PRESCRIPTION POSP)) (48 48 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (48 48 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (48 48 (:REWRITE FOLD-CONSTS-IN-+)) (44 44 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (42 42 (:REWRITE BVCHOP-SUBST-CONSTANT)) (42 12 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (41 41 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (40 8 (:REWRITE +-OF---AND-0)) (37 37 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (36 9 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (34 17 (:REWRITE UNICITY-OF-0)) (32 32 (:DEFINITION FIX)) (30 15 (:REWRITE +-OF-+-OF---SAME)) (30 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (28 28 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (28 28 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (28 28 (:LINEAR EXPT-BOUND-LINEAR)) (28 28 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (24 6 (:DEFINITION POSP)) (23 23 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (17 17 (:REWRITE INVERSE-OF-+)) (14 14 (:REWRITE DEFAULT-UNARY-MINUS)) (14 14 (:LINEAR EXPT-BOUND-LINEAR-2)) (10 10 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (SLICE-OF-BVCHOP-TIGHTEN (352 9 (:REWRITE BVCHOP-IDENTITY)) (220 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (105 9 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (80 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (51 51 (:REWRITE BOUND-WHEN-USB)) (36 36 (:REWRITE DEFAULT-<-2)) (36 36 (:REWRITE DEFAULT-<-1)) (35 35 (:REWRITE DEFAULT-+-2)) (35 35 (:REWRITE DEFAULT-+-1)) (34 14 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (26 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (23 23 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (20 20 (:TYPE-PRESCRIPTION NATP)) (20 4 (:DEFINITION NFIX)) (18 9 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (16 16 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (16 16 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (16 16 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (16 16 (:REWRITE UBP-LONGER-BETTER)) (15 15 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (15 15 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (15 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 14 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (13 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (12 3 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (12 3 (:REWRITE +-OF---AND-0)) (11 11 (:TYPE-PRESCRIPTION POSP)) (9 9 (:REWRITE BVCHOP-SUBST-CONSTANT)) (9 9 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (9 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (9 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 8 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (8 8 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:DEFINITION POSP)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (5 5 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 2 (:REWRITE +-OF-+-OF---SAME)) (2 2 (:REWRITE INVERSE-OF-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) ) (SLICE-OF-BVCHOP-TOO-HIGH (94 4 (:REWRITE BVCHOP-IDENTITY)) (40 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (24 15 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (15 15 (:REWRITE DEFAULT-<-1)) (14 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (10 1 (:REWRITE LOGTAIL-OF-BVCHOP)) (9 9 (:TYPE-PRESCRIPTION NATP)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:REWRITE +-OF---AND-0)) (8 2 (:DEFINITION POSP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (7 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) ) (SLICE-OF-BVCHOP-LOW-GEN (48 7 (:REWRITE SLICE-TOO-HIGH-IS-0)) (30 30 (:REWRITE DEFAULT-<-2)) (30 30 (:REWRITE DEFAULT-<-1)) (28 4 (:REWRITE BVCHOP-IDENTITY)) (27 7 (:REWRITE SLICE-OUT-OF-ORDER)) (24 24 (:REWRITE BOUND-WHEN-USB)) (20 20 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (13 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (12 7 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 10 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 7 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (8 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (7 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-BVCHOP-TYPE)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (UNSIGNED-BYTE-P-OF-SLICE-GEN (221 3 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (202 2 (:REWRITE BVCHOP-IDENTITY)) (89 3 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (75 9 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (48 4 (:REWRITE COMMUTATIVITY-OF-+)) (38 4 (:REWRITE COMMUTATIVITY-2-OF-+)) (37 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (26 26 (:REWRITE BOUND-WHEN-USB)) (23 23 (:REWRITE DEFAULT-+-2)) (23 23 (:REWRITE DEFAULT-+-1)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (15 3 (:DEFINITION NFIX)) (14 2 (:REWRITE LOGTAIL-BECOMES-0)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (13 13 (:REWRITE UBP-LONGER-BETTER)) (12 12 (:TYPE-PRESCRIPTION NATP)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (12 12 (:REWRITE +-COMBINE-CONSTANTS)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 2 (:DEFINITION POSP)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (3 3 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) ) (SLICE-WHEN-LOW-IS-NEGATIVE (829 6 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (219 6 (:REWRITE MOD-WHEN-MULTIPLE)) (187 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (169 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (161 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (156 6 (:REWRITE MOD-WHEN-<)) (133 10 (:REWRITE INTEGERP-OF-*)) (115 40 (:REWRITE DEFAULT-<-2)) (94 10 (:REWRITE DEFAULT-UNARY-/)) (79 40 (:REWRITE DEFAULT-<-1)) (72 5 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (65 65 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (52 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (52 10 (:REWRITE DEFAULT-*-2)) (37 12 (:REWRITE DEFAULT-UNARY-MINUS)) (36 6 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (36 6 (:REWRITE MOD-WHEN-<-OF-0)) (32 6 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (28 28 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (28 28 (:LINEAR EXPT-BOUND-LINEAR)) (24 24 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE)) (22 2 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (19 19 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (18 10 (:REWRITE DEFAULT-*-1)) (17 17 (:REWRITE BOUND-WHEN-USB)) (14 14 (:LINEAR EXPT-BOUND-LINEAR-2)) (14 6 (:REWRITE DEFAULT-+-2)) (10 10 (:REWRITE INTEGERP-OF-POWER2-HACK)) (10 6 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (10 6 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (7 7 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (5 5 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) ) (UNSIGNED-BYTE-P-OF-SLICE-HELPER (146 2 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (83 1 (:REWRITE BVCHOP-IDENTITY)) (75 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (54 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (48 4 (:REWRITE COMMUTATIVITY-OF-+)) (38 4 (:REWRITE COMMUTATIVITY-2-OF-+)) (34 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (18 18 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-+-1)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (10 2 (:DEFINITION NFIX)) (9 9 (:REWRITE BOUND-WHEN-USB)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 8 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (7 1 (:REWRITE LOGTAIL-BECOMES-0)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 1 (:DEFINITION POSP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (UNSIGNED-BYTE-P-OF-SLICE (30 30 (:REWRITE BOUND-WHEN-USB)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (20 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (14 14 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (14 14 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (9 9 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (9 3 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (7 7 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (BVCHOP-OF-SLICE-BOTH (155 125 (:REWRITE DEFAULT-+-2)) (143 125 (:REWRITE DEFAULT-+-1)) (127 88 (:REWRITE DEFAULT-<-1)) (111 21 (:REWRITE SLICE-TOO-HIGH-IS-0)) (106 88 (:REWRITE DEFAULT-<-2)) (68 38 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (58 58 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (57 57 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (54 54 (:REWRITE BOUND-WHEN-USB)) (54 22 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (51 15 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (49 49 (:REWRITE FOLD-CONSTS-IN-+)) (49 49 (:REWRITE +-COMBINE-CONSTANTS)) (44 44 (:REWRITE DEFAULT-UNARY-MINUS)) (38 38 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (38 38 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (38 38 (:REWRITE UBP-LONGER-BETTER)) (38 38 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (36 24 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (36 21 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (32 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (24 24 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (23 23 (:REWRITE BVCHOP-SUBST-CONSTANT)) (22 22 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (21 21 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (21 21 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (21 21 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (21 21 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (18 3 (:REWRITE DEFAULT-*-2)) (17 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (12 4 (:REWRITE <-OF-+-CANCEL-1+-2)) (11 11 (:TYPE-PRESCRIPTION NATP)) (11 11 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (10 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (10 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (6 2 (:REWRITE INTEGERP-OF-+-WHEN-INTEGERP-1-CHEAP)) (5 5 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-*-1)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:DEFINITION FIX)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) ) (LOGTAIL-OF-BVCHOP-BECOMES-SLICE (261 13 (:REWRITE BVCHOP-IDENTITY)) (173 5 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (58 41 (:REWRITE DEFAULT-<-1)) (57 3 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (55 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (45 45 (:REWRITE BOUND-WHEN-USB)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (41 41 (:REWRITE DEFAULT-<-2)) (41 9 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (38 8 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (37 29 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (29 29 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (29 29 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (29 29 (:REWRITE UBP-LONGER-BETTER)) (26 23 (:REWRITE DEFAULT-+-2)) (24 6 (:DEFINITION POSP)) (23 23 (:REWRITE DEFAULT-+-1)) (23 9 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (21 21 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (20 5 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (20 5 (:REWRITE +-OF---AND-0)) (20 4 (:DEFINITION NFIX)) (19 9 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (17 17 (:TYPE-PRESCRIPTION NATP)) (17 17 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (15 15 (:TYPE-PRESCRIPTION POSP)) (14 9 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 9 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (13 13 (:REWRITE BVCHOP-SUBST-CONSTANT)) (13 13 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (11 11 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (11 11 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (9 9 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (9 5 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (8 4 (:REWRITE +-OF-+-OF---SAME)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (7 7 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) ) (SLICE-ALT-DEF (36 6 (:REWRITE SLICE-TOO-HIGH-IS-0)) (35 5 (:REWRITE BVCHOP-IDENTITY)) (16 6 (:REWRITE SLICE-OUT-OF-ORDER)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (15 9 (:REWRITE DEFAULT-<-1)) (14 8 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (11 6 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 10 (:REWRITE UBP-LONGER-BETTER)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (9 9 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (6 6 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (5 5 (:REWRITE BVCHOP-SUBST-CONSTANT)) (5 5 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE BOUND-WHEN-USB)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-OF-LOGTAIL (115 2 (:REWRITE BVCHOP-IDENTITY)) (108 1 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (33 33 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (29 29 (:REWRITE DEFAULT-+-2)) (29 29 (:REWRITE DEFAULT-+-1)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (15 3 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (15 3 (:REWRITE LOGTAIL-BECOMES-0)) (14 14 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE +-COMBINE-CONSTANTS)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (11 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (10 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 2 (:DEFINITION POSP)) (9 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (7 1 (:DEFINITION NFIX)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (5 5 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (5 5 (:REWRITE UBP-LONGER-BETTER)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 3 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 1 (:REWRITE +-OF-+-OF---SAME)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (BVCHOP-OF-LOGTAIL (265 19 (:REWRITE BVCHOP-IDENTITY)) (156 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (142 6 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (97 61 (:REWRITE DEFAULT-<-2)) (96 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (80 8 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (72 61 (:REWRITE DEFAULT-<-1)) (61 61 (:REWRITE BOUND-WHEN-USB)) (43 43 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (41 41 (:TYPE-PRESCRIPTION NATP)) (40 40 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (38 19 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (36 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (30 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (28 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (27 27 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (27 27 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (27 27 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (27 27 (:REWRITE UBP-LONGER-BETTER)) (25 6 (:DEFINITION NFIX)) (23 23 (:TYPE-PRESCRIPTION POSP)) (22 22 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (22 22 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (20 4 (:REWRITE LOGTAIL-NON-NEG)) (20 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (19 19 (:REWRITE BVCHOP-SUBST-CONSTANT)) (19 19 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (18 4 (:DEFINITION POSP)) (16 16 (:REWRITE DEFAULT-+-2)) (16 16 (:REWRITE DEFAULT-+-1)) (16 16 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (13 13 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (13 13 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (13 13 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 12 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (12 12 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (8 4 (:REWRITE UNICITY-OF-0)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) ) (BVCHOP-OF-LOGTAIL-BECOMES-SLICE (196 6 (:REWRITE BVCHOP-IDENTITY)) (84 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (48 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (47 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (41 22 (:REWRITE DEFAULT-<-1)) (41 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (40 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (22 22 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE BOUND-WHEN-USB)) (20 4 (:DEFINITION NFIX)) (19 16 (:REWRITE DEFAULT-+-2)) (17 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 16 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE DEFAULT-+-1)) (15 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (15 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:REWRITE LOGTAIL-BECOMES-0)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (7 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 1 (:DEFINITION POSP)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-OF-SLICE (733 73 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (390 11 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (333 61 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (258 225 (:REWRITE DEFAULT-+-2)) (244 244 (:REWRITE BOUND-WHEN-USB)) (225 225 (:REWRITE DEFAULT-+-1)) (222 50 (:DEFINITION POSP)) (208 208 (:REWRITE DEFAULT-<-2)) (208 208 (:REWRITE DEFAULT-<-1)) (187 187 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (187 187 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (187 187 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (187 187 (:REWRITE UBP-LONGER-BETTER)) (148 3 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (110 110 (:REWRITE +-COMBINE-CONSTANTS)) (100 100 (:REWRITE FOLD-CONSTS-IN-+)) (90 90 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (80 80 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (67 67 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (65 65 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (55 11 (:DEFINITION NFIX)) (52 52 (:TYPE-PRESCRIPTION POSP)) (49 39 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (47 47 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (41 39 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (41 39 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (39 39 (:REWRITE BVCHOP-SUBST-CONSTANT)) (33 30 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (32 6 (:REWRITE +-OF---AND-0)) (30 30 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (30 30 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (30 30 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (30 30 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 7 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (25 25 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (25 25 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (25 25 (:REWRITE DEFAULT-UNARY-MINUS)) (22 22 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (22 22 (:LINEAR EXPT-BOUND-LINEAR)) (22 22 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (18 18 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (11 11 (:LINEAR EXPT-BOUND-LINEAR-2)) (8 1 (:REWRITE <-OF-+-CANCEL-1+-2+)) (2 2 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-TOO-HIGH-HELPER (18 18 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (6 1 (:REWRITE SLICE-OUT-OF-ORDER)) (4 1 (:REWRITE DEFAULT-<-1)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-TOO-HIGH-LEMMA (12 12 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) ) (SLICE-UPPER-BOUND-LINEAR (68 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (33 33 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (31 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (11 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (8 8 (:REWRITE BOUND-WHEN-USB)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE +-COMBINE-CONSTANTS)) (3 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) ) (SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION (30 30 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (30 30 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 3 (:REWRITE DEFAULT-+-2)) (7 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (3 3 (:REWRITE DEFAULT-+-1)) (3 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (<-OF-SLICE-AND-CONSTANT (99 99 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (22 8 (:REWRITE DEFAULT-+-2)) (18 7 (:REWRITE DEFAULT-<-1)) (14 2 (:REWRITE SLICE-TOO-HIGH-IS-0)) (11 7 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE BOUND-WHEN-USB)) (6 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-OUT-OF-ORDER)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (LOGTAIL-BECOMES-SLICE (91 4 (:REWRITE LOGTAIL-BECOMES-0)) (74 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (35 35 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (23 18 (:REWRITE DEFAULT-+-2)) (23 18 (:REWRITE DEFAULT-+-1)) (19 19 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (19 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (15 15 (:REWRITE BOUND-WHEN-USB)) (12 3 (:REWRITE <-OF-EXPT-AND-EXPT)) (12 3 (:DEFINITION POSP)) (11 1 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (10 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 1 (:REWRITE DEFAULT-*-2)) (4 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:TYPE-PRESCRIPTION NATP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-*-1)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (SLICE-MONOTONE (101 35 (:REWRITE BOUND-WHEN-USB)) (53 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (44 6 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (38 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (36 30 (:REWRITE DEFAULT-+-2)) (30 30 (:REWRITE DEFAULT-+-1)) (30 24 (:REWRITE DEFAULT-<-2)) (24 24 (:REWRITE DEFAULT-<-1)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (12 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (10 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE +-COMBINE-CONSTANTS)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:DEFINITION POSP)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (SLICE-OF-EXPT (78 8 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (69 4 (:REWRITE BVCHOP-IDENTITY)) (48 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (46 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (37 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (34 34 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (34 34 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (27 27 (:REWRITE BOUND-WHEN-USB)) (25 11 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (20 20 (:REWRITE DEFAULT-<-2)) (20 20 (:REWRITE DEFAULT-<-1)) (20 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (17 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (12 3 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (11 11 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 11 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (9 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 2 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (5 5 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (3 3 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) ) (SLICE-OF-SLICE-GEN-BETTER (110 80 (:REWRITE DEFAULT-+-2)) (85 17 (:REWRITE SLICE-OUT-OF-ORDER)) (80 80 (:REWRITE DEFAULT-+-1)) (51 51 (:REWRITE DEFAULT-<-2)) (51 51 (:REWRITE DEFAULT-<-1)) (37 37 (:REWRITE BOUND-WHEN-USB)) (28 16 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (27 27 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (23 23 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (22 22 (:REWRITE +-COMBINE-CONSTANTS)) (20 20 (:REWRITE FOLD-CONSTS-IN-+)) (18 18 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (18 18 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (17 17 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (17 17 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (17 16 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (16 16 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (15 5 (:REWRITE <-OF-+-CANCEL-1+-1+)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (12 12 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (9 9 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-WHEN-BVCHOP-KNOWN (395 22 (:REWRITE LOGTAIL-BECOMES-0)) (338 45 (:REWRITE BVCHOP-IDENTITY)) (197 42 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (148 22 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (143 107 (:REWRITE DEFAULT-<-1)) (122 22 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (118 118 (:REWRITE BOUND-WHEN-USB)) (107 107 (:REWRITE DEFAULT-<-2)) (106 22 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (103 87 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (87 87 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (87 87 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (87 87 (:REWRITE UBP-LONGER-BETTER)) (80 20 (:DEFINITION POSP)) (80 10 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (79 37 (:REWRITE DEFAULT-+-2)) (74 74 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (74 42 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (68 43 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (66 42 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (63 63 (:TYPE-PRESCRIPTION POSP)) (52 52 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (48 42 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (47 37 (:REWRITE DEFAULT-+-1)) (46 16 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (45 45 (:REWRITE BVCHOP-SUBST-CONSTANT)) (45 45 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (45 22 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (44 43 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (41 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (35 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (18 18 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (12 12 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (12 12 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (12 12 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 2 (:REWRITE DEFAULT-*-2)) (7 7 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE DEFAULT-*-1)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-SUBST-IN-CONSTANT (139 104 (:REWRITE DEFAULT-+-2)) (104 104 (:REWRITE DEFAULT-+-1)) (77 11 (:REWRITE SLICE-TOO-HIGH-IS-0)) (48 48 (:REWRITE BOUND-WHEN-USB)) (44 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (41 41 (:REWRITE DEFAULT-<-2)) (41 41 (:REWRITE DEFAULT-<-1)) (25 25 (:REWRITE FOLD-CONSTS-IN-+)) (25 25 (:REWRITE +-COMBINE-CONSTANTS)) (21 11 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (20 20 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (20 20 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (18 18 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 16 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (16 4 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (13 13 (:REWRITE DEFAULT-UNARY-MINUS)) (13 13 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (13 13 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (12 12 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (12 12 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (12 12 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (12 12 (:LINEAR EXPT-BOUND-LINEAR)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (11 11 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (10 10 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (6 6 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-SUBST-IN-CONSTANT-ALT) (<-OF-SLICE-SAME (262 10 (:REWRITE BVCHOP-IDENTITY)) (196 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (92 8 (:REWRITE COMMUTATIVITY-OF-+)) (90 10 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (72 8 (:REWRITE COMMUTATIVITY-2-OF-+)) (60 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (49 7 (:REWRITE LOGTAIL-BECOMES-0)) (48 33 (:REWRITE DEFAULT-+-2)) (33 33 (:REWRITE DEFAULT-+-1)) (30 30 (:REWRITE BOUND-WHEN-USB)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (22 20 (:REWRITE DEFAULT-<-1)) (21 21 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (21 21 (:REWRITE UBP-LONGER-BETTER)) (21 21 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (21 21 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (20 20 (:REWRITE DEFAULT-<-2)) (20 20 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (20 10 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (20 4 (:DEFINITION NFIX)) (18 10 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (18 10 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (13 13 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (13 13 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (10 10 (:TYPE-PRESCRIPTION POSP)) (10 10 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (9 9 (:REWRITE FOLD-CONSTS-IN-+)) (9 9 (:REWRITE +-COMBINE-CONSTANTS)) (8 4 (:REWRITE UNICITY-OF-0)) (7 7 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (7 7 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (6 6 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE INVERSE-OF-+)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:DEFINITION FIX)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) ) (SLICE-WHEN-INDICES-ARE-NEGATIVE (295 21 (:REWRITE BVCHOP-IDENTITY)) (167 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (107 29 (:REWRITE DEFAULT-<-1)) (56 7 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (29 29 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (26 26 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (26 26 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (22 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (21 21 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (21 21 (:REWRITE UBP-LONGER-BETTER)) (21 21 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (20 11 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (19 19 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (19 19 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (19 19 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (17 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (11 11 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (11 11 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (11 11 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (11 11 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (10 10 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (10 10 (:REWRITE BOUND-WHEN-USB)) (3 3 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) ) (SLICE-SAME-TYPE (217 6 (:REWRITE BVCHOP-IDENTITY)) (128 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (63 3 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (46 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (45 22 (:REWRITE DEFAULT-<-1)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (40 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (26 26 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (26 26 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (24 4 (:DEFINITION NATP)) (22 22 (:REWRITE DEFAULT-<-2)) (16 16 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 16 (:REWRITE BOUND-WHEN-USB)) (15 3 (:DEFINITION NFIX)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (14 14 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (14 2 (:REWRITE LOGTAIL-BECOMES-0)) (12 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (12 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (8 4 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (8 2 (:DEFINITION POSP)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (6 6 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (6 6 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (6 6 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (6 6 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) ) (SLICE-OF-MOD-OF-EXPT (1031 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (1006 8 (:REWRITE MOD-WHEN-<)) (591 591 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (396 12 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (384 12 (:LINEAR EXPT-HALF-LINEAR)) (380 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (369 69 (:LINEAR EXPT-BOUND-LINEAR-2)) (341 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (336 8 (:REWRITE MOD-WHEN-MULTIPLE)) (215 86 (:REWRITE DEFAULT-<-2)) (189 104 (:REWRITE DEFAULT-+-2)) (176 16 (:REWRITE DEFAULT-UNARY-/)) (175 105 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (168 28 (:REWRITE DEFAULT-*-2)) (164 104 (:REWRITE DEFAULT-+-1)) (157 86 (:REWRITE DEFAULT-<-1)) (153 114 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (124 4 (:REWRITE LOGTAIL-BECOMES-0)) (111 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD-WHEN-<=-OF-EXPT)) (96 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (91 91 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE)) (91 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (89 16 (:REWRITE INTEGERP-OF-*)) (67 18 (:REWRITE DEFAULT-UNARY-MINUS)) (50 50 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (50 10 (:REWRITE BVCHOP-OF-MOD-OF-EXPT-2)) (48 8 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (45 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (42 42 (:REWRITE BOUND-WHEN-USB)) (40 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (37 28 (:REWRITE DEFAULT-*-1)) (34 9 (:REWRITE MOD-WHEN-<-OF-0)) (33 8 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (30 30 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (30 30 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (30 30 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (30 30 (:REWRITE UBP-LONGER-BETTER)) (29 29 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (25 5 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (25 3 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (22 22 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (22 22 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (22 22 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (19 19 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (19 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (18 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 18 (:REWRITE BVCHOP-SUBST-CONSTANT)) (17 8 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (16 16 (:REWRITE INTEGERP-OF-POWER2-HACK)) (16 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (16 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 16 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (16 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD2)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (12 12 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (12 12 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (12 3 (:DEFINITION POSP)) (12 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (11 3 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (10 10 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (10 10 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (10 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (9 9 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (8 8 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (8 8 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (EQUAL-OF-LOGTAIL-AND-SLICE (80 1 (:REWRITE BVCHOP-IDENTITY)) (53 53 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (49 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (37 37 (:REWRITE BOUND-WHEN-USB)) (31 6 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (27 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (26 26 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE DEFAULT-<-1)) (20 5 (:DEFINITION POSP)) (19 19 (:REWRITE DEFAULT-+-2)) (19 19 (:REWRITE DEFAULT-+-1)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 9 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (SLICE-OF-+-OF--1-AND-EXPT-SAME (54 1 (:REWRITE BVCHOP-IDENTITY)) (43 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (35 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (31 1 (:REWRITE USB-PLUS-FROM-BOUNDS)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (15 7 (:REWRITE DEFAULT-+-2)) (15 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (13 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (12 7 (:REWRITE DEFAULT-+-1)) (11 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (9 9 (:REWRITE BOUND-WHEN-USB)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (8 1 (:REWRITE UNSIGNED-BYTE-P-OF-1)) (8 1 (:REWRITE COMMUTATIVITY-OF-+)) (7 7 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (7 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (7 1 (:REWRITE DEFAULT-UNARY-/)) (7 1 (:DEFINITION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST-ARG2)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE BVCHOP-CHOP-LEADING-CONSTANT)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (SLICE-LEIBNIZ) (BVCHOP-OF-FLOOR-OF-EXPT-OF-2 (332 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (84 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (79 4 (:REWRITE FLOOR-WHEN-<)) (73 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (52 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (49 3 (:REWRITE BVCHOP-IDENTITY)) (44 1 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (41 1 (:REWRITE <-OF-FLOOR-AND-0)) (36 2 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (33 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (33 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (32 14 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (32 1 (:REWRITE <-OF-/-AND-CONSTANT)) (30 21 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE DEFAULT-<-1)) (21 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (18 15 (:REWRITE DEFAULT-+-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (16 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (15 15 (:REWRITE DEFAULT-+-1)) (14 14 (:LINEAR EXPT-BOUND-LINEAR)) (14 2 (:REWRITE DEFAULT-UNARY-/)) (13 13 (:TYPE-PRESCRIPTION FLOOR)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (13 13 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (9 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (9 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 2 (:REWRITE DEFAULT-*-2)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:LINEAR EXPT-BOUND-LINEAR-2)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 1 (:REWRITE <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE)) (5 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (5 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (5 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (4 4 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (4 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (4 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (3 1 (:REWRITE <-OF-1-AND-EXPT-GEN)) (3 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-*-1)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-LINEAR)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-0-AND-EXPT)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (BVCHOP-OF-FLOOR-OF-EXPT-OF-2-CONSTANT-VERSION (133 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (42 3 (:REWRITE BVCHOP-IDENTITY)) (38 2 (:REWRITE SLICE-OUT-OF-ORDER)) (32 20 (:REWRITE DEFAULT-+-2)) (31 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (30 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (30 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (29 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (27 27 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (24 20 (:REWRITE DEFAULT-+-1)) (24 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (24 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (21 3 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (19 1 (:REWRITE <-OF-FLOOR-AND-0)) (17 17 (:REWRITE BOUND-WHEN-USB)) (14 2 (:REWRITE SLICE-TOO-HIGH-IS-0)) (13 13 (:TYPE-PRESCRIPTION FLOOR)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (12 6 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (12 4 (:REWRITE FLOOR-WHEN-<)) (12 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 2 (:REWRITE <-OF-+-CANCEL-1+-1)) (9 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 8 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 2 (:REWRITE +-OF---AND-0)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 1 (:LINEAR <-OF-EXPT-OF-ONE-LESS-OF-INTEGER-LENGTH-LINEAR)) (6 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 2 (:REWRITE COMMUTATIVITY-OF-*)) (6 2 (:REWRITE <-OF-+-CANCEL-2-2)) (5 5 (:REWRITE DEFAULT-*-2)) (5 5 (:REWRITE DEFAULT-*-1)) (5 1 (:REWRITE <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE)) (5 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (4 4 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (4 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (4 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (4 4 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (3 1 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-UNARY-/)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-LINEAR)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE EQUAL-OF-EXPT-AND-CONSTANT)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (BITP-OF-SLICE-SAME-TYPE) (SLICE-SAME-WHEN-NOT-0) (SLICE-BOUND-3 (182 182 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (182 182 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (37 17 (:REWRITE DEFAULT-+-2)) (30 15 (:REWRITE DEFAULT-<-2)) (20 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (17 17 (:REWRITE DEFAULT-+-1)) (15 15 (:REWRITE DEFAULT-<-1)) (10 10 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 5 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (5 5 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (5 5 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (5 5 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (5 5 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (SLICE-BOUND-3-CONSTANT-VERSION) (SLICE-OF-TIMES-OF-EXPT (572 4 (:REWRITE FLOOR-WHEN-<)) (341 6 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (116 2 (:REWRITE FLOOR-OF-1-WHEN-INTEGERP)) (102 1 (:REWRITE <-OF-*-OF-/-ARG1-ARG3)) (96 24 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (91 2 (:REWRITE INTEGERP-OF-*)) (91 1 (:REWRITE <-OF-*-OF-/-ARG2-ALT)) (64 17 (:REWRITE DEFAULT-*-2)) (48 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (47 17 (:REWRITE DEFAULT-*-1)) (45 1 (:REWRITE <-OF-*-OF-/-ARG2)) (32 23 (:REWRITE DEFAULT-<-2)) (32 23 (:REWRITE DEFAULT-<-1)) (32 4 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (32 1 (:REWRITE <-OF-/-AND-CONSTANT)) (31 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (28 4 (:REWRITE DEFAULT-UNARY-/)) (28 2 (:REWRITE BVCHOP-IDENTITY)) (27 27 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (27 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (24 24 (:LINEAR EXPT-BOUND-LINEAR)) (21 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (21 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (21 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (20 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (14 14 (:REWRITE DEFAULT-+-2)) (14 14 (:REWRITE DEFAULT-+-1)) (14 14 (:REWRITE BOUND-WHEN-USB)) (12 12 (:LINEAR EXPT-BOUND-LINEAR-2)) (12 12 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (12 12 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (12 12 (:LINEAR <-OF-*-AND-*-LINEAR)) (12 4 (:REWRITE <-OF-1-AND-EXPT-GEN)) (12 1 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (10 2 (:REWRITE UNICITY-OF-1)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (8 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 1 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (8 1 (:REWRITE INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2)) (8 1 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (7 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (6 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:TYPE-PRESCRIPTION FLOOR)) (4 4 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (4 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (4 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (3 1 (:REWRITE FLOOR-OF-*-OF-EXPT-AND-EXPT)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (2 2 (:REWRITE <-OF-0-AND-EXPT)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (1 1 (:REWRITE INTEGERP-OF-POWER2-HACK-ANOTHER-FACTOR-ALT)) ) (SLICE-OF-TIMES-OF-EXPT-ALT (46 4 (:REWRITE SLICE-TOO-HIGH-IS-0)) (26 3 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (24 4 (:REWRITE SLICE-OUT-OF-ORDER)) (24 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT-ALT)) (14 14 (:REWRITE DEFAULT-<-2)) (14 14 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE DEFAULT-+-1)) (10 10 (:REWRITE BOUND-WHEN-USB)) (10 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (10 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 4 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (9 3 (:REWRITE DEFAULT-*-2)) (8 2 (:REWRITE <-OF-+-CANCEL-2-2)) (7 7 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (7 7 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (7 7 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 3 (:REWRITE DEFAULT-*-1)) (6 2 (:REWRITE <-OF-+-CANCEL-1+-1+)) (6 2 (:REWRITE +-OF---AND-0)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (4 4 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (3 3 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-OF-ASH (280 2 (:REWRITE BVCHOP-IDENTITY)) (268 2 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (132 2 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (125 3 (:REWRITE FLOOR-WHEN-<)) (124 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (62 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (31 31 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (30 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (29 20 (:REWRITE DEFAULT-<-1)) (28 28 (:REWRITE DEFAULT-+-2)) (28 28 (:REWRITE DEFAULT-+-1)) (28 20 (:REWRITE DEFAULT-<-2)) (23 3 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (20 2 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (19 19 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (18 8 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (16 5 (:REWRITE DEFAULT-*-1)) (14 5 (:REWRITE DEFAULT-*-2)) (13 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (12 3 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (12 3 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (12 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (9 3 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (8 8 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 8 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 1 (:REWRITE DEFAULT-UNARY-/)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (6 6 (:LINEAR <-OF-*-AND-*-LINEAR)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 2 (:REWRITE EQUAL-OF-EXPT-SAME)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (SLICE-OF-ASH-RIGHT (589 6 (:REWRITE FLOOR-WHEN-<)) (163 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (152 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (146 146 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (102 3 (:REWRITE FLOOR-OF-1-WHEN-INTEGERP)) (87 2 (:REWRITE BVCHOP-IDENTITY)) (87 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (62 7 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (61 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (56 1 (:REWRITE <-OF-*-AND-0)) (55 23 (:REWRITE DEFAULT-<-1)) (52 4 (:REWRITE INTEGERP-OF-*)) (47 1 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (46 46 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (44 7 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (43 6 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (43 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (38 10 (:REWRITE DEFAULT-*-2)) (33 10 (:REWRITE DEFAULT-*-1)) (32 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (32 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (30 5 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (29 23 (:REWRITE DEFAULT-<-2)) (20 15 (:REWRITE DEFAULT-+-2)) (20 4 (:REWRITE INTEGERP-OF-EXPT2)) (18 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (17 17 (:REWRITE BOUND-WHEN-USB)) (17 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (15 15 (:REWRITE DEFAULT-+-1)) (15 5 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (13 13 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 1 (:REWRITE DEFAULT-UNARY-/)) (10 10 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (10 10 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (10 10 (:LINEAR <-OF-*-AND-*-LINEAR)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (7 2 (:LINEAR EXPT-BOUND-LINEAR)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE +-COMBINE-CONSTANTS)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-0-AND-EXPT)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) ) (SLICE-OF-ASH-SAME (190 10 (:REWRITE BVCHOP-IDENTITY)) (156 4 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (144 12 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (130 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (76 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (72 49 (:REWRITE DEFAULT-<-1)) (65 65 (:REWRITE BOUND-WHEN-USB)) (62 2 (:REWRITE FLOOR-WHEN-<)) (61 49 (:REWRITE DEFAULT-<-2)) (50 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (46 12 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (38 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (32 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (30 30 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (30 8 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (28 28 (:TYPE-PRESCRIPTION NATP)) (24 8 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (20 20 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 18 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (18 18 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 4 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (14 14 (:REWRITE DEFAULT-+-2)) (14 14 (:REWRITE DEFAULT-+-1)) (13 13 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (12 12 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (12 12 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (12 12 (:REWRITE UBP-LONGER-BETTER)) (12 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (12 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (12 2 (:REWRITE SLICE-OUT-OF-ORDER)) (10 10 (:TYPE-PRESCRIPTION POSP)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (10 10 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (10 10 (:LINEAR EXPT-BOUND-LINEAR)) (10 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (10 4 (:REWRITE DEFAULT-*-2)) (10 4 (:REWRITE DEFAULT-*-1)) (8 8 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 8 (:REWRITE DEFAULT-UNARY-MINUS)) (8 8 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 8 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (8 2 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (8 2 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 2 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (5 5 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 4 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (4 4 (:LINEAR <-OF-*-AND-*-LINEAR)) (2 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 2 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (2 2 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (2 2 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) ) (SLICES-SAME-WHEN-BVCHOPS-SAME (86 10 (:REWRITE BVCHOP-IDENTITY)) (32 8 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (30 18 (:REWRITE DEFAULT-<-1)) (29 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (22 4 (:REWRITE SLICE-TOO-HIGH-IS-0)) (19 8 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-<-2)) (16 8 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (14 14 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (13 13 (:REWRITE UBP-LONGER-BETTER)) (13 8 (:REWRITE DEFAULT-+-1)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (10 10 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 8 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 8 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (8 4 (:REWRITE SLICE-OUT-OF-ORDER)) (7 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (6 6 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (6 6 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (6 6 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (6 6 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (6 6 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (6 1 (:REWRITE DEFAULT-*-2)) (4 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE DEFAULT-*-1)) ) (SLICE-OF-+-OF--1-AND-EXPT (414 6 (:REWRITE BVCHOP-IDENTITY)) (207 3 (:REWRITE USB-PLUS-FROM-BOUNDS)) (114 6 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (97 41 (:REWRITE DEFAULT-+-2)) (81 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (50 41 (:REWRITE DEFAULT-+-1)) (49 22 (:LINEAR EXPT-BOUND-LINEAR)) (48 3 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1-AND-EXPT)) (46 46 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (44 26 (:REWRITE DEFAULT-<-1)) (35 26 (:REWRITE DEFAULT-<-2)) (31 22 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (24 6 (:REWRITE DEFAULT-*-2)) (24 6 (:REWRITE DEFAULT-*-1)) (23 23 (:REWRITE BOUND-WHEN-USB)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (18 3 (:REWRITE USB-OF-MASK-GEN)) (12 12 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 12 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (11 11 (:LINEAR EXPT-BOUND-LINEAR-2)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 9 (:REWRITE UBP-LONGER-BETTER)) (9 9 (:REWRITE FOLD-CONSTS-IN-+)) (9 9 (:REWRITE +-COMBINE-CONSTANTS)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (6 6 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (3 3 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (3 3 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-OF-EXPT-AND-CONSTANT)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-BOUND (55 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (49 1 (:DEFINITION UNSIGNED-BYTE-P)) (48 1 (:DEFINITION INTEGER-RANGE-P)) (41 41 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (31 31 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (24 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 3 (:REWRITE DEFAULT-+-2)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (5 2 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE DEFAULT-<-1)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (1 1 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (1 1 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BOUND-WHEN-USB)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) ) (SLICE-OF-+-OF-EXPT-GEN (758 20 (:REWRITE BVCHOP-IDENTITY)) (706 8 (:REWRITE USB-PLUS-FROM-BOUNDS)) (275 1 (:REWRITE LOGTAIL-OF-SUM)) (182 91 (:REWRITE DEFAULT-+-2)) (176 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (156 52 (:LINEAR EXPT-BOUND-LINEAR)) (150 91 (:REWRITE DEFAULT-+-1)) (142 86 (:REWRITE DEFAULT-<-2)) (139 86 (:REWRITE DEFAULT-<-1)) (128 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (121 121 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (96 96 (:REWRITE BOUND-WHEN-USB)) (94 14 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (84 12 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (83 18 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (76 52 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (76 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (72 32 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (56 27 (:LINEAR EXPT-BOUND-LINEAR-2)) (52 13 (:DEFINITION POSP)) (49 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (47 47 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (47 47 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (47 47 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (47 47 (:REWRITE UBP-LONGER-BETTER)) (38 38 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (38 38 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (32 32 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (32 17 (:REWRITE DEFAULT-UNARY-MINUS)) (30 16 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (30 1 (:LINEAR EXPT-HALF-LINEAR)) (28 14 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (28 14 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (28 14 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (27 27 (:TYPE-PRESCRIPTION POSP)) (26 26 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (26 14 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (26 1 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (21 21 (:REWRITE FOLD-CONSTS-IN-+)) (21 21 (:REWRITE +-COMBINE-CONSTANTS)) (21 14 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (20 20 (:REWRITE BVCHOP-SUBST-CONSTANT)) (20 20 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (20 2 (:REWRITE INTEGERP-OF-*)) (18 4 (:REWRITE DEFAULT-*-2)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 4 (:REWRITE DEFAULT-*-1)) (8 8 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (8 8 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (8 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (8 1 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (8 1 (:REWRITE INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2)) (7 7 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (3 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (1 1 (:REWRITE INTEGERP-OF-POWER2-HACK)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST-ARG2)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE BVCHOP-CHOP-LEADING-CONSTANT)) ) (*-OF-EXPT-AND-SLICE-SAME-LINEAR (227 2 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (106 106 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (77 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (52 1 (:REWRITE <-OF-/-AND-CONSTANT)) (48 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (47 12 (:REWRITE DEFAULT-*-2)) (36 11 (:REWRITE DEFAULT-+-2)) (33 12 (:REWRITE DEFAULT-*-1)) (27 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (20 11 (:REWRITE DEFAULT-+-1)) (20 8 (:REWRITE DEFAULT-<-2)) (17 8 (:REWRITE DEFAULT-<-1)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (8 8 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (8 8 (:REWRITE BOUND-WHEN-USB)) (7 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (6 3 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (4 4 (:LINEAR <-OF-*-AND-*-LINEAR)) (4 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (3 3 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (3 3 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (3 3 (:REWRITE SLICE-OUT-OF-ORDER)) (3 3 (:LINEAR EXPT-BOUND-LINEAR-2)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (1 1 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:DEFINITION IFIX)) ) (FLOOR-BOUND-LEMMA100 (230 2 (:REWRITE *-OF-FLOOR-OF-SAME-WHEN-MULTIPLE)) (137 3 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (134 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (133 1 (:LINEAR *-OF-FLOOR-UPPER-BOUND-LINEAR)) (96 2 (:LINEAR MOD-BOUND-LINEAR-ARG2)) (80 4 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (64 64 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (57 43 (:REWRITE DEFAULT-<-2)) (56 2 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (52 2 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (43 43 (:REWRITE DEFAULT-<-1)) (40 4 (:REWRITE MOD-WHEN-MULTIPLE)) (28 14 (:REWRITE DEFAULT-*-2)) (24 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (20 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (18 6 (:REWRITE FLOOR-WHEN-<)) (16 16 (:TYPE-PRESCRIPTION RATIONALP-OF-MOD)) (16 16 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE-2)) (16 16 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (16 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:REWRITE DEFAULT-*-1)) (12 12 (:REWRITE DEFAULT-UNARY-/)) (12 8 (:REWRITE INTEGERP-OF-*)) (12 4 (:REWRITE MOD-WHEN-<-OF-0)) (12 4 (:REWRITE MOD-WHEN-<)) (10 2 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (10 2 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (10 2 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (10 2 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (8 8 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (6 6 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (6 6 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (6 6 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (6 6 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (6 6 (:LINEAR <-OF-*-AND-*-LINEAR)) (6 2 (:REWRITE <-OF-/-AND-CONSTANT)) (6 2 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (6 2 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (5 1 (:LINEAR FLOOR-UPPER-BOUND-ALT-LINEAR)) (4 4 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (4 4 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (4 4 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:LINEAR <=-OF-/-LINEAR)) (4 2 (:LINEAR MOD-BOUND-LINEAR-ARG2-STRONG)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (2 1 (:REWRITE <-OF-0-AND-FLOOR)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (EQUAL-OF-SLICE-HELPER (4606 6 (:REWRITE *-OF-FLOOR-OF-SAME-WHEN-MULTIPLE)) (2542 24 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (1342 6 (:LINEAR MOD-BOUND-LINEAR-ARG2-STRONG)) (1131 205 (:REWRITE BOUND-WHEN-USB)) (924 6 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (906 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (906 6 (:LINEAR MOD-BOUND-LINEAR-ARG2)) (705 177 (:REWRITE DEFAULT-*-2)) (636 24 (:REWRITE MOD-WHEN-MULTIPLE)) (520 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (472 52 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (454 24 (:REWRITE MOD-WHEN-<)) (427 61 (:REWRITE DEFAULT-UNARY-/)) (402 42 (:REWRITE INTEGERP-OF-*)) (401 208 (:REWRITE DEFAULT-<-2)) (399 177 (:REWRITE DEFAULT-*-1)) (296 208 (:REWRITE DEFAULT-<-1)) (264 66 (:TYPE-PRESCRIPTION RATIONALP-OF-MOD)) (254 8 (:REWRITE <-OF-/-AND-CONSTANT)) (248 77 (:REWRITE DEFAULT-+-2)) (192 24 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (191 191 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (168 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (168 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (122 122 (:LINEAR EXPT-BOUND-LINEAR)) (116 29 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (107 27 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (99 27 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (98 77 (:REWRITE DEFAULT-+-1)) (96 24 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (96 24 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (90 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (83 4 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (76 76 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (66 66 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE-2)) (66 66 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (64 8 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (62 62 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (62 62 (:LINEAR <-OF-*-AND-*-LINEAR)) (61 61 (:LINEAR EXPT-BOUND-LINEAR-2)) (48 48 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (42 42 (:REWRITE INTEGERP-OF-POWER2-HACK)) (32 8 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (31 31 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (29 29 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (29 29 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (29 29 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (28 11 (:REWRITE +-COMBINE-CONSTANTS)) (25 25 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (24 24 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (24 24 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (24 24 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (24 24 (:REWRITE MOD-WHEN-<-OF-0)) (24 8 (:REWRITE EQUAL-OF-1-AND-EXPT)) (21 1 (:REWRITE *-OF---ARG2)) (17 17 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (16 16 (:LINEAR <=-OF-/-LINEAR)) (11 5 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (8 8 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (7 1 (:REWRITE <-OF-*-OF-/-ARG1-ARG2)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (2 2 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) ) (EQUAL-OF-SLICE (105 105 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (57 25 (:REWRITE DEFAULT-+-2)) (36 6 (:REWRITE BVCHOP-IDENTITY)) (34 25 (:REWRITE DEFAULT-+-1)) (32 12 (:REWRITE DEFAULT-<-1)) (32 8 (:REWRITE DEFAULT-*-2)) (21 12 (:REWRITE DEFAULT-<-2)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (17 17 (:REWRITE BOUND-WHEN-USB)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (11 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 8 (:REWRITE DEFAULT-*-1)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (4 4 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (4 4 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE SLICE-OUT-OF-ORDER)) (3 3 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (3 3 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-OF--1 (31 31 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (27 1 (:REWRITE BVCHOP-IDENTITY)) (25 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (19 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (16 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE BOUND-WHEN-USB)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (UNSIGNED-BYTE-P-OF-SLICE-LEMMA (95 1 (:REWRITE BVCHOP-IDENTITY)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (18 18 (:REWRITE BOUND-WHEN-USB)) (18 2 (:REWRITE COMMUTATIVITY-2-OF-+)) (14 1 (:REWRITE LOGTAIL-BECOMES-0)) (13 13 (:REWRITE DEFAULT-+-2)) (13 13 (:REWRITE DEFAULT-+-1)) (12 12 (:REWRITE DEFAULT-<-2)) (12 12 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (4 1 (:REWRITE <-OF-+-CANCEL-1-1+)) (4 1 (:DEFINITION POSP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE +-COMBINE-CONSTANTS)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (2 1 (:REWRITE UNICITY-OF-0)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE INVERSE-OF-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:DEFINITION FIX)) )
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/bv/.sys/slice%40useless-runes.lsp
lisp
(+-OF---AND-0) (SLICE-OF-0 (100 3 (:REWRITE BVCHOP-IDENTITY)) (98 5 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (67 9 (:DEFINITION NATP)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (28 2 (:REWRITE LOGTAIL-BECOMES-0)) (20 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (11 11 (:REWRITE DEFAULT-<-2)) (11 11 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (9 9 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:DEFINITION POSP)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:TYPE-PRESCRIPTION POSP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (5 5 (:REWRITE UBP-LONGER-BETTER)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 1 (:REWRITE <-OF---AND--)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (INTEGERP-OF-SLICE) (NATP-OF-SLICE) (SLICE-WHEN-VAL-IS-NOT-AN-INTEGER (100 3 (:REWRITE BVCHOP-IDENTITY)) (82 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (57 7 (:DEFINITION NATP)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (20 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (15 15 (:REWRITE BOUND-WHEN-USB)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE DEFAULT-<-2)) (9 9 (:REWRITE DEFAULT-<-1)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 1 (:REWRITE <-OF---AND--)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (2 2 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (2 2 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP) (SLICE-TOO-HIGH-IS-0 (40 1 (:REWRITE BVCHOP-IDENTITY)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (23 3 (:DEFINITION NATP)) (20 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (9 9 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (7 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (6 6 (:REWRITE BOUND-WHEN-USB)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE +-OF---AND-0)) (4 1 (:DEFINITION POSP)) (3 3 (:TYPE-PRESCRIPTION NATP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-+-2)) (3 3 (:REWRITE DEFAULT-+-1)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-BECOMES-BVCHOP (172 4 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (138 10 (:DEFINITION NATP)) (81 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (70 8 (:REWRITE BVCHOP-IDENTITY)) (41 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (36 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (31 17 (:REWRITE DEFAULT-<-1)) (26 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (25 25 (:REWRITE BOUND-WHEN-USB)) (21 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (20 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (20 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (19 17 (:REWRITE DEFAULT-<-2)) (18 18 (:TYPE-PRESCRIPTION NATP)) (14 14 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (12 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (10 10 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (10 10 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (8 8 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE DEFAULT-+-1)) (8 8 (:REWRITE BVCHOP-SUBST-CONSTANT)) (8 8 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) ) (SLICE-OUT-OF-ORDER (119 1 (:REWRITE BVCHOP-IDENTITY)) (113 1 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (48 6 (:DEFINITION NATP)) (44 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (42 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (24 2 (:REWRITE COMMUTATIVITY-OF-+)) (19 2 (:REWRITE COMMUTATIVITY-2-OF-+)) (16 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 12 (:REWRITE BOUND-WHEN-USB)) (9 9 (:REWRITE DEFAULT-<-2)) (9 9 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE DEFAULT-+-2)) (9 9 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 1 (:REWRITE LOGTAIL-BECOMES-0)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (5 5 (:TYPE-PRESCRIPTION NATP)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (5 1 (:DEFINITION NFIX)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (4 1 (:DEFINITION POSP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (1 1 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (BVCHOP-OF-SLICE (1246 17 (:REWRITE BVCHOP-IDENTITY)) (1139 13 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (782 104 (:DEFINITION NATP)) (590 56 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (440 13 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (310 13 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (245 9 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (226 162 (:REWRITE DEFAULT-<-1)) (221 81 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (218 218 (:REWRITE BOUND-WHEN-USB)) (202 18 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (162 162 (:REWRITE DEFAULT-<-2)) (137 137 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (115 115 (:TYPE-PRESCRIPTION NATP)) (104 104 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (104 104 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (103 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (92 92 (:REWRITE DEFAULT-+-2)) (92 92 (:REWRITE DEFAULT-+-1)) (81 81 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (80 8 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (68 68 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (68 68 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (65 13 (:DEFINITION NFIX)) (64 8 (:REWRITE LOGTAIL-NON-NEG)) (64 8 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (60 15 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (56 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (52 17 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (50 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (46 46 (:REWRITE FOLD-CONSTS-IN-+)) (44 44 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (44 44 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (44 44 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (44 44 (:REWRITE UBP-LONGER-BETTER)) (43 43 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (43 43 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (34 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (34 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (34 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (32 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 28 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (28 28 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (20 20 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (20 20 (:LINEAR EXPT-BOUND-LINEAR)) (19 19 (:TYPE-PRESCRIPTION POSP)) (17 17 (:REWRITE BVCHOP-SUBST-CONSTANT)) (17 17 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (16 16 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (16 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (16 16 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 4 (:REWRITE LOGTAIL-BECOMES-0)) (16 4 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (16 4 (:REWRITE +-OF---AND-0)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (10 10 (:LINEAR EXPT-BOUND-LINEAR-2)) (8 2 (:DEFINITION POSP)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (LOGTAIL-OF-BVCHOP (1244 23 (:REWRITE MOD-WHEN-MULTIPLE)) (1066 26 (:REWRITE MOD-WHEN-<-OF-0)) (783 44 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE)) (741 23 (:REWRITE MOD-WHEN-<)) (532 44 (:REWRITE INTEGERP-OF-*)) (522 62 (:REWRITE DEFAULT-UNARY-/)) (439 13 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (406 44 (:REWRITE MULTIPLE-WHEN-MOD-0-CHEAP)) (403 202 (:REWRITE DEFAULT-<-2)) (396 125 (:REWRITE DEFAULT-*-2)) (391 125 (:REWRITE DEFAULT-*-1)) (352 202 (:REWRITE DEFAULT-<-1)) (300 22 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (229 3 (:REWRITE <-OF-FLOOR-AND-0)) (223 13 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (212 44 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP-ALT)) (166 166 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (166 166 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (148 23 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (114 42 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (112 23 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (105 13 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (94 24 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (93 9 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (84 29 (:REWRITE DEFAULT-+-2)) (82 82 (:REWRITE BOUND-WHEN-USB)) (77 77 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (59 23 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (59 23 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (47 9 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (39 39 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (38 24 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (38 24 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (36 36 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (34 29 (:REWRITE DEFAULT-+-1)) (32 9 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (31 23 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (30 1 (:LINEAR EXPT-HALF-LINEAR)) (26 26 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (26 1 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (25 25 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (24 24 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (18 18 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (18 18 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (18 18 (:LINEAR <-OF-*-AND-*-LINEAR)) (13 13 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (13 13 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (12 4 (:REWRITE <-OF-1-AND-EXPT-GEN)) (9 9 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (9 9 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) ) (SLICE-OF-BVCHOP-LOW (1450 32 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (476 14 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (285 285 (:REWRITE BOUND-WHEN-USB)) (240 212 (:REWRITE DEFAULT-<-1)) (222 182 (:REWRITE DEFAULT-+-2)) (212 212 (:REWRITE DEFAULT-<-2)) (182 182 (:REWRITE DEFAULT-+-1)) (160 32 (:DEFINITION NFIX)) (158 158 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (156 39 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (141 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (130 130 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (130 130 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (130 130 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (130 130 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (126 14 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (91 41 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (84 42 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (81 81 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (81 81 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (81 81 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (81 81 (:REWRITE UBP-LONGER-BETTER)) (81 37 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (80 40 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (80 28 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (70 14 (:REWRITE LOGTAIL-NON-NEG)) (70 14 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (63 63 (:REWRITE +-COMBINE-CONSTANTS)) (56 28 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (48 48 (:TYPE-PRESCRIPTION POSP)) (48 48 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (48 48 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (48 48 (:REWRITE FOLD-CONSTS-IN-+)) (44 44 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (42 42 (:REWRITE BVCHOP-SUBST-CONSTANT)) (42 12 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (41 41 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (40 8 (:REWRITE +-OF---AND-0)) (37 37 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (36 9 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (34 17 (:REWRITE UNICITY-OF-0)) (32 32 (:DEFINITION FIX)) (30 15 (:REWRITE +-OF-+-OF---SAME)) (30 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (28 28 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (28 28 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (28 28 (:LINEAR EXPT-BOUND-LINEAR)) (28 28 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (24 6 (:DEFINITION POSP)) (23 23 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (17 17 (:REWRITE INVERSE-OF-+)) (14 14 (:REWRITE DEFAULT-UNARY-MINUS)) (14 14 (:LINEAR EXPT-BOUND-LINEAR-2)) (10 10 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (SLICE-OF-BVCHOP-TIGHTEN (352 9 (:REWRITE BVCHOP-IDENTITY)) (220 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (105 9 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (80 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (51 51 (:REWRITE BOUND-WHEN-USB)) (36 36 (:REWRITE DEFAULT-<-2)) (36 36 (:REWRITE DEFAULT-<-1)) (35 35 (:REWRITE DEFAULT-+-2)) (35 35 (:REWRITE DEFAULT-+-1)) (34 14 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (26 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (23 23 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (20 20 (:TYPE-PRESCRIPTION NATP)) (20 4 (:DEFINITION NFIX)) (18 9 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (16 16 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (16 16 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (16 16 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (16 16 (:REWRITE UBP-LONGER-BETTER)) (15 15 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (15 15 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (15 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 14 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (13 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (12 3 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (12 3 (:REWRITE +-OF---AND-0)) (11 11 (:TYPE-PRESCRIPTION POSP)) (9 9 (:REWRITE BVCHOP-SUBST-CONSTANT)) (9 9 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (9 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (9 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 8 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (8 8 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:DEFINITION POSP)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (5 5 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 2 (:REWRITE +-OF-+-OF---SAME)) (2 2 (:REWRITE INVERSE-OF-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) ) (SLICE-OF-BVCHOP-TOO-HIGH (94 4 (:REWRITE BVCHOP-IDENTITY)) (40 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (24 15 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (15 15 (:REWRITE DEFAULT-<-1)) (14 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (10 1 (:REWRITE LOGTAIL-OF-BVCHOP)) (9 9 (:TYPE-PRESCRIPTION NATP)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:REWRITE +-OF---AND-0)) (8 2 (:DEFINITION POSP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (7 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) ) (SLICE-OF-BVCHOP-LOW-GEN (48 7 (:REWRITE SLICE-TOO-HIGH-IS-0)) (30 30 (:REWRITE DEFAULT-<-2)) (30 30 (:REWRITE DEFAULT-<-1)) (28 4 (:REWRITE BVCHOP-IDENTITY)) (27 7 (:REWRITE SLICE-OUT-OF-ORDER)) (24 24 (:REWRITE BOUND-WHEN-USB)) (20 20 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (13 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (12 7 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 10 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 7 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (8 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (7 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-BVCHOP-TYPE)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (UNSIGNED-BYTE-P-OF-SLICE-GEN (221 3 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (202 2 (:REWRITE BVCHOP-IDENTITY)) (89 3 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (75 9 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (48 4 (:REWRITE COMMUTATIVITY-OF-+)) (38 4 (:REWRITE COMMUTATIVITY-2-OF-+)) (37 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (26 26 (:REWRITE BOUND-WHEN-USB)) (23 23 (:REWRITE DEFAULT-+-2)) (23 23 (:REWRITE DEFAULT-+-1)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (15 3 (:DEFINITION NFIX)) (14 2 (:REWRITE LOGTAIL-BECOMES-0)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (13 13 (:REWRITE UBP-LONGER-BETTER)) (12 12 (:TYPE-PRESCRIPTION NATP)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (12 12 (:REWRITE +-COMBINE-CONSTANTS)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 2 (:DEFINITION POSP)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (3 3 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) ) (SLICE-WHEN-LOW-IS-NEGATIVE (829 6 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (219 6 (:REWRITE MOD-WHEN-MULTIPLE)) (187 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (169 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (161 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (156 6 (:REWRITE MOD-WHEN-<)) (133 10 (:REWRITE INTEGERP-OF-*)) (115 40 (:REWRITE DEFAULT-<-2)) (94 10 (:REWRITE DEFAULT-UNARY-/)) (79 40 (:REWRITE DEFAULT-<-1)) (72 5 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (65 65 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (52 10 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (52 10 (:REWRITE DEFAULT-*-2)) (37 12 (:REWRITE DEFAULT-UNARY-MINUS)) (36 6 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (36 6 (:REWRITE MOD-WHEN-<-OF-0)) (32 6 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (28 28 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (28 28 (:LINEAR EXPT-BOUND-LINEAR)) (24 24 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE)) (22 2 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (19 19 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (18 10 (:REWRITE DEFAULT-*-1)) (17 17 (:REWRITE BOUND-WHEN-USB)) (14 14 (:LINEAR EXPT-BOUND-LINEAR-2)) (14 6 (:REWRITE DEFAULT-+-2)) (10 10 (:REWRITE INTEGERP-OF-POWER2-HACK)) (10 6 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (10 6 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (7 7 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (5 5 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) ) (UNSIGNED-BYTE-P-OF-SLICE-HELPER (146 2 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (83 1 (:REWRITE BVCHOP-IDENTITY)) (75 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (54 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (48 4 (:REWRITE COMMUTATIVITY-OF-+)) (38 4 (:REWRITE COMMUTATIVITY-2-OF-+)) (34 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (18 18 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-+-1)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (10 2 (:DEFINITION NFIX)) (9 9 (:REWRITE BOUND-WHEN-USB)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 8 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (7 1 (:REWRITE LOGTAIL-BECOMES-0)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 1 (:DEFINITION POSP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (UNSIGNED-BYTE-P-OF-SLICE (30 30 (:REWRITE BOUND-WHEN-USB)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (20 20 (:REWRITE DEFAULT-+-2)) (20 20 (:REWRITE DEFAULT-+-1)) (18 18 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (14 14 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (14 14 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (9 9 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (9 3 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (7 7 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (BVCHOP-OF-SLICE-BOTH (155 125 (:REWRITE DEFAULT-+-2)) (143 125 (:REWRITE DEFAULT-+-1)) (127 88 (:REWRITE DEFAULT-<-1)) (111 21 (:REWRITE SLICE-TOO-HIGH-IS-0)) (106 88 (:REWRITE DEFAULT-<-2)) (68 38 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (58 58 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (57 57 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (54 54 (:REWRITE BOUND-WHEN-USB)) (54 22 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (51 15 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (49 49 (:REWRITE FOLD-CONSTS-IN-+)) (49 49 (:REWRITE +-COMBINE-CONSTANTS)) (44 44 (:REWRITE DEFAULT-UNARY-MINUS)) (38 38 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (38 38 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (38 38 (:REWRITE UBP-LONGER-BETTER)) (38 38 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (36 24 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (36 21 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (32 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (24 24 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (23 23 (:REWRITE BVCHOP-SUBST-CONSTANT)) (22 22 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (21 21 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (21 21 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (21 21 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (21 21 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (18 3 (:REWRITE DEFAULT-*-2)) (17 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (12 4 (:REWRITE <-OF-+-CANCEL-1+-2)) (11 11 (:TYPE-PRESCRIPTION NATP)) (11 11 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (10 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (10 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (6 2 (:REWRITE INTEGERP-OF-+-WHEN-INTEGERP-1-CHEAP)) (5 5 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-*-1)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:DEFINITION FIX)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) ) (LOGTAIL-OF-BVCHOP-BECOMES-SLICE (261 13 (:REWRITE BVCHOP-IDENTITY)) (173 5 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (58 41 (:REWRITE DEFAULT-<-1)) (57 3 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (55 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (45 45 (:REWRITE BOUND-WHEN-USB)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (41 41 (:REWRITE DEFAULT-<-2)) (41 9 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (38 8 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (37 29 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (29 29 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (29 29 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (29 29 (:REWRITE UBP-LONGER-BETTER)) (26 23 (:REWRITE DEFAULT-+-2)) (24 6 (:DEFINITION POSP)) (23 23 (:REWRITE DEFAULT-+-1)) (23 9 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (21 21 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (20 5 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (20 5 (:REWRITE +-OF---AND-0)) (20 4 (:DEFINITION NFIX)) (19 9 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (17 17 (:TYPE-PRESCRIPTION NATP)) (17 17 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (15 15 (:TYPE-PRESCRIPTION POSP)) (14 9 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 9 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (13 13 (:REWRITE BVCHOP-SUBST-CONSTANT)) (13 13 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (11 11 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (11 11 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (9 9 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (9 5 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (8 4 (:REWRITE +-OF-+-OF---SAME)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (7 7 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) ) (SLICE-ALT-DEF (36 6 (:REWRITE SLICE-TOO-HIGH-IS-0)) (35 5 (:REWRITE BVCHOP-IDENTITY)) (16 6 (:REWRITE SLICE-OUT-OF-ORDER)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (15 9 (:REWRITE DEFAULT-<-1)) (14 8 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (11 6 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 10 (:REWRITE UBP-LONGER-BETTER)) (10 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (9 9 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (6 6 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (5 5 (:REWRITE BVCHOP-SUBST-CONSTANT)) (5 5 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE BOUND-WHEN-USB)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-OF-LOGTAIL (115 2 (:REWRITE BVCHOP-IDENTITY)) (108 1 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (33 33 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (29 29 (:REWRITE DEFAULT-+-2)) (29 29 (:REWRITE DEFAULT-+-1)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (15 3 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (15 3 (:REWRITE LOGTAIL-BECOMES-0)) (14 14 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE +-COMBINE-CONSTANTS)) (12 12 (:REWRITE FOLD-CONSTS-IN-+)) (11 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (10 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 2 (:DEFINITION POSP)) (9 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (7 1 (:DEFINITION NFIX)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (6 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (5 5 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (5 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (5 5 (:REWRITE UBP-LONGER-BETTER)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 3 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 1 (:REWRITE +-OF-+-OF---SAME)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (BVCHOP-OF-LOGTAIL (265 19 (:REWRITE BVCHOP-IDENTITY)) (156 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (142 6 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (97 61 (:REWRITE DEFAULT-<-2)) (96 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (80 8 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (72 61 (:REWRITE DEFAULT-<-1)) (61 61 (:REWRITE BOUND-WHEN-USB)) (43 43 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (41 41 (:TYPE-PRESCRIPTION NATP)) (40 40 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (38 19 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (36 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (30 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (28 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (27 27 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (27 27 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (27 27 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (27 27 (:REWRITE UBP-LONGER-BETTER)) (25 6 (:DEFINITION NFIX)) (23 23 (:TYPE-PRESCRIPTION POSP)) (22 22 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (22 22 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (20 4 (:REWRITE LOGTAIL-NON-NEG)) (20 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (19 19 (:REWRITE BVCHOP-SUBST-CONSTANT)) (19 19 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (18 4 (:DEFINITION POSP)) (16 16 (:REWRITE DEFAULT-+-2)) (16 16 (:REWRITE DEFAULT-+-1)) (16 16 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (13 13 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (13 13 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (13 13 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 12 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (12 12 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (8 4 (:REWRITE UNICITY-OF-0)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) ) (BVCHOP-OF-LOGTAIL-BECOMES-SLICE (196 6 (:REWRITE BVCHOP-IDENTITY)) (84 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (48 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (47 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (41 22 (:REWRITE DEFAULT-<-1)) (41 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (40 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (22 22 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE BOUND-WHEN-USB)) (20 4 (:DEFINITION NFIX)) (19 16 (:REWRITE DEFAULT-+-2)) (17 5 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 16 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE DEFAULT-+-1)) (15 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (15 5 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:REWRITE LOGTAIL-BECOMES-0)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (7 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 5 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (5 5 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 1 (:DEFINITION POSP)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-OF-SLICE (733 73 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (390 11 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (333 61 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (258 225 (:REWRITE DEFAULT-+-2)) (244 244 (:REWRITE BOUND-WHEN-USB)) (225 225 (:REWRITE DEFAULT-+-1)) (222 50 (:DEFINITION POSP)) (208 208 (:REWRITE DEFAULT-<-2)) (208 208 (:REWRITE DEFAULT-<-1)) (187 187 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (187 187 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (187 187 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (187 187 (:REWRITE UBP-LONGER-BETTER)) (148 3 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (110 110 (:REWRITE +-COMBINE-CONSTANTS)) (100 100 (:REWRITE FOLD-CONSTS-IN-+)) (90 90 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (80 80 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (67 67 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (65 65 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (55 11 (:DEFINITION NFIX)) (52 52 (:TYPE-PRESCRIPTION POSP)) (49 39 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (47 47 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (41 39 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (41 39 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (39 39 (:REWRITE BVCHOP-SUBST-CONSTANT)) (33 30 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (32 6 (:REWRITE +-OF---AND-0)) (30 30 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (30 30 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (30 30 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (30 30 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (28 7 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (25 25 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (25 25 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (25 25 (:REWRITE DEFAULT-UNARY-MINUS)) (22 22 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (22 22 (:LINEAR EXPT-BOUND-LINEAR)) (22 22 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (18 18 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (11 11 (:LINEAR EXPT-BOUND-LINEAR-2)) (8 1 (:REWRITE <-OF-+-CANCEL-1+-2+)) (2 2 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-TOO-HIGH-HELPER (18 18 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (6 1 (:REWRITE SLICE-OUT-OF-ORDER)) (4 1 (:REWRITE DEFAULT-<-1)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (SLICE-TOO-HIGH-LEMMA (12 12 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) ) (SLICE-UPPER-BOUND-LINEAR (68 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (33 33 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (31 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (11 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (8 8 (:REWRITE BOUND-WHEN-USB)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE +-COMBINE-CONSTANTS)) (3 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) ) (SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION (30 30 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (30 30 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (8 3 (:REWRITE DEFAULT-+-2)) (7 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (3 3 (:REWRITE DEFAULT-+-1)) (3 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-<-2)) (1 1 (:REWRITE DEFAULT-<-1)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (<-OF-SLICE-AND-CONSTANT (99 99 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (22 8 (:REWRITE DEFAULT-+-2)) (18 7 (:REWRITE DEFAULT-<-1)) (14 2 (:REWRITE SLICE-TOO-HIGH-IS-0)) (11 7 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE BOUND-WHEN-USB)) (6 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-OUT-OF-ORDER)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) ) (LOGTAIL-BECOMES-SLICE (91 4 (:REWRITE LOGTAIL-BECOMES-0)) (74 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (35 35 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (23 18 (:REWRITE DEFAULT-+-2)) (23 18 (:REWRITE DEFAULT-+-1)) (19 19 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (19 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (15 15 (:REWRITE BOUND-WHEN-USB)) (12 3 (:REWRITE <-OF-EXPT-AND-EXPT)) (12 3 (:DEFINITION POSP)) (11 1 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (10 10 (:REWRITE DEFAULT-<-2)) (10 10 (:REWRITE DEFAULT-<-1)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 1 (:REWRITE DEFAULT-*-2)) (4 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:TYPE-PRESCRIPTION NATP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-*-1)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (SLICE-MONOTONE (101 35 (:REWRITE BOUND-WHEN-USB)) (53 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (44 6 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (38 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (36 30 (:REWRITE DEFAULT-+-2)) (30 30 (:REWRITE DEFAULT-+-1)) (30 24 (:REWRITE DEFAULT-<-2)) (24 24 (:REWRITE DEFAULT-<-1)) (14 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (12 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (10 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE +-COMBINE-CONSTANTS)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:DEFINITION POSP)) (5 5 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (SLICE-OF-EXPT (78 8 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (69 4 (:REWRITE BVCHOP-IDENTITY)) (48 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (46 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (37 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (34 34 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (34 34 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (27 27 (:REWRITE BOUND-WHEN-USB)) (25 11 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (20 20 (:REWRITE DEFAULT-<-2)) (20 20 (:REWRITE DEFAULT-<-1)) (20 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (17 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (13 13 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (12 3 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (11 11 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 11 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (9 5 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 2 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 7 (:REWRITE DEFAULT-+-2)) (7 7 (:REWRITE DEFAULT-+-1)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (5 5 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (3 3 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) ) (SLICE-OF-SLICE-GEN-BETTER (110 80 (:REWRITE DEFAULT-+-2)) (85 17 (:REWRITE SLICE-OUT-OF-ORDER)) (80 80 (:REWRITE DEFAULT-+-1)) (51 51 (:REWRITE DEFAULT-<-2)) (51 51 (:REWRITE DEFAULT-<-1)) (37 37 (:REWRITE BOUND-WHEN-USB)) (28 16 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (27 27 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (23 23 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (22 22 (:REWRITE +-COMBINE-CONSTANTS)) (20 20 (:REWRITE FOLD-CONSTS-IN-+)) (18 18 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (18 18 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (17 17 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (17 17 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (17 16 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (16 16 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (15 15 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (15 5 (:REWRITE <-OF-+-CANCEL-1+-1+)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (12 12 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (9 9 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (8 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (2 2 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-WHEN-BVCHOP-KNOWN (395 22 (:REWRITE LOGTAIL-BECOMES-0)) (338 45 (:REWRITE BVCHOP-IDENTITY)) (197 42 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (148 22 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (143 107 (:REWRITE DEFAULT-<-1)) (122 22 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (118 118 (:REWRITE BOUND-WHEN-USB)) (107 107 (:REWRITE DEFAULT-<-2)) (106 22 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (103 87 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (87 87 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (87 87 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (87 87 (:REWRITE UBP-LONGER-BETTER)) (80 20 (:DEFINITION POSP)) (80 10 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (79 37 (:REWRITE DEFAULT-+-2)) (74 74 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (74 42 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (68 43 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (66 42 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (63 63 (:TYPE-PRESCRIPTION POSP)) (52 52 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (48 42 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (47 37 (:REWRITE DEFAULT-+-1)) (46 16 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (45 45 (:REWRITE BVCHOP-SUBST-CONSTANT)) (45 45 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (45 22 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (44 43 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (41 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (35 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (18 18 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (16 16 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (12 12 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (12 12 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (12 12 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 2 (:REWRITE DEFAULT-*-2)) (7 7 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE DEFAULT-*-1)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-SUBST-IN-CONSTANT (139 104 (:REWRITE DEFAULT-+-2)) (104 104 (:REWRITE DEFAULT-+-1)) (77 11 (:REWRITE SLICE-TOO-HIGH-IS-0)) (48 48 (:REWRITE BOUND-WHEN-USB)) (44 4 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (41 41 (:REWRITE DEFAULT-<-2)) (41 41 (:REWRITE DEFAULT-<-1)) (25 25 (:REWRITE FOLD-CONSTS-IN-+)) (25 25 (:REWRITE +-COMBINE-CONSTANTS)) (21 11 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (20 20 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (20 20 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (18 18 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 16 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (16 4 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (13 13 (:REWRITE DEFAULT-UNARY-MINUS)) (13 13 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (13 13 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (12 12 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (12 12 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (12 12 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (12 12 (:LINEAR EXPT-BOUND-LINEAR)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (11 11 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (10 10 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (8 8 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (6 6 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-SUBST-IN-CONSTANT-ALT) (<-OF-SLICE-SAME (262 10 (:REWRITE BVCHOP-IDENTITY)) (196 4 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (92 8 (:REWRITE COMMUTATIVITY-OF-+)) (90 10 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (72 8 (:REWRITE COMMUTATIVITY-2-OF-+)) (60 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (49 7 (:REWRITE LOGTAIL-BECOMES-0)) (48 33 (:REWRITE DEFAULT-+-2)) (33 33 (:REWRITE DEFAULT-+-1)) (30 30 (:REWRITE BOUND-WHEN-USB)) (25 25 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (22 20 (:REWRITE DEFAULT-<-1)) (21 21 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (21 21 (:REWRITE UBP-LONGER-BETTER)) (21 21 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (21 21 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (20 20 (:REWRITE DEFAULT-<-2)) (20 20 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (20 10 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (20 4 (:DEFINITION NFIX)) (18 10 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (18 10 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (13 13 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (13 13 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (10 10 (:TYPE-PRESCRIPTION POSP)) (10 10 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (9 9 (:REWRITE FOLD-CONSTS-IN-+)) (9 9 (:REWRITE +-COMBINE-CONSTANTS)) (8 4 (:REWRITE UNICITY-OF-0)) (7 7 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (7 7 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (6 6 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE INVERSE-OF-+)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 4 (:DEFINITION FIX)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) ) (SLICE-WHEN-INDICES-ARE-NEGATIVE (295 21 (:REWRITE BVCHOP-IDENTITY)) (167 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (107 29 (:REWRITE DEFAULT-<-1)) (56 7 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (29 29 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (26 26 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (26 26 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (22 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (21 21 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (21 21 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (21 21 (:REWRITE UBP-LONGER-BETTER)) (21 21 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (20 11 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (19 19 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (19 19 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (19 19 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (17 17 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (11 11 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (11 11 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (11 11 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (11 11 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (10 10 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (10 10 (:REWRITE BOUND-WHEN-USB)) (3 3 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) ) (SLICE-SAME-TYPE (217 6 (:REWRITE BVCHOP-IDENTITY)) (128 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (63 3 (:REWRITE UNSIGNED-BYTE-P-OF-LOGTAIL-STRONG)) (46 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (45 22 (:REWRITE DEFAULT-<-1)) (44 4 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (40 4 (:LINEAR <=-OF-LOGTAIL-SAME-LINEAR)) (32 4 (:LINEAR LOGTAIL-NON-NEGATIVE-LINEAR)) (26 26 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (26 26 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (24 4 (:DEFINITION NATP)) (22 22 (:REWRITE DEFAULT-<-2)) (16 16 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 16 (:REWRITE BOUND-WHEN-USB)) (15 3 (:DEFINITION NFIX)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (14 14 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (14 2 (:REWRITE LOGTAIL-BECOMES-0)) (12 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (12 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (12 2 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (8 4 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (8 2 (:DEFINITION POSP)) (8 1 (:REWRITE LOGTAIL-NON-NEG)) (6 6 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (6 6 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (6 6 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (6 6 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (5 5 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (5 5 (:REWRITE DEFAULT-+-2)) (5 5 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) ) (SLICE-OF-MOD-OF-EXPT (1031 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (1006 8 (:REWRITE MOD-WHEN-<)) (591 591 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (396 12 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (384 12 (:LINEAR EXPT-HALF-LINEAR)) (380 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (369 69 (:LINEAR EXPT-BOUND-LINEAR-2)) (341 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (336 8 (:REWRITE MOD-WHEN-MULTIPLE)) (215 86 (:REWRITE DEFAULT-<-2)) (189 104 (:REWRITE DEFAULT-+-2)) (176 16 (:REWRITE DEFAULT-UNARY-/)) (175 105 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (168 28 (:REWRITE DEFAULT-*-2)) (164 104 (:REWRITE DEFAULT-+-1)) (157 86 (:REWRITE DEFAULT-<-1)) (153 114 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (124 4 (:REWRITE LOGTAIL-BECOMES-0)) (111 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD-WHEN-<=-OF-EXPT)) (96 16 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (91 91 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE)) (91 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (89 16 (:REWRITE INTEGERP-OF-*)) (67 18 (:REWRITE DEFAULT-UNARY-MINUS)) (50 50 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (50 10 (:REWRITE BVCHOP-OF-MOD-OF-EXPT-2)) (48 8 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (45 16 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (42 42 (:REWRITE BOUND-WHEN-USB)) (40 4 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (37 28 (:REWRITE DEFAULT-*-1)) (34 9 (:REWRITE MOD-WHEN-<-OF-0)) (33 8 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (30 30 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (30 30 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (30 30 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (30 30 (:REWRITE UBP-LONGER-BETTER)) (29 29 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (25 5 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (25 3 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (22 22 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (22 22 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (22 22 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (19 19 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (19 4 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (18 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 18 (:REWRITE BVCHOP-SUBST-CONSTANT)) (17 8 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (16 16 (:REWRITE INTEGERP-OF-POWER2-HACK)) (16 16 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (16 16 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 16 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (16 16 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD2)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-MOD)) (14 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (12 12 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (12 12 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (12 3 (:DEFINITION POSP)) (12 2 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (11 3 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (10 10 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (10 10 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (10 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (9 9 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (8 8 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (8 8 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (4 4 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (EQUAL-OF-LOGTAIL-AND-SLICE (80 1 (:REWRITE BVCHOP-IDENTITY)) (53 53 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (49 5 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (37 37 (:REWRITE BOUND-WHEN-USB)) (31 6 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (27 5 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (26 26 (:REWRITE DEFAULT-<-2)) (26 26 (:REWRITE DEFAULT-<-1)) (20 5 (:DEFINITION POSP)) (19 19 (:REWRITE DEFAULT-+-2)) (19 19 (:REWRITE DEFAULT-+-1)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 9 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (8 2 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (7 7 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (6 6 (:TYPE-PRESCRIPTION POSP)) (6 6 (:TYPE-PRESCRIPTION NATP)) (6 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 2 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (SLICE-OF-+-OF--1-AND-EXPT-SAME (54 1 (:REWRITE BVCHOP-IDENTITY)) (43 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (35 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (31 1 (:REWRITE USB-PLUS-FROM-BOUNDS)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (15 7 (:REWRITE DEFAULT-+-2)) (15 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (13 1 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (12 7 (:REWRITE DEFAULT-+-1)) (11 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (9 9 (:REWRITE BOUND-WHEN-USB)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE DEFAULT-<-2)) (8 8 (:REWRITE DEFAULT-<-1)) (8 1 (:REWRITE UNSIGNED-BYTE-P-OF-1)) (8 1 (:REWRITE COMMUTATIVITY-OF-+)) (7 7 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (7 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (7 1 (:REWRITE DEFAULT-UNARY-/)) (7 1 (:DEFINITION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST-ARG2)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE BVCHOP-CHOP-LEADING-CONSTANT)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (SLICE-LEIBNIZ) (BVCHOP-OF-FLOOR-OF-EXPT-OF-2 (332 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (84 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (79 4 (:REWRITE FLOOR-WHEN-<)) (73 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (52 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (49 3 (:REWRITE BVCHOP-IDENTITY)) (44 1 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (41 1 (:REWRITE <-OF-FLOOR-AND-0)) (36 2 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (33 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (33 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (32 14 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (32 1 (:REWRITE <-OF-/-AND-CONSTANT)) (30 21 (:REWRITE DEFAULT-<-2)) (21 21 (:REWRITE DEFAULT-<-1)) (21 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (18 15 (:REWRITE DEFAULT-+-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (16 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (15 15 (:REWRITE DEFAULT-+-1)) (14 14 (:LINEAR EXPT-BOUND-LINEAR)) (14 2 (:REWRITE DEFAULT-UNARY-/)) (13 13 (:TYPE-PRESCRIPTION FLOOR)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (13 13 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (9 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (9 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 2 (:REWRITE DEFAULT-*-2)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:LINEAR EXPT-BOUND-LINEAR-2)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 1 (:REWRITE <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE)) (5 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (5 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (5 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (4 4 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (4 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (4 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (3 1 (:REWRITE <-OF-1-AND-EXPT-GEN)) (3 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-*-1)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-LINEAR)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-0-AND-EXPT)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (BVCHOP-OF-FLOOR-OF-EXPT-OF-2-CONSTANT-VERSION (133 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (42 3 (:REWRITE BVCHOP-IDENTITY)) (38 2 (:REWRITE SLICE-OUT-OF-ORDER)) (32 20 (:REWRITE DEFAULT-+-2)) (31 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (30 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (30 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (29 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (27 27 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (24 20 (:REWRITE DEFAULT-+-1)) (24 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (24 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (22 22 (:REWRITE DEFAULT-<-2)) (22 22 (:REWRITE DEFAULT-<-1)) (21 3 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (19 1 (:REWRITE <-OF-FLOOR-AND-0)) (17 17 (:REWRITE BOUND-WHEN-USB)) (14 2 (:REWRITE SLICE-TOO-HIGH-IS-0)) (13 13 (:TYPE-PRESCRIPTION FLOOR)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (13 13 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (12 6 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (12 4 (:REWRITE FLOOR-WHEN-<)) (12 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 2 (:REWRITE <-OF-+-CANCEL-1+-1)) (9 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 8 (:REWRITE UBP-LONGER-BETTER)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 2 (:REWRITE +-OF---AND-0)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 1 (:LINEAR <-OF-EXPT-OF-ONE-LESS-OF-INTEGER-LENGTH-LINEAR)) (6 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 2 (:REWRITE COMMUTATIVITY-OF-*)) (6 2 (:REWRITE <-OF-+-CANCEL-2-2)) (5 5 (:REWRITE DEFAULT-*-2)) (5 5 (:REWRITE DEFAULT-*-1)) (5 1 (:REWRITE <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE)) (5 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (4 4 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (4 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (4 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (4 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (4 4 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (3 3 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (3 1 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (2 2 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE DEFAULT-UNARY-/)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (2 2 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-LINEAR)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE EQUAL-OF-EXPT-AND-CONSTANT)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (1 1 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (BITP-OF-SLICE-SAME-TYPE) (SLICE-SAME-WHEN-NOT-0) (SLICE-BOUND-3 (182 182 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (182 182 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (37 17 (:REWRITE DEFAULT-+-2)) (30 15 (:REWRITE DEFAULT-<-2)) (20 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (17 17 (:REWRITE DEFAULT-+-1)) (15 15 (:REWRITE DEFAULT-<-1)) (10 10 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (6 6 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (5 5 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (5 5 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (5 5 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (5 5 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (5 5 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE +-COMBINE-CONSTANTS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (2 2 (:TYPE-PRESCRIPTION NATP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) ) (SLICE-BOUND-3-CONSTANT-VERSION) (SLICE-OF-TIMES-OF-EXPT (572 4 (:REWRITE FLOOR-WHEN-<)) (341 6 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (116 2 (:REWRITE FLOOR-OF-1-WHEN-INTEGERP)) (102 1 (:REWRITE <-OF-*-OF-/-ARG1-ARG3)) (96 24 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (91 2 (:REWRITE INTEGERP-OF-*)) (91 1 (:REWRITE <-OF-*-OF-/-ARG2-ALT)) (64 17 (:REWRITE DEFAULT-*-2)) (48 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (47 17 (:REWRITE DEFAULT-*-1)) (45 1 (:REWRITE <-OF-*-OF-/-ARG2)) (32 23 (:REWRITE DEFAULT-<-2)) (32 23 (:REWRITE DEFAULT-<-1)) (32 4 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (32 1 (:REWRITE <-OF-/-AND-CONSTANT)) (31 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (28 4 (:REWRITE DEFAULT-UNARY-/)) (28 2 (:REWRITE BVCHOP-IDENTITY)) (27 27 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (27 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (24 24 (:LINEAR EXPT-BOUND-LINEAR)) (21 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (21 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (21 4 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (20 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (14 14 (:REWRITE DEFAULT-+-2)) (14 14 (:REWRITE DEFAULT-+-1)) (14 14 (:REWRITE BOUND-WHEN-USB)) (12 12 (:LINEAR EXPT-BOUND-LINEAR-2)) (12 12 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (12 12 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (12 12 (:LINEAR <-OF-*-AND-*-LINEAR)) (12 4 (:REWRITE <-OF-1-AND-EXPT-GEN)) (12 1 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (10 2 (:REWRITE UNICITY-OF-1)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (8 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (8 1 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (8 1 (:REWRITE INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2)) (8 1 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (7 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (7 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (6 6 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (6 2 (:REWRITE <-OF-EXPT-AND-EXPT)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (5 5 (:REWRITE FOLD-CONSTS-IN-+)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:TYPE-PRESCRIPTION FLOOR)) (4 4 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (4 4 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (4 1 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (4 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (3 1 (:REWRITE FLOOR-OF-*-OF-EXPT-AND-EXPT)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (2 2 (:REWRITE <-OF-0-AND-EXPT)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (1 1 (:REWRITE INTEGERP-OF-POWER2-HACK-ANOTHER-FACTOR-ALT)) ) (SLICE-OF-TIMES-OF-EXPT-ALT (46 4 (:REWRITE SLICE-TOO-HIGH-IS-0)) (26 3 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (24 4 (:REWRITE SLICE-OUT-OF-ORDER)) (24 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT-ALT)) (14 14 (:REWRITE DEFAULT-<-2)) (14 14 (:REWRITE DEFAULT-<-1)) (12 12 (:REWRITE DEFAULT-+-2)) (12 12 (:REWRITE DEFAULT-+-1)) (10 10 (:REWRITE BOUND-WHEN-USB)) (10 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (10 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (10 4 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (9 3 (:REWRITE DEFAULT-*-2)) (8 2 (:REWRITE <-OF-+-CANCEL-2-2)) (7 7 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (7 7 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (7 7 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 3 (:REWRITE DEFAULT-*-1)) (6 2 (:REWRITE <-OF-+-CANCEL-1+-1+)) (6 2 (:REWRITE +-OF---AND-0)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (4 4 (:REWRITE UBP-LONGER-BETTER)) (4 4 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (4 4 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (3 3 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-OF-ASH (280 2 (:REWRITE BVCHOP-IDENTITY)) (268 2 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (132 2 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (125 3 (:REWRITE FLOOR-WHEN-<)) (124 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (62 8 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (31 31 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (31 31 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (30 4 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (30 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (29 20 (:REWRITE DEFAULT-<-1)) (28 28 (:REWRITE DEFAULT-+-2)) (28 28 (:REWRITE DEFAULT-+-1)) (28 20 (:REWRITE DEFAULT-<-2)) (23 3 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (20 2 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (19 19 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (18 8 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (17 17 (:REWRITE BOUND-WHEN-USB)) (16 5 (:REWRITE DEFAULT-*-1)) (14 5 (:REWRITE DEFAULT-*-2)) (13 4 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (12 3 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (12 3 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (12 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (10 10 (:REWRITE +-COMBINE-CONSTANTS)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (9 3 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (8 8 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (8 8 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (8 8 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (8 8 (:LINEAR EXPT-BOUND-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 1 (:REWRITE DEFAULT-UNARY-/)) (6 6 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (6 6 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (6 6 (:REWRITE UBP-LONGER-BETTER)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (6 6 (:LINEAR <-OF-*-AND-*-LINEAR)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 2 (:REWRITE EQUAL-OF-EXPT-SAME)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (SLICE-OF-ASH-RIGHT (589 6 (:REWRITE FLOOR-WHEN-<)) (163 1 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (152 1 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (146 146 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (102 3 (:REWRITE FLOOR-OF-1-WHEN-INTEGERP)) (87 2 (:REWRITE BVCHOP-IDENTITY)) (87 1 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (62 7 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (61 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR)) (56 1 (:REWRITE <-OF-*-AND-0)) (55 23 (:REWRITE DEFAULT-<-1)) (52 4 (:REWRITE INTEGERP-OF-*)) (47 1 (:REWRITE UNSIGNED-BYTE-P-OF-*)) (46 46 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (46 46 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (44 7 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (43 6 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (43 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (38 10 (:REWRITE DEFAULT-*-2)) (33 10 (:REWRITE DEFAULT-*-1)) (32 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (32 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (30 5 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (29 23 (:REWRITE DEFAULT-<-2)) (20 15 (:REWRITE DEFAULT-+-2)) (20 4 (:REWRITE INTEGERP-OF-EXPT2)) (18 1 (:REWRITE UNSIGNED-BYTE-P-OF-FLOOR-OF-EXPT)) (17 17 (:REWRITE BOUND-WHEN-USB)) (17 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (15 15 (:REWRITE DEFAULT-+-1)) (15 5 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (13 13 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (11 1 (:REWRITE DEFAULT-UNARY-/)) (10 10 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (10 10 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (10 10 (:LINEAR <-OF-*-AND-*-LINEAR)) (10 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (7 2 (:LINEAR EXPT-BOUND-LINEAR)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (6 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-OF-EXPT)) (5 5 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (5 5 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE FOLD-CONSTS-IN-+)) (4 4 (:REWRITE +-COMBINE-CONSTANTS)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (2 2 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (2 2 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (2 2 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (2 2 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-*-GEN)) (1 1 (:REWRITE <-OF-FLOOR-OF-CONSTANT-AND-CONSTANT-GEN)) (1 1 (:REWRITE <-OF-0-AND-EXPT)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (1 1 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (1 1 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) ) (SLICE-OF-ASH-SAME (190 10 (:REWRITE BVCHOP-IDENTITY)) (156 4 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (144 12 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (130 2 (:REWRITE UNSIGNED-BYTE-P-OF-IF)) (76 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (72 49 (:REWRITE DEFAULT-<-1)) (65 65 (:REWRITE BOUND-WHEN-USB)) (62 2 (:REWRITE FLOOR-WHEN-<)) (61 49 (:REWRITE DEFAULT-<-2)) (50 20 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (46 12 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (38 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (32 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (30 30 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (30 8 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (28 28 (:TYPE-PRESCRIPTION NATP)) (24 8 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (20 20 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (20 10 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (18 18 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (18 18 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 4 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (14 14 (:REWRITE DEFAULT-+-2)) (14 14 (:REWRITE DEFAULT-+-1)) (13 13 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (12 12 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (12 12 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (12 12 (:REWRITE UBP-LONGER-BETTER)) (12 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (12 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (12 2 (:REWRITE SLICE-OUT-OF-ORDER)) (10 10 (:TYPE-PRESCRIPTION POSP)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (10 10 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (10 10 (:LINEAR EXPT-BOUND-LINEAR)) (10 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (10 4 (:REWRITE DEFAULT-*-2)) (10 4 (:REWRITE DEFAULT-*-1)) (8 8 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 8 (:REWRITE DEFAULT-UNARY-MINUS)) (8 8 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (8 8 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 8 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (8 2 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (8 2 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (8 2 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 2 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (5 5 (:LINEAR EXPT-BOUND-LINEAR-2)) (4 4 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (4 4 (:LINEAR <-OF-*-AND-*-LINEAR)) (2 2 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (2 2 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (2 2 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (2 2 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (2 2 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) (2 2 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) ) (SLICES-SAME-WHEN-BVCHOPS-SAME (86 10 (:REWRITE BVCHOP-IDENTITY)) (32 8 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (30 18 (:REWRITE DEFAULT-<-1)) (29 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (22 4 (:REWRITE SLICE-TOO-HIGH-IS-0)) (19 8 (:REWRITE DEFAULT-+-2)) (18 18 (:REWRITE DEFAULT-<-2)) (16 8 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (14 14 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (13 13 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (13 13 (:REWRITE UBP-LONGER-BETTER)) (13 8 (:REWRITE DEFAULT-+-1)) (11 11 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (10 10 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (10 10 (:REWRITE BVCHOP-SUBST-CONSTANT)) (10 10 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (8 8 (:TYPE-PRESCRIPTION POSP)) (8 8 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 8 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 8 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 8 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (8 4 (:REWRITE SLICE-OUT-OF-ORDER)) (7 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (6 6 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (6 6 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (6 6 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (6 6 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (6 6 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (6 1 (:REWRITE DEFAULT-*-2)) (4 4 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE DEFAULT-*-1)) ) (SLICE-OF-+-OF--1-AND-EXPT (414 6 (:REWRITE BVCHOP-IDENTITY)) (207 3 (:REWRITE USB-PLUS-FROM-BOUNDS)) (114 6 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (97 41 (:REWRITE DEFAULT-+-2)) (81 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (50 41 (:REWRITE DEFAULT-+-1)) (49 22 (:LINEAR EXPT-BOUND-LINEAR)) (48 3 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1-AND-EXPT)) (46 46 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (44 26 (:REWRITE DEFAULT-<-1)) (35 26 (:REWRITE DEFAULT-<-2)) (31 22 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (24 6 (:REWRITE DEFAULT-*-2)) (24 6 (:REWRITE DEFAULT-*-1)) (23 23 (:REWRITE BOUND-WHEN-USB)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (18 3 (:REWRITE USB-OF-MASK-GEN)) (12 12 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (12 12 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (11 11 (:LINEAR EXPT-BOUND-LINEAR-2)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 9 (:REWRITE UBP-LONGER-BETTER)) (9 9 (:REWRITE FOLD-CONSTS-IN-+)) (9 9 (:REWRITE +-COMBINE-CONSTANTS)) (6 6 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (6 6 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (5 5 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (3 3 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (3 3 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (3 3 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (3 3 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (2 2 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-OF-EXPT-AND-CONSTANT)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-BOUND (55 1 (:REWRITE SLICE-TOO-HIGH-IS-0)) (49 1 (:DEFINITION UNSIGNED-BYTE-P)) (48 1 (:DEFINITION INTEGER-RANGE-P)) (41 41 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (31 31 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (24 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (8 3 (:REWRITE DEFAULT-+-2)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (5 2 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:LINEAR EXPT-BOUND-LINEAR-2)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE DEFAULT-<-1)) (2 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (1 1 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (1 1 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (1 1 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (1 1 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (1 1 (:REWRITE SLICE-OUT-OF-ORDER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BOUND-WHEN-USB)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) ) (SLICE-OF-+-OF-EXPT-GEN (758 20 (:REWRITE BVCHOP-IDENTITY)) (706 8 (:REWRITE USB-PLUS-FROM-BOUNDS)) (275 1 (:REWRITE LOGTAIL-OF-SUM)) (182 91 (:REWRITE DEFAULT-+-2)) (176 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (156 52 (:LINEAR EXPT-BOUND-LINEAR)) (150 91 (:REWRITE DEFAULT-+-1)) (142 86 (:REWRITE DEFAULT-<-2)) (139 86 (:REWRITE DEFAULT-<-1)) (128 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (121 121 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (96 96 (:REWRITE BOUND-WHEN-USB)) (94 14 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (84 12 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (83 18 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (76 52 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (76 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (72 32 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (56 27 (:LINEAR EXPT-BOUND-LINEAR-2)) (52 13 (:DEFINITION POSP)) (49 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (47 47 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (47 47 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (47 47 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (47 47 (:REWRITE UBP-LONGER-BETTER)) (38 38 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (38 38 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (32 32 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (32 17 (:REWRITE DEFAULT-UNARY-MINUS)) (30 16 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (30 1 (:LINEAR EXPT-HALF-LINEAR)) (28 14 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (28 14 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (28 14 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (27 27 (:TYPE-PRESCRIPTION POSP)) (26 26 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (26 14 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (26 1 (:LINEAR EXPT-OF-ONE-LESS-LINEAR)) (24 6 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (21 21 (:REWRITE FOLD-CONSTS-IN-+)) (21 21 (:REWRITE +-COMBINE-CONSTANTS)) (21 14 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (20 20 (:REWRITE BVCHOP-SUBST-CONSTANT)) (20 20 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (20 2 (:REWRITE INTEGERP-OF-*)) (18 4 (:REWRITE DEFAULT-*-2)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (10 4 (:REWRITE DEFAULT-*-1)) (8 8 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF-CONSTANT-STRONG)) (8 8 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (8 8 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (8 2 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (8 1 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (8 1 (:REWRITE INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2)) (7 7 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (3 3 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (3 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (1 1 (:REWRITE INTEGERP-OF-POWER2-HACK)) (1 1 (:REWRITE EQUAL-OF-LOGTAIL-CONSTANT-VERSION)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST-ARG2)) (1 1 (:REWRITE BVCHOP-SUM-SUBST-CONST)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE BVCHOP-CHOP-LEADING-CONSTANT)) ) (*-OF-EXPT-AND-SLICE-SAME-LINEAR (227 2 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (106 106 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (77 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR)) (52 1 (:REWRITE <-OF-/-AND-CONSTANT)) (48 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (47 12 (:REWRITE DEFAULT-*-2)) (36 11 (:REWRITE DEFAULT-+-2)) (33 12 (:REWRITE DEFAULT-*-1)) (27 6 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (21 3 (:REWRITE DEFAULT-UNARY-/)) (20 11 (:REWRITE DEFAULT-+-1)) (20 8 (:REWRITE DEFAULT-<-2)) (17 8 (:REWRITE DEFAULT-<-1)) (11 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (8 8 (:TYPE-PRESCRIPTION INTEGERP-OF-*-OF-EXPT2-AND-/-OF-EXPT2-TYPE)) (8 8 (:REWRITE BOUND-WHEN-USB)) (7 1 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (6 6 (:LINEAR EXPT-BOUND-LINEAR)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (6 3 (:REWRITE DEFAULT-UNARY-MINUS)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (4 4 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (4 4 (:LINEAR <-OF-*-AND-*-LINEAR)) (4 1 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (3 3 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (3 3 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (3 3 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (3 3 (:REWRITE SLICE-OUT-OF-ORDER)) (3 3 (:LINEAR EXPT-BOUND-LINEAR-2)) (3 1 (:REWRITE EQUAL-OF-1-AND-EXPT)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) (2 2 (:LINEAR <=-OF-/-LINEAR)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (2 2 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (1 1 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (1 1 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (1 1 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (1 1 (:LINEAR SLICE-UPPER-BOUND-LINEAR-CONSTANT-VERSION)) (1 1 (:DEFINITION IFIX)) ) (FLOOR-BOUND-LEMMA100 (230 2 (:REWRITE *-OF-FLOOR-OF-SAME-WHEN-MULTIPLE)) (137 3 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (134 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (133 1 (:LINEAR *-OF-FLOOR-UPPER-BOUND-LINEAR)) (96 2 (:LINEAR MOD-BOUND-LINEAR-ARG2)) (80 4 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (64 64 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONNEGATIVE-AND-NONPOSITIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONNEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (64 64 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (57 43 (:REWRITE DEFAULT-<-2)) (56 2 (:LINEAR MY-FLOOR-LOWER-BOUND-LINEAR)) (52 2 (:LINEAR FLOOR-UPPER-BOUND-LINEAR)) (43 43 (:REWRITE DEFAULT-<-1)) (40 4 (:REWRITE MOD-WHEN-MULTIPLE)) (28 14 (:REWRITE DEFAULT-*-2)) (24 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (20 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (18 6 (:REWRITE FLOOR-WHEN-<)) (16 16 (:TYPE-PRESCRIPTION RATIONALP-OF-MOD)) (16 16 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE-2)) (16 16 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (16 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (15 15 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (14 14 (:REWRITE DEFAULT-*-1)) (12 12 (:REWRITE DEFAULT-UNARY-/)) (12 8 (:REWRITE INTEGERP-OF-*)) (12 4 (:REWRITE MOD-WHEN-<-OF-0)) (12 4 (:REWRITE MOD-WHEN-<)) (10 2 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (10 2 (:LINEAR FLOOR-BOUND-ARG1-LINEAR)) (10 2 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (10 2 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NONNEGATIVE-LINEAR)) (9 9 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 8 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (8 8 (:REWRITE DEFAULT-UNARY-MINUS)) (6 6 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (6 6 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (6 6 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (6 6 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (6 6 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-LINEAR)) (6 6 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (6 6 (:LINEAR <-OF-*-AND-*-LINEAR)) (6 2 (:REWRITE <-OF-/-AND-CONSTANT)) (6 2 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (6 2 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (5 1 (:LINEAR FLOOR-UPPER-BOUND-ALT-LINEAR)) (4 4 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (4 4 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (4 4 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (4 4 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (4 4 (:LINEAR <=-OF-/-LINEAR)) (4 2 (:LINEAR MOD-BOUND-LINEAR-ARG2-STRONG)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (3 3 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (2 2 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR-1)) (2 1 (:REWRITE <-OF-0-AND-FLOOR)) (1 1 (:REWRITE FOLD-CONSTS-IN-+)) (1 1 (:REWRITE +-COMBINE-CONSTANTS)) ) (EQUAL-OF-SLICE-HELPER (4606 6 (:REWRITE *-OF-FLOOR-OF-SAME-WHEN-MULTIPLE)) (2542 24 (:REWRITE MOD-WHEN-INTEGERP-OF-QUOTIENT)) (1342 6 (:LINEAR MOD-BOUND-LINEAR-ARG2-STRONG)) (1131 205 (:REWRITE BOUND-WHEN-USB)) (924 6 (:LINEAR MOD-BOUND-LINEAR-ARG1)) (906 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-2)) (906 6 (:LINEAR MOD-BOUND-LINEAR-ARG2)) (705 177 (:REWRITE DEFAULT-*-2)) (636 24 (:REWRITE MOD-WHEN-MULTIPLE)) (520 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-NEGATIVE-ALT)) (472 52 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (454 24 (:REWRITE MOD-WHEN-<)) (427 61 (:REWRITE DEFAULT-UNARY-/)) (402 42 (:REWRITE INTEGERP-OF-*)) (401 208 (:REWRITE DEFAULT-<-2)) (399 177 (:REWRITE DEFAULT-*-1)) (296 208 (:REWRITE DEFAULT-<-1)) (264 66 (:TYPE-PRESCRIPTION RATIONALP-OF-MOD)) (254 8 (:REWRITE <-OF-/-AND-CONSTANT)) (248 77 (:REWRITE DEFAULT-+-2)) (192 24 (:REWRITE INTEGERP-OF-/-OF-EXPT-2)) (191 191 (:TYPE-PRESCRIPTION <=-OF-FLOOR-AND-0-WHEN-NONPOSITIVE-AND-NONNEGATIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <=-OF-0-AND-FLOOR-WHEN-BOTH-NONPOSITIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-POSITIVE-AND-NEGATIVE-TYPE)) (191 191 (:TYPE-PRESCRIPTION <-OF-FLOOR-AND-0-WHEN-NEGATIVE-AND-POSITIVE-TYPE)) (168 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-RATIONALP-AND-COMPLEX-RATIONALP)) (168 42 (:REWRITE INTEGERP-OF-*-OF-/-WHEN-<-AND-MIXED-1)) (122 122 (:LINEAR EXPT-BOUND-LINEAR)) (116 29 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-OF-QUOTIENT)) (107 27 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) (99 27 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (98 77 (:REWRITE DEFAULT-+-1)) (96 24 (:REWRITE MOD-WHEN-RATIONALP-ARG1-AND-NOT-RATIONALP-ARG2)) (96 24 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG2)) (90 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (83 4 (:LINEAR FLOOR-BOUND-STRICT-LINEAR)) (76 76 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (66 66 (:TYPE-PRESCRIPTION NONNEG-OF-MOD-TYPE-2)) (66 66 (:TYPE-PRESCRIPTION INTEGERP-OF-MOD-TYPE)) (64 8 (:LINEAR FLOOR-UPPER-BOUND-STRONG-LINEAR-CHEAP)) (62 62 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (62 62 (:LINEAR <-OF-*-AND-*-LINEAR)) (61 61 (:LINEAR EXPT-BOUND-LINEAR-2)) (48 48 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (42 42 (:REWRITE INTEGERP-OF-POWER2-HACK)) (32 8 (:LINEAR <=-OF-*-OF-/-WHEN-NEGATIVE-AND-POSITIVE-LINEAR)) (31 31 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (29 29 (:REWRITE FLOOR-WHEN-NEGATIVE-AND-SMALL-CHEAP)) (29 29 (:REWRITE FLOOR-WHEN-I-IS-NOT-AN-ACL2-NUMBERP)) (29 29 (:REWRITE FLOOR-MINUS-NEGATIVE-CONSTANT)) (28 11 (:REWRITE +-COMBINE-CONSTANTS)) (25 25 (:REWRITE FLOOR-WHEN-NOT-RATIONALP-ARG1)) (24 24 (:REWRITE MOD-WHEN-NOT-RATIONALP-ARG1-AND-RATIONALP-ARG2)) (24 24 (:REWRITE MOD-WHEN-NOT-ACL2-NUMBERP-ARG1)) (24 24 (:REWRITE MOD-WHEN-EQUAL-OF-MOD-AND-0-FREE-CHEAP)) (24 24 (:REWRITE MOD-WHEN-<-OF-0)) (24 8 (:REWRITE EQUAL-OF-1-AND-EXPT)) (21 1 (:REWRITE *-OF---ARG2)) (17 17 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (16 16 (:LINEAR <=-OF-/-LINEAR)) (11 5 (:REWRITE DEFAULT-UNARY-MINUS)) (10 10 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 10 (:REWRITE FOLD-CONSTS-IN-+)) (8 8 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (8 8 (:LINEAR <=-OF-*-OF-/-WHEN-BOTH-NEGATIVE-LINEAR)) (8 2 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (7 1 (:REWRITE <-OF-*-OF-/-ARG1-ARG2)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (6 6 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:LINEAR FLOOR-WEAK-MONOTONE-LINEAR=-2)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (2 2 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) ) (EQUAL-OF-SLICE (105 105 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (57 25 (:REWRITE DEFAULT-+-2)) (36 6 (:REWRITE BVCHOP-IDENTITY)) (34 25 (:REWRITE DEFAULT-+-1)) (32 12 (:REWRITE DEFAULT-<-1)) (32 8 (:REWRITE DEFAULT-*-2)) (21 12 (:REWRITE DEFAULT-<-2)) (21 3 (:REWRITE SLICE-TOO-HIGH-IS-0)) (17 17 (:REWRITE BOUND-WHEN-USB)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (11 11 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (11 11 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (11 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (10 10 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (10 8 (:REWRITE DEFAULT-*-1)) (6 6 (:REWRITE FOLD-CONSTS-IN-+)) (6 6 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (6 6 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 6 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 6 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 6 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (6 6 (:REWRITE BVCHOP-SUBST-CONSTANT)) (6 6 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (6 6 (:REWRITE +-COMBINE-CONSTANTS)) (6 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE SLICE-WHEN-LOW-IS-NEGATIVE)) (4 4 (:REWRITE SLICE-WHEN-BVCHOP-KNOWN)) (4 4 (:REWRITE SLICE-TOO-HIGH-LEMMA)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT-ALT)) (4 4 (:REWRITE SLICE-SUBST-IN-CONSTANT)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (3 3 (:REWRITE SLICE-WHEN-VAL-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE SLICE-OUT-OF-ORDER)) (3 3 (:REWRITE DEFAULT-UNARY-MINUS)) (3 3 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (3 3 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-CONSTANT-AND-*-OF-CONSTANT)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (SLICE-OF--1 (31 31 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (27 1 (:REWRITE BVCHOP-IDENTITY)) (25 1 (:REWRITE UNSIGNED-BYTE-P-OF-+-OF--1)) (19 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG2)) (16 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (5 5 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (5 5 (:REWRITE BOUND-WHEN-USB)) (4 4 (:REWRITE DEFAULT-<-2)) (4 4 (:REWRITE DEFAULT-<-1)) (4 4 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (4 4 (:LINEAR EXPT-BOUND-LINEAR)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE FOLD-CONSTS-IN-+)) (2 2 (:REWRITE DEFAULT-UNARY-MINUS)) (2 2 (:REWRITE +-COMBINE-CONSTANTS)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (UNSIGNED-BYTE-P-OF-SLICE-LEMMA (95 1 (:REWRITE BVCHOP-IDENTITY)) (24 2 (:REWRITE NATP-OF-+-WHEN-NATP-AND-NATP)) (18 18 (:REWRITE BOUND-WHEN-USB)) (18 2 (:REWRITE COMMUTATIVITY-2-OF-+)) (14 1 (:REWRITE LOGTAIL-BECOMES-0)) (13 13 (:REWRITE DEFAULT-+-2)) (13 13 (:REWRITE DEFAULT-+-1)) (12 12 (:REWRITE DEFAULT-<-2)) (12 12 (:REWRITE DEFAULT-<-1)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (9 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-2)) (9 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (8 8 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (8 4 (:REWRITE <-OF-+-COMBINE-CONSTANTS-1)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 1 (:REWRITE LOGTAIL-WHEN-NOT-POSP-ARG1)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE <-OF-+-ARG2-WHEN-NEGATIVE-CONSTANT)) (4 4 (:REWRITE <-OF-+-ARG1-WHEN-NEGATIVE-CONSTANT)) (4 1 (:REWRITE <-OF-MINUS-AND-CONSTANT)) (4 1 (:REWRITE <-OF-+-OF---AND-0-ARG2)) (4 1 (:REWRITE <-OF-+-CANCEL-1-1+)) (4 1 (:DEFINITION POSP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE FOLD-CONSTS-IN-+)) (3 3 (:REWRITE +-COMBINE-CONSTANTS)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL-NON-POSITIVE)) (2 2 (:TYPE-PRESCRIPTION LOGTAIL$INLINE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (2 2 (:LINEAR EXPT-BOUND-LINEAR-WEAK)) (2 2 (:LINEAR EXPT-BOUND-LINEAR)) (2 1 (:REWRITE UNICITY-OF-0)) (2 1 (:REWRITE LOGTAIL-WHEN-NOT-INTEGERP-ARG2)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (2 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE INVERSE-OF-+)) (1 1 (:REWRITE DEFAULT-UNARY-MINUS)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (1 1 (:REWRITE <-OF-CONSTANT-AND-MINUS)) (1 1 (:REWRITE <-OF-+-AND-+-COMBINE-CONSTANTS)) (1 1 (:LINEAR EXPT-BOUND-LINEAR-2)) (1 1 (:DEFINITION FIX)) )
b1e5fd42f0dd144af7c89fa3f3ae4ea34e985f07d918fcc7b625ebf4000e183e
hjcapple/reading-sicp
eceval-compiler-example.scm
#lang sicp P425 - [ 5.5.7 编译代码与求值器的互连 ] (#%require "ch5-eceval-compiler.scm") (compile-and-go '(begin (define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n))) (factorial 5) ))
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_5/eceval-compiler-example.scm
scheme
#lang sicp P425 - [ 5.5.7 编译代码与求值器的互连 ] (#%require "ch5-eceval-compiler.scm") (compile-and-go '(begin (define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n))) (factorial 5) ))
2b2c3ca2220e0e4774c08e16be011790b53a9de3b9e04c4d8009fd748c481a54
ivanjovanovic/sicp
e-5.13.scm
Exercise 5.13 . Modify the simulator so that it uses the controller ; sequence to determine what registers the machine has rather than ; requiring a list of registers as an argument to make-machine. Instead ; of pre-allocating the registers in make-machine, you can allocate them one at a time when they are first seen during assembly of the ; instructions. ; ------------------------------------------------------------ ; This is not so difficult task. ; First hint is to update get - register - content and set - register - content ; to create the register if there is no one already.
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/5.2/e-5.13.scm
scheme
sequence to determine what registers the machine has rather than requiring a list of registers as an argument to make-machine. Instead of pre-allocating the registers in make-machine, you can allocate them instructions. ------------------------------------------------------------ This is not so difficult task. to create the register if there is no one already.
Exercise 5.13 . Modify the simulator so that it uses the controller one at a time when they are first seen during assembly of the First hint is to update get - register - content and set - register - content
d6eaf944556aff68169c915e97b103ab36f4d9b860fe3aa82dd1a9c4d9ca5183
emmabastas/elm-embed
Expression.hs
# OPTIONS_GHC -Wall -fno - warn - unused - do - bind # {-# LANGUAGE OverloadedStrings #-} module Parse.Expression ( expression ) where import qualified Data.Name as Name import qualified AST.Source as Src import qualified Parse.Keyword as Keyword import qualified Parse.Number as Number import qualified Parse.Pattern as Pattern import qualified Parse.Shader as Shader import qualified Parse.Space as Space import qualified Parse.Symbol as Symbol import qualified Parse.Type as Type import qualified Parse.String as String import qualified Parse.Variable as Var import Parse.Primitives hiding (State) import qualified Parse.Primitives as P import qualified Reporting.Annotation as A import qualified Reporting.Error.Syntax as E -- TERMS term :: Parser E.Expr Src.Expr term = do start <- getPosition oneOf E.Start [ variable start >>= accessible start , string start , number start , Shader.shader start , list start , record start >>= accessible start , tuple start >>= accessible start , accessor start , character start ] string :: A.Position -> Parser E.Expr Src.Expr string start = do str <- String.string E.Start E.String addEnd start (Src.Str str) character :: A.Position -> Parser E.Expr Src.Expr character start = do chr <- String.character E.Start E.Char addEnd start (Src.Chr chr) number :: A.Position -> Parser E.Expr Src.Expr number start = do nmbr <- Number.number E.Start E.Number addEnd start $ case nmbr of Number.Int int -> Src.Int int Number.Float float -> Src.Float float accessor :: A.Position -> Parser E.Expr Src.Expr accessor start = do word1 0x2E {-.-} E.Dot field <- Var.lower E.Access addEnd start (Src.Accessor field) variable :: A.Position -> Parser E.Expr Src.Expr variable start = do var <- Var.foreignAlpha E.Start addEnd start var accessible :: A.Position -> Src.Expr -> Parser E.Expr Src.Expr accessible start expr = oneOfWithFallback [ do word1 0x2E {-.-} E.Dot pos <- getPosition field <- Var.lower E.Access end <- getPosition accessible start $ A.at start end (Src.Access expr (A.at pos end field)) ] expr -- LISTS list :: A.Position -> Parser E.Expr Src.Expr list start = inContext E.List (word1 0x5B {-[-} E.Start) $ do Space.chompAndCheckIndent E.ListSpace E.ListIndentOpen oneOf E.ListOpen [ do (entry, end) <- specialize E.ListExpr expression Space.checkIndent end E.ListIndentEnd chompListEnd start [entry] , do word1 0x5D {-]-} E.ListOpen addEnd start (Src.List []) ] chompListEnd :: A.Position -> [Src.Expr] -> Parser E.List Src.Expr chompListEnd start entries = oneOf E.ListEnd [ do word1 0x2C {-,-} E.ListEnd Space.chompAndCheckIndent E.ListSpace E.ListIndentExpr (entry, end) <- specialize E.ListExpr expression Space.checkIndent end E.ListIndentEnd chompListEnd start (entry:entries) , do word1 0x5D {-]-} E.ListEnd addEnd start (Src.List (reverse entries)) ] TUPLES tuple :: A.Position -> Parser E.Expr Src.Expr tuple start@(A.Position row col) = inContext E.Tuple (word1 0x28 {-(-} E.Start) $ do before <- getPosition Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExpr1 after <- getPosition if before /= after then do (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] else oneOf E.TupleIndentExpr1 [ do op <- Symbol.operator E.TupleIndentExpr1 E.TupleOperatorReserved if op == "-" then oneOf E.TupleOperatorClose [ do word1 0x29 {-)-} E.TupleOperatorClose addEnd start (Src.Op op) , do (entry, end) <- specialize E.TupleExpr $ do negatedExpr@(A.At (A.Region _ end) _) <- term Space.chomp E.Space let exprStart = A.Position row (col + 2) let expr = A.at exprStart end (Src.Negate negatedExpr) chompExprEnd exprStart (State [] expr [] end) Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] ] else do word1 0x29 {-)-} E.TupleOperatorClose addEnd start (Src.Op op) , do word1 0x29 {-)-} E.TupleIndentExpr1 addEnd start Src.Unit , do (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] ] chompTupleEnd :: A.Position -> Src.Expr -> [Src.Expr] -> Parser E.Tuple Src.Expr chompTupleEnd start firstExpr revExprs = oneOf E.TupleEnd [ do word1 0x2C {-,-} E.TupleEnd Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExprN (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start firstExpr (entry : revExprs) , do word1 0x29 {-)-} E.TupleEnd case reverse revExprs of [] -> return firstExpr secondExpr : otherExprs -> addEnd start (Src.Tuple firstExpr secondExpr otherExprs) ] RECORDS record :: A.Position -> Parser E.Expr Src.Expr record start = inContext E.Record (word1 0x7B {- { -} E.Start) $ do Space.chompAndCheckIndent E.RecordSpace E.RecordIndentOpen oneOf E.RecordOpen [ do word1 0x7D {-}-} E.RecordOpen addEnd start (Src.Record []) , do starter <- addLocation (Var.lower E.RecordField) Space.chompAndCheckIndent E.RecordSpace E.RecordIndentEquals oneOf E.RecordEquals [ do word1 0x7C {-|-} E.RecordEquals Space.chompAndCheckIndent E.RecordSpace E.RecordIndentField firstField <- chompField fields <- chompFields [firstField] addEnd start (Src.Update starter fields) , do word1 0x3D {-=-} E.RecordEquals Space.chompAndCheckIndent E.RecordSpace E.RecordIndentExpr (value, end) <- specialize E.RecordExpr expression Space.checkIndent end E.RecordIndentEnd fields <- chompFields [(starter, value)] addEnd start (Src.Record fields) ] ] type Field = ( A.Located Name.Name, Src.Expr ) chompFields :: [Field] -> Parser E.Record [Field] chompFields fields = oneOf E.RecordEnd [ do word1 0x2C {-,-} E.RecordEnd Space.chompAndCheckIndent E.RecordSpace E.RecordIndentField f <- chompField chompFields (f : fields) , do word1 0x7D {-}-} E.RecordEnd return (reverse fields) ] chompField :: Parser E.Record Field chompField = do key <- addLocation (Var.lower E.RecordField) Space.chompAndCheckIndent E.RecordSpace E.RecordIndentEquals word1 0x3D {-=-} E.RecordEquals Space.chompAndCheckIndent E.RecordSpace E.RecordIndentExpr (value, end) <- specialize E.RecordExpr expression Space.checkIndent end E.RecordIndentEnd return (key, value) -- EXPRESSIONS expression :: Space.Parser E.Expr Src.Expr expression = do start <- getPosition oneOf E.Start [ let_ start , if_ start , case_ start , function start , do expr <- possiblyNegativeTerm start end <- getPosition Space.chomp E.Space chompExprEnd start (State [] expr [] end) ] data State = State { _ops :: ![(Src.Expr, A.Located Name.Name)] , _expr :: !Src.Expr , _args :: ![Src.Expr] , _end :: !A.Position } chompExprEnd :: A.Position -> State -> Space.Parser E.Expr Src.Expr chompExprEnd start (State ops expr args end) = oneOfWithFallback [ -- argument do Space.checkIndent end E.Start arg <- term newEnd <- getPosition Space.chomp E.Space chompExprEnd start (State ops expr (arg:args) newEnd) , -- operator do Space.checkIndent end E.Start op@(A.At (A.Region opStart opEnd) opName) <- addLocation (Symbol.operator E.Start E.OperatorReserved) Space.chompAndCheckIndent E.Space (E.IndentOperatorRight opName) newStart <- getPosition if "-" == opName && end /= opStart && opEnd == newStart then -- negative terms do negatedExpr <- term newEnd <- getPosition Space.chomp E.Space let arg = A.at opStart newEnd (Src.Negate negatedExpr) chompExprEnd start (State ops expr (arg:args) newEnd) else let err = E.OperatorRight opName in oneOf err [ -- term do newExpr <- possiblyNegativeTerm newStart newEnd <- getPosition Space.chomp E.Space let newOps = (toCall expr args, op) : ops chompExprEnd start (State newOps newExpr [] newEnd) , -- final term do (newLast, newEnd) <- oneOf err [ let_ newStart , case_ newStart , if_ newStart , function newStart ] let newOps = (toCall expr args, op) : ops let finalExpr = Src.Binops (reverse newOps) newLast return ( A.at start newEnd finalExpr, newEnd ) ] ] -- done ( case ops of [] -> ( toCall expr args , end ) _ -> ( A.at start end (Src.Binops (reverse ops) (toCall expr args)) , end ) ) possiblyNegativeTerm :: A.Position -> Parser E.Expr Src.Expr possiblyNegativeTerm start = oneOf E.Start [ do word1 0x2D {---} E.Start expr <- term addEnd start (Src.Negate expr) , term ] toCall :: Src.Expr -> [Src.Expr] -> Src.Expr toCall func revArgs = case revArgs of [] -> func lastArg : _ -> A.merge func lastArg (Src.Call func (reverse revArgs)) -- IF EXPRESSION if_ :: A.Position -> Space.Parser E.Expr Src.Expr if_ start = inContext E.If (Keyword.if_ E.Start) $ chompIfEnd start [] chompIfEnd :: A.Position -> [(Src.Expr, Src.Expr)] -> Space.Parser E.If Src.Expr chompIfEnd start branches = do Space.chompAndCheckIndent E.IfSpace E.IfIndentCondition (condition, condEnd) <- specialize E.IfCondition expression Space.checkIndent condEnd E.IfIndentThen Keyword.then_ E.IfThen Space.chompAndCheckIndent E.IfSpace E.IfIndentThenBranch (thenBranch, thenEnd) <- specialize E.IfThenBranch expression Space.checkIndent thenEnd E.IfIndentElse Keyword.else_ E.IfElse Space.chompAndCheckIndent E.IfSpace E.IfIndentElseBranch let newBranches = (condition, thenBranch) : branches oneOf E.IfElseBranchStart [ do Keyword.if_ E.IfElseBranchStart chompIfEnd start newBranches , do (elseBranch, elseEnd) <- specialize E.IfElseBranch expression let ifExpr = Src.If (reverse newBranches) elseBranch return ( A.at start elseEnd ifExpr, elseEnd ) ] LAMBDA EXPRESSION function :: A.Position -> Space.Parser E.Expr Src.Expr function start = inContext E.Func (word1 0x5C {-\-} E.Start) $ do Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArg arg <- specialize E.FuncArg Pattern.term Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArrow revArgs <- chompArgs [arg] Space.chompAndCheckIndent E.FuncSpace E.FuncIndentBody (body, end) <- specialize E.FuncBody expression let funcExpr = Src.Lambda (reverse revArgs) body return (A.at start end funcExpr, end) chompArgs :: [Src.Pattern] -> Parser E.Func [Src.Pattern] chompArgs revArgs = oneOf E.FuncArrow [ do arg <- specialize E.FuncArg Pattern.term Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArrow chompArgs (arg:revArgs) , do word2 0x2D 0x3E {-->-} E.FuncArrow return revArgs ] -- CASE EXPRESSIONS case_ :: A.Position -> Space.Parser E.Expr Src.Expr case_ start = inContext E.Case (Keyword.case_ E.Start) $ do Space.chompAndCheckIndent E.CaseSpace E.CaseIndentExpr (expr, exprEnd) <- specialize E.CaseExpr expression Space.checkIndent exprEnd E.CaseIndentOf Keyword.of_ E.CaseOf Space.chompAndCheckIndent E.CaseSpace E.CaseIndentPattern withIndent $ do (firstBranch, firstEnd) <- chompBranch (branches, end) <- chompCaseEnd [firstBranch] firstEnd return ( A.at start end (Src.Case expr branches) , end ) chompBranch :: Space.Parser E.Case (Src.Pattern, Src.Expr) chompBranch = do (pattern, patternEnd) <- specialize E.CasePattern Pattern.expression Space.checkIndent patternEnd E.CaseIndentArrow word2 0x2D 0x3E {-->-} E.CaseArrow Space.chompAndCheckIndent E.CaseSpace E.CaseIndentBranch (branchExpr, end) <- specialize E.CaseBranch expression return ( (pattern, branchExpr), end ) chompCaseEnd :: [(Src.Pattern, Src.Expr)] -> A.Position -> Space.Parser E.Case [(Src.Pattern, Src.Expr)] chompCaseEnd branches end = oneOfWithFallback [ do Space.checkAligned E.CasePatternAlignment (branch, newEnd) <- chompBranch chompCaseEnd (branch:branches) newEnd ] (reverse branches, end) -- LET EXPRESSION let_ :: A.Position -> Space.Parser E.Expr Src.Expr let_ start = inContext E.Let (Keyword.let_ E.Start) $ do (defs, defsEnd) <- withBacksetIndent 3 $ do Space.chompAndCheckIndent E.LetSpace E.LetIndentDef withIndent $ do (def, end) <- chompLetDef chompLetDefs [def] end Space.checkIndent defsEnd E.LetIndentIn Keyword.in_ E.LetIn Space.chompAndCheckIndent E.LetSpace E.LetIndentBody (body, end) <- specialize E.LetBody expression return ( A.at start end (Src.Let defs body) , end ) chompLetDefs :: [A.Located Src.Def] -> A.Position -> Space.Parser E.Let [A.Located Src.Def] chompLetDefs revDefs end = oneOfWithFallback [ do Space.checkAligned E.LetDefAlignment (def, newEnd) <- chompLetDef chompLetDefs (def:revDefs) newEnd ] (reverse revDefs, end) -- LET DEFINITIONS chompLetDef :: Space.Parser E.Let (A.Located Src.Def) chompLetDef = oneOf E.LetDefName [ definition , destructure ] -- DEFINITION definition :: Space.Parser E.Let (A.Located Src.Def) definition = do aname@(A.At (A.Region start _) name) <- addLocation (Var.lower E.LetDefName) specialize (E.LetDef name) $ do Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals oneOf E.DefEquals [ do word1 0x3A {-:-} E.DefEquals Space.chompAndCheckIndent E.DefSpace E.DefIndentType (tipe, _) <- specialize E.DefType Type.expression Space.checkAligned E.DefAlignment defName <- chompMatchingName name Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals chompDefArgsAndBody start defName (Just tipe) [] , chompDefArgsAndBody start aname Nothing [] ] chompDefArgsAndBody :: A.Position -> A.Located Name.Name -> Maybe Src.Type -> [Src.Pattern] -> Space.Parser E.Def (A.Located Src.Def) chompDefArgsAndBody start name tipe revArgs = oneOf E.DefEquals [ do arg <- specialize E.DefArg Pattern.term Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals chompDefArgsAndBody start name tipe (arg : revArgs) , do word1 0x3D {-=-} E.DefEquals Space.chompAndCheckIndent E.DefSpace E.DefIndentBody (body, end) <- specialize E.DefBody expression return ( A.at start end (Src.Define name (reverse revArgs) body tipe) , end ) ] chompMatchingName :: Name.Name -> Parser E.Def (A.Located Name.Name) chompMatchingName expectedName = let (P.Parser parserL) = Var.lower E.DefNameRepeat in P.Parser $ \state@(P.State _ _ _ _ sr sc _) cok eok cerr eerr -> let cokL name newState@(P.State _ _ _ _ er ec _) = if expectedName == name then cok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else cerr sr sc (E.DefNameMatch name) eokL name newState@(P.State _ _ _ _ er ec _) = if expectedName == name then eok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else eerr sr sc (E.DefNameMatch name) in parserL state cokL eokL cerr eerr -- DESTRUCTURE destructure :: Space.Parser E.Let (A.Located Src.Def) destructure = specialize E.LetDestruct $ do start <- getPosition pattern <- specialize E.DestructPattern Pattern.term Space.chompAndCheckIndent E.DestructSpace E.DestructIndentEquals word1 0x3D {-=-} E.DestructEquals Space.chompAndCheckIndent E.DestructSpace E.DestructIndentBody (expr, end) <- specialize E.DestructBody expression return ( A.at start end (Src.Destruct pattern expr), end )
null
https://raw.githubusercontent.com/emmabastas/elm-embed/c2c4f9dcc5c4f47480f728247ff7b4d0700d7476/compiler/src/Parse/Expression.hs
haskell
# LANGUAGE OverloadedStrings # TERMS . . LISTS [ ] , ] ( ) ) ) , ) { } | = , } = EXPRESSIONS argument operator negative terms term final term done - IF EXPRESSION \ -> CASE EXPRESSIONS -> LET EXPRESSION LET DEFINITIONS DEFINITION : = DESTRUCTURE =
# OPTIONS_GHC -Wall -fno - warn - unused - do - bind # module Parse.Expression ( expression ) where import qualified Data.Name as Name import qualified AST.Source as Src import qualified Parse.Keyword as Keyword import qualified Parse.Number as Number import qualified Parse.Pattern as Pattern import qualified Parse.Shader as Shader import qualified Parse.Space as Space import qualified Parse.Symbol as Symbol import qualified Parse.Type as Type import qualified Parse.String as String import qualified Parse.Variable as Var import Parse.Primitives hiding (State) import qualified Parse.Primitives as P import qualified Reporting.Annotation as A import qualified Reporting.Error.Syntax as E term :: Parser E.Expr Src.Expr term = do start <- getPosition oneOf E.Start [ variable start >>= accessible start , string start , number start , Shader.shader start , list start , record start >>= accessible start , tuple start >>= accessible start , accessor start , character start ] string :: A.Position -> Parser E.Expr Src.Expr string start = do str <- String.string E.Start E.String addEnd start (Src.Str str) character :: A.Position -> Parser E.Expr Src.Expr character start = do chr <- String.character E.Start E.Char addEnd start (Src.Chr chr) number :: A.Position -> Parser E.Expr Src.Expr number start = do nmbr <- Number.number E.Start E.Number addEnd start $ case nmbr of Number.Int int -> Src.Int int Number.Float float -> Src.Float float accessor :: A.Position -> Parser E.Expr Src.Expr accessor start = field <- Var.lower E.Access addEnd start (Src.Accessor field) variable :: A.Position -> Parser E.Expr Src.Expr variable start = do var <- Var.foreignAlpha E.Start addEnd start var accessible :: A.Position -> Src.Expr -> Parser E.Expr Src.Expr accessible start expr = oneOfWithFallback pos <- getPosition field <- Var.lower E.Access end <- getPosition accessible start $ A.at start end (Src.Access expr (A.at pos end field)) ] expr list :: A.Position -> Parser E.Expr Src.Expr list start = do Space.chompAndCheckIndent E.ListSpace E.ListIndentOpen oneOf E.ListOpen [ do (entry, end) <- specialize E.ListExpr expression Space.checkIndent end E.ListIndentEnd chompListEnd start [entry] addEnd start (Src.List []) ] chompListEnd :: A.Position -> [Src.Expr] -> Parser E.List Src.Expr chompListEnd start entries = oneOf E.ListEnd Space.chompAndCheckIndent E.ListSpace E.ListIndentExpr (entry, end) <- specialize E.ListExpr expression Space.checkIndent end E.ListIndentEnd chompListEnd start (entry:entries) addEnd start (Src.List (reverse entries)) ] TUPLES tuple :: A.Position -> Parser E.Expr Src.Expr tuple start@(A.Position row col) = do before <- getPosition Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExpr1 after <- getPosition if before /= after then do (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] else oneOf E.TupleIndentExpr1 [ do op <- Symbol.operator E.TupleIndentExpr1 E.TupleOperatorReserved if op == "-" then oneOf E.TupleOperatorClose [ addEnd start (Src.Op op) , do (entry, end) <- specialize E.TupleExpr $ do negatedExpr@(A.At (A.Region _ end) _) <- term Space.chomp E.Space let exprStart = A.Position row (col + 2) let expr = A.at exprStart end (Src.Negate negatedExpr) chompExprEnd exprStart (State [] expr [] end) Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] ] else addEnd start (Src.Op op) , addEnd start Src.Unit , do (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start entry [] ] chompTupleEnd :: A.Position -> Src.Expr -> [Src.Expr] -> Parser E.Tuple Src.Expr chompTupleEnd start firstExpr revExprs = oneOf E.TupleEnd Space.chompAndCheckIndent E.TupleSpace E.TupleIndentExprN (entry, end) <- specialize E.TupleExpr expression Space.checkIndent end E.TupleIndentEnd chompTupleEnd start firstExpr (entry : revExprs) case reverse revExprs of [] -> return firstExpr secondExpr : otherExprs -> addEnd start (Src.Tuple firstExpr secondExpr otherExprs) ] RECORDS record :: A.Position -> Parser E.Expr Src.Expr record start = do Space.chompAndCheckIndent E.RecordSpace E.RecordIndentOpen oneOf E.RecordOpen addEnd start (Src.Record []) , do starter <- addLocation (Var.lower E.RecordField) Space.chompAndCheckIndent E.RecordSpace E.RecordIndentEquals oneOf E.RecordEquals Space.chompAndCheckIndent E.RecordSpace E.RecordIndentField firstField <- chompField fields <- chompFields [firstField] addEnd start (Src.Update starter fields) Space.chompAndCheckIndent E.RecordSpace E.RecordIndentExpr (value, end) <- specialize E.RecordExpr expression Space.checkIndent end E.RecordIndentEnd fields <- chompFields [(starter, value)] addEnd start (Src.Record fields) ] ] type Field = ( A.Located Name.Name, Src.Expr ) chompFields :: [Field] -> Parser E.Record [Field] chompFields fields = oneOf E.RecordEnd Space.chompAndCheckIndent E.RecordSpace E.RecordIndentField f <- chompField chompFields (f : fields) return (reverse fields) ] chompField :: Parser E.Record Field chompField = do key <- addLocation (Var.lower E.RecordField) Space.chompAndCheckIndent E.RecordSpace E.RecordIndentEquals Space.chompAndCheckIndent E.RecordSpace E.RecordIndentExpr (value, end) <- specialize E.RecordExpr expression Space.checkIndent end E.RecordIndentEnd return (key, value) expression :: Space.Parser E.Expr Src.Expr expression = do start <- getPosition oneOf E.Start [ let_ start , if_ start , case_ start , function start , do expr <- possiblyNegativeTerm start end <- getPosition Space.chomp E.Space chompExprEnd start (State [] expr [] end) ] data State = State { _ops :: ![(Src.Expr, A.Located Name.Name)] , _expr :: !Src.Expr , _args :: ![Src.Expr] , _end :: !A.Position } chompExprEnd :: A.Position -> State -> Space.Parser E.Expr Src.Expr chompExprEnd start (State ops expr args end) = oneOfWithFallback do Space.checkIndent end E.Start arg <- term newEnd <- getPosition Space.chomp E.Space chompExprEnd start (State ops expr (arg:args) newEnd) do Space.checkIndent end E.Start op@(A.At (A.Region opStart opEnd) opName) <- addLocation (Symbol.operator E.Start E.OperatorReserved) Space.chompAndCheckIndent E.Space (E.IndentOperatorRight opName) newStart <- getPosition if "-" == opName && end /= opStart && opEnd == newStart then do negatedExpr <- term newEnd <- getPosition Space.chomp E.Space let arg = A.at opStart newEnd (Src.Negate negatedExpr) chompExprEnd start (State ops expr (arg:args) newEnd) else let err = E.OperatorRight opName in oneOf err do newExpr <- possiblyNegativeTerm newStart newEnd <- getPosition Space.chomp E.Space let newOps = (toCall expr args, op) : ops chompExprEnd start (State newOps newExpr [] newEnd) do (newLast, newEnd) <- oneOf err [ let_ newStart , case_ newStart , if_ newStart , function newStart ] let newOps = (toCall expr args, op) : ops let finalExpr = Src.Binops (reverse newOps) newLast return ( A.at start newEnd finalExpr, newEnd ) ] ] ( case ops of [] -> ( toCall expr args , end ) _ -> ( A.at start end (Src.Binops (reverse ops) (toCall expr args)) , end ) ) possiblyNegativeTerm :: A.Position -> Parser E.Expr Src.Expr possiblyNegativeTerm start = oneOf E.Start expr <- term addEnd start (Src.Negate expr) , term ] toCall :: Src.Expr -> [Src.Expr] -> Src.Expr toCall func revArgs = case revArgs of [] -> func lastArg : _ -> A.merge func lastArg (Src.Call func (reverse revArgs)) if_ :: A.Position -> Space.Parser E.Expr Src.Expr if_ start = inContext E.If (Keyword.if_ E.Start) $ chompIfEnd start [] chompIfEnd :: A.Position -> [(Src.Expr, Src.Expr)] -> Space.Parser E.If Src.Expr chompIfEnd start branches = do Space.chompAndCheckIndent E.IfSpace E.IfIndentCondition (condition, condEnd) <- specialize E.IfCondition expression Space.checkIndent condEnd E.IfIndentThen Keyword.then_ E.IfThen Space.chompAndCheckIndent E.IfSpace E.IfIndentThenBranch (thenBranch, thenEnd) <- specialize E.IfThenBranch expression Space.checkIndent thenEnd E.IfIndentElse Keyword.else_ E.IfElse Space.chompAndCheckIndent E.IfSpace E.IfIndentElseBranch let newBranches = (condition, thenBranch) : branches oneOf E.IfElseBranchStart [ do Keyword.if_ E.IfElseBranchStart chompIfEnd start newBranches , do (elseBranch, elseEnd) <- specialize E.IfElseBranch expression let ifExpr = Src.If (reverse newBranches) elseBranch return ( A.at start elseEnd ifExpr, elseEnd ) ] LAMBDA EXPRESSION function :: A.Position -> Space.Parser E.Expr Src.Expr function start = do Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArg arg <- specialize E.FuncArg Pattern.term Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArrow revArgs <- chompArgs [arg] Space.chompAndCheckIndent E.FuncSpace E.FuncIndentBody (body, end) <- specialize E.FuncBody expression let funcExpr = Src.Lambda (reverse revArgs) body return (A.at start end funcExpr, end) chompArgs :: [Src.Pattern] -> Parser E.Func [Src.Pattern] chompArgs revArgs = oneOf E.FuncArrow [ do arg <- specialize E.FuncArg Pattern.term Space.chompAndCheckIndent E.FuncSpace E.FuncIndentArrow chompArgs (arg:revArgs) return revArgs ] case_ :: A.Position -> Space.Parser E.Expr Src.Expr case_ start = inContext E.Case (Keyword.case_ E.Start) $ do Space.chompAndCheckIndent E.CaseSpace E.CaseIndentExpr (expr, exprEnd) <- specialize E.CaseExpr expression Space.checkIndent exprEnd E.CaseIndentOf Keyword.of_ E.CaseOf Space.chompAndCheckIndent E.CaseSpace E.CaseIndentPattern withIndent $ do (firstBranch, firstEnd) <- chompBranch (branches, end) <- chompCaseEnd [firstBranch] firstEnd return ( A.at start end (Src.Case expr branches) , end ) chompBranch :: Space.Parser E.Case (Src.Pattern, Src.Expr) chompBranch = do (pattern, patternEnd) <- specialize E.CasePattern Pattern.expression Space.checkIndent patternEnd E.CaseIndentArrow Space.chompAndCheckIndent E.CaseSpace E.CaseIndentBranch (branchExpr, end) <- specialize E.CaseBranch expression return ( (pattern, branchExpr), end ) chompCaseEnd :: [(Src.Pattern, Src.Expr)] -> A.Position -> Space.Parser E.Case [(Src.Pattern, Src.Expr)] chompCaseEnd branches end = oneOfWithFallback [ do Space.checkAligned E.CasePatternAlignment (branch, newEnd) <- chompBranch chompCaseEnd (branch:branches) newEnd ] (reverse branches, end) let_ :: A.Position -> Space.Parser E.Expr Src.Expr let_ start = inContext E.Let (Keyword.let_ E.Start) $ do (defs, defsEnd) <- withBacksetIndent 3 $ do Space.chompAndCheckIndent E.LetSpace E.LetIndentDef withIndent $ do (def, end) <- chompLetDef chompLetDefs [def] end Space.checkIndent defsEnd E.LetIndentIn Keyword.in_ E.LetIn Space.chompAndCheckIndent E.LetSpace E.LetIndentBody (body, end) <- specialize E.LetBody expression return ( A.at start end (Src.Let defs body) , end ) chompLetDefs :: [A.Located Src.Def] -> A.Position -> Space.Parser E.Let [A.Located Src.Def] chompLetDefs revDefs end = oneOfWithFallback [ do Space.checkAligned E.LetDefAlignment (def, newEnd) <- chompLetDef chompLetDefs (def:revDefs) newEnd ] (reverse revDefs, end) chompLetDef :: Space.Parser E.Let (A.Located Src.Def) chompLetDef = oneOf E.LetDefName [ definition , destructure ] definition :: Space.Parser E.Let (A.Located Src.Def) definition = do aname@(A.At (A.Region start _) name) <- addLocation (Var.lower E.LetDefName) specialize (E.LetDef name) $ do Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals oneOf E.DefEquals [ Space.chompAndCheckIndent E.DefSpace E.DefIndentType (tipe, _) <- specialize E.DefType Type.expression Space.checkAligned E.DefAlignment defName <- chompMatchingName name Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals chompDefArgsAndBody start defName (Just tipe) [] , chompDefArgsAndBody start aname Nothing [] ] chompDefArgsAndBody :: A.Position -> A.Located Name.Name -> Maybe Src.Type -> [Src.Pattern] -> Space.Parser E.Def (A.Located Src.Def) chompDefArgsAndBody start name tipe revArgs = oneOf E.DefEquals [ do arg <- specialize E.DefArg Pattern.term Space.chompAndCheckIndent E.DefSpace E.DefIndentEquals chompDefArgsAndBody start name tipe (arg : revArgs) Space.chompAndCheckIndent E.DefSpace E.DefIndentBody (body, end) <- specialize E.DefBody expression return ( A.at start end (Src.Define name (reverse revArgs) body tipe) , end ) ] chompMatchingName :: Name.Name -> Parser E.Def (A.Located Name.Name) chompMatchingName expectedName = let (P.Parser parserL) = Var.lower E.DefNameRepeat in P.Parser $ \state@(P.State _ _ _ _ sr sc _) cok eok cerr eerr -> let cokL name newState@(P.State _ _ _ _ er ec _) = if expectedName == name then cok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else cerr sr sc (E.DefNameMatch name) eokL name newState@(P.State _ _ _ _ er ec _) = if expectedName == name then eok (A.At (A.Region (A.Position sr sc) (A.Position er ec)) name) newState else eerr sr sc (E.DefNameMatch name) in parserL state cokL eokL cerr eerr destructure :: Space.Parser E.Let (A.Located Src.Def) destructure = specialize E.LetDestruct $ do start <- getPosition pattern <- specialize E.DestructPattern Pattern.term Space.chompAndCheckIndent E.DestructSpace E.DestructIndentEquals Space.chompAndCheckIndent E.DestructSpace E.DestructIndentBody (expr, end) <- specialize E.DestructBody expression return ( A.at start end (Src.Destruct pattern expr), end )
ae180d7932d345c2e97e407ea8cce9ee9c5886eb9fa0f8cec852b062ca95f96b
vikram/lisplibraries
test.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : TBNL ; Base : 10 -*- $ Header : /usr / local / cvsrep / tbnl / test / test.lisp , v 1.35 2006/09/04 22:54:36 edi Exp $ Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. To test TBNL with Apache add something like this to your ;;; httpd.conf ;;; LispServer 127.0.0.1 3000 " tbnl " ;;; ;;; <Location /tbnl> SetHandler lisp - handler ;;; </Location> ;;; and afterwards restart Apache and evaluate ;;; ;;; (asdf:oos 'asdf:load-op :tbnl-test) ;;; (tbnl:start-tbnl) ;;; ;;; then point your browser at <>. See the ;;; docs for other testing options. (in-package #:tbnl-test) (defmacro with-html (&body body) `(with-html-output-to-string (*standard-output* nil :prologue t) ,@body)) (defun tbnl-link () (with-html-output (*standard-output*) (:a :href "/" "TBNL"))) (defun menu-link () (with-html-output (*standard-output*) (:p (:hr (:a :href "/tbnl/test" "Back to menu"))))) (defmacro info-table (&rest forms) (let ((=value= (gensym))) `(with-html-output (*standard-output*) (:p (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td :colspan 2 "Some Information " (tbnl-link) " provides about this request \(actual values may depend on front-end):")) ,@(loop for form in forms collect `(:tr (:td :valign "top" (:pre :style "padding: 0px" (let ((*package* (find-package :cl))) (pprint ',form)))) (:td :valign "top" (:pre :style "padding: 0px" (let ((*package* (find-package :cl))) (loop for ,=value= in (multiple-value-list ,form) for first = t then nil unless first do (princ ", ") do (pprint ,=value=))))))))) (menu-link)))) (defun authorization-page () (multiple-value-bind (user password) (authorization) (cond ((and (equal user "nanook") (equal password "igloo")) (with-html (:html (:head (:title "TBNL page with Basic Authentication")) (:body (:h2 (tbnl-link) " page with Basic Authentication") (info-table (header-in "Authorization") (authorization)))))) (t (require-authorization))))) (defparameter *test-image* (load-time-value (with-open-file (in (make-pathname :name "fz" :type "jpg" :version nil :defaults (load-time-value *load-pathname*)) #+:tbnl-bivalent-streams :element-type #+:tbnl-bivalent-streams '(unsigned-byte 8)) (let ((image-data (make-array (file-length in) :element-type #-:tbnl-bivalent-streams 'character #+:tbnl-bivalent-streams '(unsigned-byte 8)))) (read-sequence image-data in) image-data)))) (defun image-ram-page () (setf (content-type) "image/jpeg") *test-image*) (let ((count 0)) (defun info () (with-html (:html (:head (:title "TBNL Information")) (:body (:h2 (tbnl-link) " Information Page") (:p "This page has been called " (:b (fmt "~[~;once~;twice~:;~:*~R times~]" (incf count))) " since its handler was compiled.") (info-table (host) (server-addr) (server-port :as-number t) (request-method :as-keyword t) (script-name) (query-string) (get-parameters) (cookies-in) (remote-addr) (real-remote-addr) (remote-port :as-number t) (user-agent) (referer) (request-uri) (server-protocol :as-keyword t) (mod-lisp-id) (ssl-session-id))))))) (defun oops () (with-html (dotimes (i 3) (log-message* "Oops (default) # ~a" i)) (log-message :emerg "Oops emergency") (log-message :alert "Oops alert") (log-message :crit "Oops critical") (log-message :error "Oops error") (log-message :warning "Oops warning") (log-message :notice "Oops notice") (log-message :info "Oops info") (log-message :debug "Oops debug") (error "An error was triggered on purpose. Check your ~ Apache error log. Up to 12 messages where logged depending on ~ the Apache log level set in httpd.conf.") (:html (:body "You'll never see this sentence...")))) (defun redir () (redirect "/tbnl/test/info.html?redirected=1")) (defun forbidden () (setf (return-code *reply*) +http-forbidden+) nil) (defun cookie-test () (set-cookie "pumpkin" :value "barking") (no-cache) (with-html (:html (:head (:title "TBNL Cookie test")) (:body (:h2 (tbnl-link) " Cookie test") (:p "You might have to reload this page to see the cookie value.") (info-table (cookie-in "pumpkin") (mapcar #'car (cookies-in))))))) (defun session-test () (let ((new-foo-value (post-parameter "new-foo-value"))) (when new-foo-value (setf (session-value 'foo) new-foo-value))) (let ((new-bar-value (post-parameter "new-bar-value"))) (when new-bar-value (setf (session-value 'bar) new-bar-value))) (no-cache) (with-html (:html (:head (:title "TBNL Session test")) (:body (:h2 (tbnl-link) " Session test") (:p "Use the forms below to set new values for " (:code "FOO") " or " (:code "BAR") ". You can later return to this page to check if they're still set. Also, try to use another browser at the same time or try with cookies disabled.") (:p (:form :method :post "New value for " (:code "FOO") ": " (:input :type :text :name "new-foo-value" :value (or (session-value 'foo) "")))) (:p (:form :method :post "New value for " (:code "BAR") ": " (:input :type :text :name "new-bar-value" :value (or (session-value 'bar) "")))) (info-table *session-cookie-name* (cookie-in *session-cookie-name*) (mapcar #'car (cookies-in)) (session-value 'foo) (session-value 'bar)))))) (defun parameter-test (&key (method :get) (charset :iso-8859-1)) (no-cache) (recompute-request-parameters :external-format (case charset (:iso-8859-1 +latin-1+) (:utf-8 +utf-8+))) (setf (content-type) (format nil "text/html; charset=~A" charset)) (with-html (:html (:head (:title (fmt "TBNL ~A parameter Test" method))) (:body (:h2 (tbnl-link) (fmt " ~A parameter Test with charset ~A" method charset)) (:p "Enter some non-ASCII characters in the input field below and see what's happening. Check URL-DECODE and OCTETS-TO-STRING in " (:code "util.lisp") " to see if this test makes sense for your Lisp.") (:p (:form :method method "Enter a value: " (:input :type :text :name "foo"))) (case method (:get (info-table (query-string) (map 'list #'char-code (get-parameter "foo")) (escape-string-all (get-parameter "foo")))) (:post (info-table (raw-post-data) (map 'list #'char-code (post-parameter "foo")) (escape-string-all (post-parameter "foo"))))))))) (defun parameter-test-latin1-get () (parameter-test :method :get :charset :iso-8859-1)) (defun parameter-test-latin1-post () (parameter-test :method :post :charset :iso-8859-1)) (defun parameter-test-utf8-get () (parameter-test :method :get :charset :utf-8)) (defun parameter-test-utf8-post () (parameter-test :method :post :charset :utf-8)) ;; this should not be the same directory as *TMP-DIRECTORY* and it ;; should be initially empty (or non-existent) (defvar *tmp-test-directory* #+(or :win32 :mswindows) #p"c:\\tbnl-temp\\test\\" #-(or :win32 :mswindows) #p"/tmp/tbnl/test/") (defvar *tmp-test-files* nil) (let ((counter 0)) (defun handle-file (post-parameter) (when (and post-parameter (listp post-parameter)) (destructuring-bind (path file-name content-type) post-parameter (let ((new-path (make-pathname :name (format nil "tbnl-test-~A" (incf counter)) :type nil :defaults *tmp-test-directory*))) strip directory info sent by Windows browsers (when (search "Windows" (user-agent) :test #'char-equal) (setq file-name (cl-ppcre:regex-replace ".*\\\\" file-name ""))) (rename-file path (ensure-directories-exist new-path)) (push (list new-path file-name content-type) *tmp-test-files*)))))) (defun clean-tmp-dir () (loop for (path . nil) in *tmp-test-files* when (probe-file path) do (ignore-errors (delete-file path))) (setq *tmp-test-files* nil)) (defun upload-test () (let (post-parameter-p) (when (post-parameter "file1") (handle-file (post-parameter "file1")) (setq post-parameter-p t)) (when (post-parameter "file2") (handle-file (post-parameter "file2")) (setq post-parameter-p t)) (when (post-parameter "clean") (clean-tmp-dir) (setq post-parameter-p t)) (when post-parameter-p ;; redirect so user can safely use 'Back' button (redirect (script-name)))) (no-cache) (with-html (:html (:head (:title "TBNL file upload test")) (:body (:h2 (tbnl-link) " File upload test") (:form :method :post :enctype "multipart/form-data" (:p "First file: " (:input :type :file :name "file1")) (:p "Second file: " (:input :type :file :name "file2")) (:p (:input :type :submit))) (when *tmp-test-files* (htm (:p (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td :colspan 3 (:b "Uploaded files"))) (loop for (path file-name nil) in *tmp-test-files* for counter from 1 do (htm (:tr (:td :align "right" (str counter)) (:td (:a :href (format nil "files/~A?path=~A" (url-encode file-name) (url-encode (namestring path))) (esc file-name))) (:td :align "right" (str (ignore-errors (with-open-file (in path) (file-length in)))) "&nbsp;Bytes")))))) (:form :method :post (:p (:input :type :submit :name "clean" :value "Delete uploaded files"))))) (menu-link))))) (defun send-file () (let* ((path (get-parameter "path")) (file-info (and path (find (pathname path) *tmp-test-files* :key #'first :test #'equal)))) (unless file-info (setf (return-code *reply*) +http-not-found+) (return-from send-file)) (handle-static-file path (third file-info)))) (defparameter *headline* (load-time-value (format nil "TBNL Test Menu (see file <code>~A</code>)" (merge-pathnames (make-pathname :type "lisp") *load-truename*)))) #+:lispworks (defun read-utf-8-file (pathspec) (coerce (external-format:encode-lisp-string (with-output-to-string (out nil :element-type 'lw:simple-char) (with-open-file (in pathspec :element-type 'lw:simple-char :external-format :utf-8) (loop for line = (read-line in nil nil) while line do (write-line line out)))) :utf-8) '(simple-array (unsigned-byte 8) (*)))) #+:lispworks (defun utf-8 () (setf (content-type) "text/html; charset=utf-8") ;; demo file stolen from <-8-test/> (read-utf-8-file (load-time-value (merge-pathnames "UTF-8-demo.html" *load-truename*)))) #+:tbnl-bivalent-streams (defun stream-direct () (setf (content-type) "text/html; charset=utf-8") (let ((stream (send-headers)) (buffer (make-array 1024 :element-type '(unsigned-byte 8)))) (with-open-file (in (load-time-value (merge-pathnames "UTF-8-demo.html" *load-truename*)) :element-type '(unsigned-byte 8)) (loop for pos = (read-sequence buffer in) until (zerop pos) do (write-sequence buffer stream :end pos))))) (define-easy-handler (easy-demo :uri "/tbnl/test/easy-demo.html" :default-request-type :post) (first-name last-name (age :parameter-type 'integer) (implementation :parameter-type 'keyword) (meal :parameter-type '(hash-table boolean)) (team :parameter-type 'list)) (with-html (:html (:head (:title "TBNL \"easy\" handler example")) (:body (:h2 (tbnl-link) " \"Easy\" handler example") (:p (:form :method :post (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td "First Name:") (:td (:input :type :text :name "first-name" :value (or first-name "Donald")))) (:tr (:td "Last name:") (:td (:input :type :text :name "last-name" :value (or last-name "Duck")))) (:tr (:td "Age:") (:td (:input :type :text :name "age" :value (or age 42)))) (:tr (:td "Implementation:") (:td (:select :name "implementation" (loop for (value option) in '((:lispworks "LispWorks") (:allegro "AllegroCL") (:cmu "CMUCL") (:sbcl "SBCL") (:clisp "CLISP")) do (htm (:option :value value :selected (eq value implementation) (str option))))))) (:tr (:td :valign :top "Meal:") (:td (loop for choice in '("Burnt weeny sandwich" "Canard du jour" "Easy meat" "Muffin" "Twenty small cigars" "Yellow snow") do (htm (:input :type "checkbox" :name (format nil "meal{~A}" choice) :checked (gethash choice meal) (esc choice)) (:br))))) (:tr (:td :valign :top "Team:") (:td (loop for player in '("Beckenbauer" "Cruyff" "Maradona" without accent ( for SBCL ) "Pele" "Zidane") do (htm (:input :type "checkbox" :name "team" :value player :checked (member player team :test #'string=) (esc player)) (:br))))) (:tr (:td :colspan 2 (:input :type "submit")))))) (info-table first-name last-name age implementation (loop :for choice :being :the :hash-keys :of meal :collect choice) (gethash "Yellow snow" meal) team))))) (defun menu () (with-html (:html (:head (:title "TBNL Test Menu")) (:body (:h2 (str *headline*)) (:table :border 0 :cellspacing 4 :cellpadding 4 (:tr (:td (:a :href "/tbnl/test/info.html?foo=bar" "Info provided by TBNL"))) (:tr (:td (:a :href "/tbnl/test/cookie.html" "Cookie test"))) (:tr (:td (:a :href "/tbnl/test/session.html" "Session test"))) (:tr (:td (:a :href "/tbnl/test/parameter_latin1_get.html" "GET parameter handling with LATIN-1 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_latin1_post.html" "POST parameter handling with LATIN-1 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_utf8_get.html" "GET parameter handling with UTF-8 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_utf8_post.html" "POST parameter handling with UTF-8 charset"))) (:tr (:td (:a :href "/tbnl/test/redir.html" "Redirect \(302) to info page above"))) (:tr (:td (:a :href "/tbnl/test/authorization.html" "Authorization") " (user 'nanook', password 'igloo')")) (:tr (:td (:a :href "/tbnl/code/test.lisp" "The source code of this test"))) (:tr (:td (:a :href "/tbnl/test/image.jpg" "Binary data, delivered from file") " \(a picture)")) (:tr (:td (:a :href "/tbnl/test/image-ram.jpg" "Binary data, delivered from RAM") " \(same picture)")) (:tr (:td (:a :href "/tbnl/test/easy-demo.html" "\"Easy\" handler example"))) #+:lispworks (:tr (:td (:a :href "/tbnl/test/utf-8.html" "UTF-8 demo") " \(currently Lispworks-only)")) #+:tbnl-bivalent-streams (:tr (:td (:a :href "/tbnl/test/umlaut.txt" "UTF-8 demo") " \(writing directly to the stream)")) (:tr (:td (:a :href "/tbnl/test/upload.html" "File uploads"))) (:tr (:td (:a :href "/tbnl/test/forbidden.html" "Forbidden \(403) page"))) (:tr (:td (:a :href "/tbnl/test/oops.html" "Error handling") " \(output depends on settings like " (:a :href "/#*show-lisp-errors-p*" (:code "*SHOW-LISP-ERRORS-P*")) (fmt " \(currently ~S) and " *show-lisp-errors-p*) (:a :href "/#*show-lisp-backtraces-p*" (:code "*SHOW-LISP-BACKTRACES-P*")) (fmt " \(currently ~S)" *show-lisp-backtraces-p*) ")")) (:tr (:td (:a :href "/tbnl/foo" "URI handled by") " " (:a :href "/#*default-handler*" (:code "*DEFAULT-HANDLER*"))))))))) (setq *dispatch-table* (nconc (list 'dispatch-easy-handlers (create-static-file-dispatcher-and-handler "/tbnl/test/image.jpg" (make-pathname :name "fz" :type "jpg" :version nil :defaults (load-time-value *load-pathname*)) "image/jpeg") (create-folder-dispatcher-and-handler "/tbnl/code/" (make-pathname :name nil :type nil :version nil :defaults (load-time-value *load-pathname*)) "text/plain")) (mapcar (lambda (args) (apply #'create-prefix-dispatcher args)) '(("/tbnl/test/form-test.html" form-test) ("/tbnl/test/forbidden.html" forbidden) ("/tbnl/test/info.html" info) ("/tbnl/test/authorization.html" authorization-page) ("/tbnl/test/image-ram.jpg" image-ram-page) ("/tbnl/test/cookie.html" cookie-test) ("/tbnl/test/session.html" session-test) ("/tbnl/test/parameter_latin1_get.html" parameter-test-latin1-get) ("/tbnl/test/parameter_latin1_post.html" parameter-test-latin1-post) ("/tbnl/test/parameter_utf8_get.html" parameter-test-utf8-get) ("/tbnl/test/parameter_utf8_post.html" parameter-test-utf8-post) ("/tbnl/test/upload.html" upload-test) ("/tbnl/test/redir.html" redir) ("/tbnl/test/oops.html" oops) #+:lispworks ("/tbnl/test/utf-8.html" utf-8) #+:tbnl-bivalent-streams ("/tbnl/test/umlaut.txt" stream-direct) ("/tbnl/test/files/" send-file) ("/tbnl/test" menu))) (list #'default-dispatcher)))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/tbnl-0.11.4/test/test.lisp
lisp
Syntax : COMMON - LISP ; Package : TBNL ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. httpd.conf <Location /tbnl> </Location> (asdf:oos 'asdf:load-op :tbnl-test) (tbnl:start-tbnl) then point your browser at <>. See the docs for other testing options. this should not be the same directory as *TMP-DIRECTORY* and it should be initially empty (or non-existent) redirect so user can safely use 'Back' button demo file stolen from <-8-test/>
$ Header : /usr / local / cvsrep / tbnl / test / test.lisp , v 1.35 2006/09/04 22:54:36 edi Exp $ Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , To test TBNL with Apache add something like this to your LispServer 127.0.0.1 3000 " tbnl " SetHandler lisp - handler and afterwards restart Apache and evaluate (in-package #:tbnl-test) (defmacro with-html (&body body) `(with-html-output-to-string (*standard-output* nil :prologue t) ,@body)) (defun tbnl-link () (with-html-output (*standard-output*) (:a :href "/" "TBNL"))) (defun menu-link () (with-html-output (*standard-output*) (:p (:hr (:a :href "/tbnl/test" "Back to menu"))))) (defmacro info-table (&rest forms) (let ((=value= (gensym))) `(with-html-output (*standard-output*) (:p (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td :colspan 2 "Some Information " (tbnl-link) " provides about this request \(actual values may depend on front-end):")) ,@(loop for form in forms collect `(:tr (:td :valign "top" (:pre :style "padding: 0px" (let ((*package* (find-package :cl))) (pprint ',form)))) (:td :valign "top" (:pre :style "padding: 0px" (let ((*package* (find-package :cl))) (loop for ,=value= in (multiple-value-list ,form) for first = t then nil unless first do (princ ", ") do (pprint ,=value=))))))))) (menu-link)))) (defun authorization-page () (multiple-value-bind (user password) (authorization) (cond ((and (equal user "nanook") (equal password "igloo")) (with-html (:html (:head (:title "TBNL page with Basic Authentication")) (:body (:h2 (tbnl-link) " page with Basic Authentication") (info-table (header-in "Authorization") (authorization)))))) (t (require-authorization))))) (defparameter *test-image* (load-time-value (with-open-file (in (make-pathname :name "fz" :type "jpg" :version nil :defaults (load-time-value *load-pathname*)) #+:tbnl-bivalent-streams :element-type #+:tbnl-bivalent-streams '(unsigned-byte 8)) (let ((image-data (make-array (file-length in) :element-type #-:tbnl-bivalent-streams 'character #+:tbnl-bivalent-streams '(unsigned-byte 8)))) (read-sequence image-data in) image-data)))) (defun image-ram-page () (setf (content-type) "image/jpeg") *test-image*) (let ((count 0)) (defun info () (with-html (:html (:head (:title "TBNL Information")) (:body (:h2 (tbnl-link) " Information Page") (:p "This page has been called " (:b (fmt "~[~;once~;twice~:;~:*~R times~]" (incf count))) " since its handler was compiled.") (info-table (host) (server-addr) (server-port :as-number t) (request-method :as-keyword t) (script-name) (query-string) (get-parameters) (cookies-in) (remote-addr) (real-remote-addr) (remote-port :as-number t) (user-agent) (referer) (request-uri) (server-protocol :as-keyword t) (mod-lisp-id) (ssl-session-id))))))) (defun oops () (with-html (dotimes (i 3) (log-message* "Oops (default) # ~a" i)) (log-message :emerg "Oops emergency") (log-message :alert "Oops alert") (log-message :crit "Oops critical") (log-message :error "Oops error") (log-message :warning "Oops warning") (log-message :notice "Oops notice") (log-message :info "Oops info") (log-message :debug "Oops debug") (error "An error was triggered on purpose. Check your ~ Apache error log. Up to 12 messages where logged depending on ~ the Apache log level set in httpd.conf.") (:html (:body "You'll never see this sentence...")))) (defun redir () (redirect "/tbnl/test/info.html?redirected=1")) (defun forbidden () (setf (return-code *reply*) +http-forbidden+) nil) (defun cookie-test () (set-cookie "pumpkin" :value "barking") (no-cache) (with-html (:html (:head (:title "TBNL Cookie test")) (:body (:h2 (tbnl-link) " Cookie test") (:p "You might have to reload this page to see the cookie value.") (info-table (cookie-in "pumpkin") (mapcar #'car (cookies-in))))))) (defun session-test () (let ((new-foo-value (post-parameter "new-foo-value"))) (when new-foo-value (setf (session-value 'foo) new-foo-value))) (let ((new-bar-value (post-parameter "new-bar-value"))) (when new-bar-value (setf (session-value 'bar) new-bar-value))) (no-cache) (with-html (:html (:head (:title "TBNL Session test")) (:body (:h2 (tbnl-link) " Session test") (:p "Use the forms below to set new values for " (:code "FOO") " or " (:code "BAR") ". You can later return to this page to check if they're still set. Also, try to use another browser at the same time or try with cookies disabled.") (:p (:form :method :post "New value for " (:code "FOO") ": " (:input :type :text :name "new-foo-value" :value (or (session-value 'foo) "")))) (:p (:form :method :post "New value for " (:code "BAR") ": " (:input :type :text :name "new-bar-value" :value (or (session-value 'bar) "")))) (info-table *session-cookie-name* (cookie-in *session-cookie-name*) (mapcar #'car (cookies-in)) (session-value 'foo) (session-value 'bar)))))) (defun parameter-test (&key (method :get) (charset :iso-8859-1)) (no-cache) (recompute-request-parameters :external-format (case charset (:iso-8859-1 +latin-1+) (:utf-8 +utf-8+))) (setf (content-type) (format nil "text/html; charset=~A" charset)) (with-html (:html (:head (:title (fmt "TBNL ~A parameter Test" method))) (:body (:h2 (tbnl-link) (fmt " ~A parameter Test with charset ~A" method charset)) (:p "Enter some non-ASCII characters in the input field below and see what's happening. Check URL-DECODE and OCTETS-TO-STRING in " (:code "util.lisp") " to see if this test makes sense for your Lisp.") (:p (:form :method method "Enter a value: " (:input :type :text :name "foo"))) (case method (:get (info-table (query-string) (map 'list #'char-code (get-parameter "foo")) (escape-string-all (get-parameter "foo")))) (:post (info-table (raw-post-data) (map 'list #'char-code (post-parameter "foo")) (escape-string-all (post-parameter "foo"))))))))) (defun parameter-test-latin1-get () (parameter-test :method :get :charset :iso-8859-1)) (defun parameter-test-latin1-post () (parameter-test :method :post :charset :iso-8859-1)) (defun parameter-test-utf8-get () (parameter-test :method :get :charset :utf-8)) (defun parameter-test-utf8-post () (parameter-test :method :post :charset :utf-8)) (defvar *tmp-test-directory* #+(or :win32 :mswindows) #p"c:\\tbnl-temp\\test\\" #-(or :win32 :mswindows) #p"/tmp/tbnl/test/") (defvar *tmp-test-files* nil) (let ((counter 0)) (defun handle-file (post-parameter) (when (and post-parameter (listp post-parameter)) (destructuring-bind (path file-name content-type) post-parameter (let ((new-path (make-pathname :name (format nil "tbnl-test-~A" (incf counter)) :type nil :defaults *tmp-test-directory*))) strip directory info sent by Windows browsers (when (search "Windows" (user-agent) :test #'char-equal) (setq file-name (cl-ppcre:regex-replace ".*\\\\" file-name ""))) (rename-file path (ensure-directories-exist new-path)) (push (list new-path file-name content-type) *tmp-test-files*)))))) (defun clean-tmp-dir () (loop for (path . nil) in *tmp-test-files* when (probe-file path) do (ignore-errors (delete-file path))) (setq *tmp-test-files* nil)) (defun upload-test () (let (post-parameter-p) (when (post-parameter "file1") (handle-file (post-parameter "file1")) (setq post-parameter-p t)) (when (post-parameter "file2") (handle-file (post-parameter "file2")) (setq post-parameter-p t)) (when (post-parameter "clean") (clean-tmp-dir) (setq post-parameter-p t)) (when post-parameter-p (redirect (script-name)))) (no-cache) (with-html (:html (:head (:title "TBNL file upload test")) (:body (:h2 (tbnl-link) " File upload test") (:form :method :post :enctype "multipart/form-data" (:p "First file: " (:input :type :file :name "file1")) (:p "Second file: " (:input :type :file :name "file2")) (:p (:input :type :submit))) (when *tmp-test-files* (htm (:p (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td :colspan 3 (:b "Uploaded files"))) (loop for (path file-name nil) in *tmp-test-files* for counter from 1 do (htm (:tr (:td :align "right" (str counter)) (:td (:a :href (format nil "files/~A?path=~A" (url-encode file-name) (url-encode (namestring path))) (esc file-name))) (:td :align "right" (str (ignore-errors (with-open-file (in path) (file-length in)))) "&nbsp;Bytes")))))) (:form :method :post (:p (:input :type :submit :name "clean" :value "Delete uploaded files"))))) (menu-link))))) (defun send-file () (let* ((path (get-parameter "path")) (file-info (and path (find (pathname path) *tmp-test-files* :key #'first :test #'equal)))) (unless file-info (setf (return-code *reply*) +http-not-found+) (return-from send-file)) (handle-static-file path (third file-info)))) (defparameter *headline* (load-time-value (format nil "TBNL Test Menu (see file <code>~A</code>)" (merge-pathnames (make-pathname :type "lisp") *load-truename*)))) #+:lispworks (defun read-utf-8-file (pathspec) (coerce (external-format:encode-lisp-string (with-output-to-string (out nil :element-type 'lw:simple-char) (with-open-file (in pathspec :element-type 'lw:simple-char :external-format :utf-8) (loop for line = (read-line in nil nil) while line do (write-line line out)))) :utf-8) '(simple-array (unsigned-byte 8) (*)))) #+:lispworks (defun utf-8 () (setf (content-type) "text/html; charset=utf-8") (read-utf-8-file (load-time-value (merge-pathnames "UTF-8-demo.html" *load-truename*)))) #+:tbnl-bivalent-streams (defun stream-direct () (setf (content-type) "text/html; charset=utf-8") (let ((stream (send-headers)) (buffer (make-array 1024 :element-type '(unsigned-byte 8)))) (with-open-file (in (load-time-value (merge-pathnames "UTF-8-demo.html" *load-truename*)) :element-type '(unsigned-byte 8)) (loop for pos = (read-sequence buffer in) until (zerop pos) do (write-sequence buffer stream :end pos))))) (define-easy-handler (easy-demo :uri "/tbnl/test/easy-demo.html" :default-request-type :post) (first-name last-name (age :parameter-type 'integer) (implementation :parameter-type 'keyword) (meal :parameter-type '(hash-table boolean)) (team :parameter-type 'list)) (with-html (:html (:head (:title "TBNL \"easy\" handler example")) (:body (:h2 (tbnl-link) " \"Easy\" handler example") (:p (:form :method :post (:table :border 1 :cellpadding 2 :cellspacing 0 (:tr (:td "First Name:") (:td (:input :type :text :name "first-name" :value (or first-name "Donald")))) (:tr (:td "Last name:") (:td (:input :type :text :name "last-name" :value (or last-name "Duck")))) (:tr (:td "Age:") (:td (:input :type :text :name "age" :value (or age 42)))) (:tr (:td "Implementation:") (:td (:select :name "implementation" (loop for (value option) in '((:lispworks "LispWorks") (:allegro "AllegroCL") (:cmu "CMUCL") (:sbcl "SBCL") (:clisp "CLISP")) do (htm (:option :value value :selected (eq value implementation) (str option))))))) (:tr (:td :valign :top "Meal:") (:td (loop for choice in '("Burnt weeny sandwich" "Canard du jour" "Easy meat" "Muffin" "Twenty small cigars" "Yellow snow") do (htm (:input :type "checkbox" :name (format nil "meal{~A}" choice) :checked (gethash choice meal) (esc choice)) (:br))))) (:tr (:td :valign :top "Team:") (:td (loop for player in '("Beckenbauer" "Cruyff" "Maradona" without accent ( for SBCL ) "Pele" "Zidane") do (htm (:input :type "checkbox" :name "team" :value player :checked (member player team :test #'string=) (esc player)) (:br))))) (:tr (:td :colspan 2 (:input :type "submit")))))) (info-table first-name last-name age implementation (loop :for choice :being :the :hash-keys :of meal :collect choice) (gethash "Yellow snow" meal) team))))) (defun menu () (with-html (:html (:head (:title "TBNL Test Menu")) (:body (:h2 (str *headline*)) (:table :border 0 :cellspacing 4 :cellpadding 4 (:tr (:td (:a :href "/tbnl/test/info.html?foo=bar" "Info provided by TBNL"))) (:tr (:td (:a :href "/tbnl/test/cookie.html" "Cookie test"))) (:tr (:td (:a :href "/tbnl/test/session.html" "Session test"))) (:tr (:td (:a :href "/tbnl/test/parameter_latin1_get.html" "GET parameter handling with LATIN-1 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_latin1_post.html" "POST parameter handling with LATIN-1 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_utf8_get.html" "GET parameter handling with UTF-8 charset"))) (:tr (:td (:a :href "/tbnl/test/parameter_utf8_post.html" "POST parameter handling with UTF-8 charset"))) (:tr (:td (:a :href "/tbnl/test/redir.html" "Redirect \(302) to info page above"))) (:tr (:td (:a :href "/tbnl/test/authorization.html" "Authorization") " (user 'nanook', password 'igloo')")) (:tr (:td (:a :href "/tbnl/code/test.lisp" "The source code of this test"))) (:tr (:td (:a :href "/tbnl/test/image.jpg" "Binary data, delivered from file") " \(a picture)")) (:tr (:td (:a :href "/tbnl/test/image-ram.jpg" "Binary data, delivered from RAM") " \(same picture)")) (:tr (:td (:a :href "/tbnl/test/easy-demo.html" "\"Easy\" handler example"))) #+:lispworks (:tr (:td (:a :href "/tbnl/test/utf-8.html" "UTF-8 demo") " \(currently Lispworks-only)")) #+:tbnl-bivalent-streams (:tr (:td (:a :href "/tbnl/test/umlaut.txt" "UTF-8 demo") " \(writing directly to the stream)")) (:tr (:td (:a :href "/tbnl/test/upload.html" "File uploads"))) (:tr (:td (:a :href "/tbnl/test/forbidden.html" "Forbidden \(403) page"))) (:tr (:td (:a :href "/tbnl/test/oops.html" "Error handling") " \(output depends on settings like " (:a :href "/#*show-lisp-errors-p*" (:code "*SHOW-LISP-ERRORS-P*")) (fmt " \(currently ~S) and " *show-lisp-errors-p*) (:a :href "/#*show-lisp-backtraces-p*" (:code "*SHOW-LISP-BACKTRACES-P*")) (fmt " \(currently ~S)" *show-lisp-backtraces-p*) ")")) (:tr (:td (:a :href "/tbnl/foo" "URI handled by") " " (:a :href "/#*default-handler*" (:code "*DEFAULT-HANDLER*"))))))))) (setq *dispatch-table* (nconc (list 'dispatch-easy-handlers (create-static-file-dispatcher-and-handler "/tbnl/test/image.jpg" (make-pathname :name "fz" :type "jpg" :version nil :defaults (load-time-value *load-pathname*)) "image/jpeg") (create-folder-dispatcher-and-handler "/tbnl/code/" (make-pathname :name nil :type nil :version nil :defaults (load-time-value *load-pathname*)) "text/plain")) (mapcar (lambda (args) (apply #'create-prefix-dispatcher args)) '(("/tbnl/test/form-test.html" form-test) ("/tbnl/test/forbidden.html" forbidden) ("/tbnl/test/info.html" info) ("/tbnl/test/authorization.html" authorization-page) ("/tbnl/test/image-ram.jpg" image-ram-page) ("/tbnl/test/cookie.html" cookie-test) ("/tbnl/test/session.html" session-test) ("/tbnl/test/parameter_latin1_get.html" parameter-test-latin1-get) ("/tbnl/test/parameter_latin1_post.html" parameter-test-latin1-post) ("/tbnl/test/parameter_utf8_get.html" parameter-test-utf8-get) ("/tbnl/test/parameter_utf8_post.html" parameter-test-utf8-post) ("/tbnl/test/upload.html" upload-test) ("/tbnl/test/redir.html" redir) ("/tbnl/test/oops.html" oops) #+:lispworks ("/tbnl/test/utf-8.html" utf-8) #+:tbnl-bivalent-streams ("/tbnl/test/umlaut.txt" stream-direct) ("/tbnl/test/files/" send-file) ("/tbnl/test" menu))) (list #'default-dispatcher)))
7be215a53d078660e7342d4e6c6b192fa55eab7e160c015860a00adc11ae9609
GaloisInc/semmc
Eval.hs
-- | Evaluators for location functions in formula definitions (e.g., memri_reg) # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module SemMC.Architecture.ARM.Eval ( interpIsR15 , interpAm2offsetimmImmExtractor , interpAm2offsetimmAddExtractor , interpBlxTarget_S , interpBlxTarget_imm10H , interpBlxTarget_imm10L , interpBlxTarget_J1 , interpBlxTarget_J2 , interpImm12Reg , interpImm12RegExtractor , interpImm12OffsetExtractor , interpImm12AddFlgExtractor , interpImm01020s4ImmExtractor , interpImm0508s4ImmExtractor , interpLdstsoregAddExtractor , interpLdstsoregImmExtractor , interpLdstsoregTypeExtractor , interpLdstsoregBaseRegExtractor , interpLdstsoregBaseReg , interpLdstsoregOffRegExtractor , interpLdstsoregOffReg , interpModimmImmExtractor , interpModimmRotExtractor , interpSoregimmTypeExtractor , interpSoregimmImmExtractor , interpSoregimmRegExtractor , interpSoregimmReg , interpSoregregTypeExtractor , interpSoregregReg1Extractor , interpSoregregReg2Extractor , interpSoregregReg1 , interpSoregregReg2 , interpT2soimmImmExtractor , interpT2soregImmExtractor , interpT2soregRegExtractor , interpT2soregTypeExtractor , interpT2soregReg , interpTaddrmodeis2ImmExtractor , interpTaddrmodeis2RegExtractor , interpTaddrmodeis2Reg , interpTaddrmodeis4ImmExtractor , interpTaddrmodeis4RegExtractor , interpTaddrmodeis4Reg , interpTaddrmodepcExtractor , interpTReglistExtractor ) where import Data.Int ( Int16, Int8 ) import qualified Data.Parameterized.List as PL import qualified Data.Word.Indexed as W import qualified Dismantle.ARM.Operands as ARMOperands import qualified Dismantle.Thumb.Operands as ThumbOperands import qualified SemMC.Architecture as A import SemMC.Architecture.ARM.Location import qualified SemMC.Architecture.ARM.OperandComponents as AOC import qualified SemMC.Architecture.Location as L import qualified SemMC.Formula as F import What4.BaseTypes ------------------------------------------------------------------------ | Extract values from the ARM Am2offset_imm operand interpAm2offsetimmImmExtractor :: ARMOperands.Am2OffsetImm -> W.W 12 -- Int16 interpAm2offsetimmImmExtractor = {- fromIntegral . W.unW . -} ARMOperands.am2OffsetImmImmediate interpAm2offsetimmAddExtractor :: ARMOperands.Am2OffsetImm -> Bool interpAm2offsetimmAddExtractor = (== 1) . ARMOperands.am2OffsetImmAdd ------------------------------------------------------------------------ | Extract values from the ARM Addrmode_imm12 operand -- | Extract the register value from an addrmode_imm12[_pre] via -- the a32.imm12_reg user function. interpImm12Reg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpImm12Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCAddrmodeImm12 loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'imm12_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpImm12RegExtractor :: ARMOperands.AddrModeImm12 -> Maybe ARMOperands.GPR interpImm12RegExtractor = Just . ARMOperands.addrModeImm12Register interpImm12OffsetExtractor :: ARMOperands.AddrModeImm12 -> Int16 interpImm12OffsetExtractor = fromIntegral . W.unW . ARMOperands.addrModeImm12Immediate interpImm12AddFlgExtractor :: ARMOperands.AddrModeImm12 -> Bool interpImm12AddFlgExtractor = (== 1) . ARMOperands.addrModeImm12Add ------------------------------------------------------------------------ | Extract values from the Thumb AddrModePc operand interpTaddrmodepcExtractor :: ThumbOperands.AddrModePc -> Int8 interpTaddrmodepcExtractor = fromInteger . toInteger . ThumbOperands.addrModePcToBits ------------------------------------------------------------------------ | Extract values from the Thumb Imm0_1020S4 operand interpImm01020s4ImmExtractor :: ThumbOperands.TImm01020S4 -> Int8 interpImm01020s4ImmExtractor = fromInteger . toInteger . ThumbOperands.tImm01020S4ToBits ------------------------------------------------------------------------ -- | Extract values from the Thumb Imm0_508S4 operand interpImm0508s4ImmExtractor :: ThumbOperands.TImm0508S4 -> Int8 interpImm0508s4ImmExtractor = fromInteger . toInteger . ThumbOperands.tImm0508S4ToBits ------------------------------------------------------------------------ -- | Extract values from the ARM LdstSoReg operand interpLdstsoregAddExtractor :: ARMOperands.LdstSoReg -> Bool interpLdstsoregAddExtractor = (== 1) . ARMOperands.ldstSoRegAdd interpLdstsoregImmExtractor :: ARMOperands.LdstSoReg -> W.W 5 interpLdstsoregImmExtractor = ARMOperands.ldstSoRegImmediate interpLdstsoregTypeExtractor :: ARMOperands.LdstSoReg -> W.W 2 interpLdstsoregTypeExtractor = ARMOperands.ldstSoRegShiftType n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpLdstsoregBaseRegExtractor :: ARMOperands.LdstSoReg -> Maybe ARMOperands.GPR interpLdstsoregBaseRegExtractor = Just . ARMOperands.ldstSoRegBaseRegister n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpLdstsoregOffRegExtractor :: ARMOperands.LdstSoReg -> Maybe ARMOperands.GPR interpLdstsoregOffRegExtractor = Just . ARMOperands.ldstSoRegOffsetRegister interpLdstsoregBaseReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpLdstsoregBaseReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCLdstSoReg { AOC.ldstSoRegBaseLoc = loc }) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'ldst_so_reg' base reg at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) interpLdstsoregOffReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpLdstsoregOffReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCLdstSoReg { AOC.ldstSoRegOffsetLoc = loc }) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'ldst_so_reg' offset reg at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) ------------------------------------------------------------------------ | Extract values from the ARM Mod_imm operand interpModimmImmExtractor :: ARMOperands.ModImm -> Int8 interpModimmImmExtractor = fromIntegral . W.unW . ARMOperands.modImmOrigImmediate interpModimmRotExtractor :: ARMOperands.ModImm -> W.W 4 interpModimmRotExtractor = ARMOperands.modImmOrigRotate ------------------------------------------------------------------------ | Extract values from the Thumb ThumbBlxTarget operand interpBlxTarget_S :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_S = fromInteger . toInteger . ThumbOperands.thumbBlxTargetS interpBlxTarget_J1 :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_J1 = fromInteger . toInteger . ThumbOperands.thumbBlxTargetJ1 interpBlxTarget_J2 :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_J2 = fromInteger . toInteger . ThumbOperands.thumbBlxTargetJ2 interpBlxTarget_imm10H :: ThumbOperands.ThumbBlxTarget -> W.W 10 interpBlxTarget_imm10H = fromInteger . toInteger . ThumbOperands.thumbBlxTargetImm10H interpBlxTarget_imm10L :: ThumbOperands.ThumbBlxTarget -> W.W 10 interpBlxTarget_imm10L = fromInteger . toInteger . ThumbOperands.thumbBlxTargetImm10L ------------------------------------------------------------------------ | Extract values from the ARM SoRegImm operand interpSoregimmTypeExtractor :: ARMOperands.SoRegImm -> W.W 2 interpSoregimmTypeExtractor = ARMOperands.soRegImmShiftType interpSoregimmImmExtractor :: ARMOperands.SoRegImm -> W.W 5 interpSoregimmImmExtractor = ARMOperands.soRegImmImmediate n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregimmRegExtractor :: ARMOperands.SoRegImm -> Maybe ARMOperands.GPR interpSoregimmRegExtractor = Just . ARMOperands.soRegImmReg -- | Extract the register value from a SoRegReg via the -- a32.soregimm_reg user function. interpSoregimmReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregimmReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegImm loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregimm_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) ------------------------------------------------------------------------ -- | Extract values from the ARM SoRegReg operand n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregregReg1Extractor :: ARMOperands.SoRegReg -> Maybe ARMOperands.GPR interpSoregregReg1Extractor = Just . ARMOperands.soRegRegReg1 n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregregReg2Extractor :: ARMOperands.SoRegReg -> Maybe ARMOperands.GPR interpSoregregReg2Extractor = Just . ARMOperands.soRegRegReg2 interpSoregregTypeExtractor :: ARMOperands.SoRegReg -> W.W 2 interpSoregregTypeExtractor = ARMOperands.soRegRegShiftType -- | Extract the register value from a SoRegReg via the -- a32.soregreg_reg user function. interpSoregregReg1 :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregregReg1 operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegReg loc _ _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregreg_reg' 1 at index " ++ show ix) _ -> error ("Invalid operand type 1 at index " ++ show ix) -- | Extract the register value from a SoRegReg via the -- a32.soregreg_reg user function. interpSoregregReg2 :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregregReg2 operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegReg _ _ loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregreg_reg' 2 at index " ++ show ix) _ -> error ("Invalid operand type 2 at index " ++ show ix) ------------------------------------------------------------------------ -- | Extract values from the Thumb AddrModeIs4 operand interpTaddrmodeis2ImmExtractor :: ThumbOperands.AddrModeIs2 -> W.W 5 interpTaddrmodeis2ImmExtractor = fromInteger . toInteger . ThumbOperands.addrModeIs2Imm n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpTaddrmodeis2RegExtractor :: ThumbOperands.AddrModeIs2 -> Maybe ThumbOperands.LowGPR interpTaddrmodeis2RegExtractor = Just . ThumbOperands.addrModeIs2Reg interpTaddrmodeis2Reg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpTaddrmodeis2Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCTAddrModeIs2 loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'addrmode_is2_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) ------------------------------------------------------------------------ -- | Extract values from the Thumb AddrModeIs4 operand interpTaddrmodeis4ImmExtractor :: ThumbOperands.AddrModeIs4 -> W.W 5 interpTaddrmodeis4ImmExtractor = fromInteger . toInteger . ThumbOperands.addrModeIs4Imm n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpTaddrmodeis4RegExtractor :: ThumbOperands.AddrModeIs4 -> Maybe ThumbOperands.LowGPR interpTaddrmodeis4RegExtractor = Just . ThumbOperands.addrModeIs4Reg interpTaddrmodeis4Reg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpTaddrmodeis4Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCTAddrModeIs4 loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'addrmode_is4_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) ------------------------------------------------------------------------ -- | Extract values from the Thumb T2SoImm operand interpT2soimmImmExtractor :: ThumbOperands.T2SoImm -> W.W 12 interpT2soimmImmExtractor = fromInteger . toInteger . ThumbOperands.t2SoImmToBits ------------------------------------------------------------------------ | Extract values from Thumb T2SoReg operand interpT2soregImmExtractor :: ThumbOperands.T2SoReg -> W.W 5 interpT2soregImmExtractor = fromInteger . toInteger . ThumbOperands.t2SoRegImm5 interpT2soregRegExtractor :: ThumbOperands.T2SoReg -> Maybe ThumbOperands.GPR interpT2soregRegExtractor = Just . ThumbOperands.t2SoRegRm interpT2soregTypeExtractor :: ThumbOperands.T2SoReg -> W.W 2 interpT2soregTypeExtractor = fromInteger . toInteger . ThumbOperands.t2SoRegShiftType interpT2soregReg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpT2soregReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCT2SoReg loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 't2_so_reg_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) ------------------------------------------------------------------------ | Extract values from the Thumb Reglist operand interpTReglistExtractor :: ThumbOperands.Reglist -> Int16 interpTReglistExtractor = fromInteger . toInteger . ThumbOperands.regListToBits ------------------------------------------------------------------------ -- | Determination of whether this register reference is for R15 -- (which is often, but not always, the PC). class InterpIsR15 a where interpIsR15 :: a -> Bool instance InterpIsR15 ARMOperands.GPR where interpIsR15 gprReg = ARMOperands.unGPR gprReg == 15 instance InterpIsR15 (Maybe ARMOperands.GPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r instance InterpIsR15 ThumbOperands.GPR where interpIsR15 gprReg = ThumbOperands.unGPR gprReg == 15 instance InterpIsR15 (Maybe ThumbOperands.GPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r instance InterpIsR15 ThumbOperands.LowGPR where only 3 bits , can never be 15 instance InterpIsR15 (Maybe ThumbOperands.LowGPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r
null
https://raw.githubusercontent.com/GaloisInc/semmc/4dc4439720b3b0de8812a68f8156dc89da76da57/semmc-arm/src/SemMC/Architecture/ARM/Eval.hs
haskell
| Evaluators for location functions in formula definitions (e.g., memri_reg) # LANGUAGE GADTs # # LANGUAGE RankNTypes # ---------------------------------------------------------------------- Int16 fromIntegral . W.unW . ---------------------------------------------------------------------- | Extract the register value from an addrmode_imm12[_pre] via the a32.imm12_reg user function. ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- | Extract values from the Thumb Imm0_508S4 operand ---------------------------------------------------------------------- | Extract values from the ARM LdstSoReg operand ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- | Extract the register value from a SoRegReg via the a32.soregimm_reg user function. ---------------------------------------------------------------------- | Extract values from the ARM SoRegReg operand | Extract the register value from a SoRegReg via the a32.soregreg_reg user function. | Extract the register value from a SoRegReg via the a32.soregreg_reg user function. ---------------------------------------------------------------------- | Extract values from the Thumb AddrModeIs4 operand ---------------------------------------------------------------------- | Extract values from the Thumb AddrModeIs4 operand ---------------------------------------------------------------------- | Extract values from the Thumb T2SoImm operand ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- | Determination of whether this register reference is for R15 (which is often, but not always, the PC).
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module SemMC.Architecture.ARM.Eval ( interpIsR15 , interpAm2offsetimmImmExtractor , interpAm2offsetimmAddExtractor , interpBlxTarget_S , interpBlxTarget_imm10H , interpBlxTarget_imm10L , interpBlxTarget_J1 , interpBlxTarget_J2 , interpImm12Reg , interpImm12RegExtractor , interpImm12OffsetExtractor , interpImm12AddFlgExtractor , interpImm01020s4ImmExtractor , interpImm0508s4ImmExtractor , interpLdstsoregAddExtractor , interpLdstsoregImmExtractor , interpLdstsoregTypeExtractor , interpLdstsoregBaseRegExtractor , interpLdstsoregBaseReg , interpLdstsoregOffRegExtractor , interpLdstsoregOffReg , interpModimmImmExtractor , interpModimmRotExtractor , interpSoregimmTypeExtractor , interpSoregimmImmExtractor , interpSoregimmRegExtractor , interpSoregimmReg , interpSoregregTypeExtractor , interpSoregregReg1Extractor , interpSoregregReg2Extractor , interpSoregregReg1 , interpSoregregReg2 , interpT2soimmImmExtractor , interpT2soregImmExtractor , interpT2soregRegExtractor , interpT2soregTypeExtractor , interpT2soregReg , interpTaddrmodeis2ImmExtractor , interpTaddrmodeis2RegExtractor , interpTaddrmodeis2Reg , interpTaddrmodeis4ImmExtractor , interpTaddrmodeis4RegExtractor , interpTaddrmodeis4Reg , interpTaddrmodepcExtractor , interpTReglistExtractor ) where import Data.Int ( Int16, Int8 ) import qualified Data.Parameterized.List as PL import qualified Data.Word.Indexed as W import qualified Dismantle.ARM.Operands as ARMOperands import qualified Dismantle.Thumb.Operands as ThumbOperands import qualified SemMC.Architecture as A import SemMC.Architecture.ARM.Location import qualified SemMC.Architecture.ARM.OperandComponents as AOC import qualified SemMC.Architecture.Location as L import qualified SemMC.Formula as F import What4.BaseTypes | Extract values from the ARM Am2offset_imm operand interpAm2offsetimmAddExtractor :: ARMOperands.Am2OffsetImm -> Bool interpAm2offsetimmAddExtractor = (== 1) . ARMOperands.am2OffsetImmAdd | Extract values from the ARM Addrmode_imm12 operand interpImm12Reg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpImm12Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCAddrmodeImm12 loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'imm12_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpImm12RegExtractor :: ARMOperands.AddrModeImm12 -> Maybe ARMOperands.GPR interpImm12RegExtractor = Just . ARMOperands.addrModeImm12Register interpImm12OffsetExtractor :: ARMOperands.AddrModeImm12 -> Int16 interpImm12OffsetExtractor = fromIntegral . W.unW . ARMOperands.addrModeImm12Immediate interpImm12AddFlgExtractor :: ARMOperands.AddrModeImm12 -> Bool interpImm12AddFlgExtractor = (== 1) . ARMOperands.addrModeImm12Add | Extract values from the Thumb AddrModePc operand interpTaddrmodepcExtractor :: ThumbOperands.AddrModePc -> Int8 interpTaddrmodepcExtractor = fromInteger . toInteger . ThumbOperands.addrModePcToBits | Extract values from the Thumb Imm0_1020S4 operand interpImm01020s4ImmExtractor :: ThumbOperands.TImm01020S4 -> Int8 interpImm01020s4ImmExtractor = fromInteger . toInteger . ThumbOperands.tImm01020S4ToBits interpImm0508s4ImmExtractor :: ThumbOperands.TImm0508S4 -> Int8 interpImm0508s4ImmExtractor = fromInteger . toInteger . ThumbOperands.tImm0508S4ToBits interpLdstsoregAddExtractor :: ARMOperands.LdstSoReg -> Bool interpLdstsoregAddExtractor = (== 1) . ARMOperands.ldstSoRegAdd interpLdstsoregImmExtractor :: ARMOperands.LdstSoReg -> W.W 5 interpLdstsoregImmExtractor = ARMOperands.ldstSoRegImmediate interpLdstsoregTypeExtractor :: ARMOperands.LdstSoReg -> W.W 2 interpLdstsoregTypeExtractor = ARMOperands.ldstSoRegShiftType n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpLdstsoregBaseRegExtractor :: ARMOperands.LdstSoReg -> Maybe ARMOperands.GPR interpLdstsoregBaseRegExtractor = Just . ARMOperands.ldstSoRegBaseRegister n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpLdstsoregOffRegExtractor :: ARMOperands.LdstSoReg -> Maybe ARMOperands.GPR interpLdstsoregOffRegExtractor = Just . ARMOperands.ldstSoRegOffsetRegister interpLdstsoregBaseReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpLdstsoregBaseReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCLdstSoReg { AOC.ldstSoRegBaseLoc = loc }) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'ldst_so_reg' base reg at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) interpLdstsoregOffReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpLdstsoregOffReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCLdstSoReg { AOC.ldstSoRegOffsetLoc = loc }) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'ldst_so_reg' offset reg at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) | Extract values from the ARM Mod_imm operand interpModimmImmExtractor :: ARMOperands.ModImm -> Int8 interpModimmImmExtractor = fromIntegral . W.unW . ARMOperands.modImmOrigImmediate interpModimmRotExtractor :: ARMOperands.ModImm -> W.W 4 interpModimmRotExtractor = ARMOperands.modImmOrigRotate | Extract values from the Thumb ThumbBlxTarget operand interpBlxTarget_S :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_S = fromInteger . toInteger . ThumbOperands.thumbBlxTargetS interpBlxTarget_J1 :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_J1 = fromInteger . toInteger . ThumbOperands.thumbBlxTargetJ1 interpBlxTarget_J2 :: ThumbOperands.ThumbBlxTarget -> W.W 1 interpBlxTarget_J2 = fromInteger . toInteger . ThumbOperands.thumbBlxTargetJ2 interpBlxTarget_imm10H :: ThumbOperands.ThumbBlxTarget -> W.W 10 interpBlxTarget_imm10H = fromInteger . toInteger . ThumbOperands.thumbBlxTargetImm10H interpBlxTarget_imm10L :: ThumbOperands.ThumbBlxTarget -> W.W 10 interpBlxTarget_imm10L = fromInteger . toInteger . ThumbOperands.thumbBlxTargetImm10L | Extract values from the ARM SoRegImm operand interpSoregimmTypeExtractor :: ARMOperands.SoRegImm -> W.W 2 interpSoregimmTypeExtractor = ARMOperands.soRegImmShiftType interpSoregimmImmExtractor :: ARMOperands.SoRegImm -> W.W 5 interpSoregimmImmExtractor = ARMOperands.soRegImmImmediate n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregimmRegExtractor :: ARMOperands.SoRegImm -> Maybe ARMOperands.GPR interpSoregimmRegExtractor = Just . ARMOperands.soRegImmReg interpSoregimmReg :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregimmReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegImm loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregimm_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregregReg1Extractor :: ARMOperands.SoRegReg -> Maybe ARMOperands.GPR interpSoregregReg1Extractor = Just . ARMOperands.soRegRegReg1 n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpSoregregReg2Extractor :: ARMOperands.SoRegReg -> Maybe ARMOperands.GPR interpSoregregReg2Extractor = Just . ARMOperands.soRegRegReg2 interpSoregregTypeExtractor :: ARMOperands.SoRegReg -> W.W 2 interpSoregregTypeExtractor = ARMOperands.soRegRegShiftType interpSoregregReg1 :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregregReg1 operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegReg loc _ _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregreg_reg' 1 at index " ++ show ix) _ -> error ("Invalid operand type 1 at index " ++ show ix) interpSoregregReg2 :: forall sh s arm tp sym . ( L.IsLocation (L.Location arm) , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpSoregregReg2 operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCSoRegReg _ _ loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'soregreg_reg' 2 at index " ++ show ix) _ -> error ("Invalid operand type 2 at index " ++ show ix) interpTaddrmodeis2ImmExtractor :: ThumbOperands.AddrModeIs2 -> W.W 5 interpTaddrmodeis2ImmExtractor = fromInteger . toInteger . ThumbOperands.addrModeIs2Imm n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpTaddrmodeis2RegExtractor :: ThumbOperands.AddrModeIs2 -> Maybe ThumbOperands.LowGPR interpTaddrmodeis2RegExtractor = Just . ThumbOperands.addrModeIs2Reg interpTaddrmodeis2Reg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpTaddrmodeis2Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCTAddrModeIs2 loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'addrmode_is2_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) interpTaddrmodeis4ImmExtractor :: ThumbOperands.AddrModeIs4 -> W.W 5 interpTaddrmodeis4ImmExtractor = fromInteger . toInteger . ThumbOperands.addrModeIs4Imm n.b . there is no Nothing , but the call in . SemMC.TH expects a Maybe result . interpTaddrmodeis4RegExtractor :: ThumbOperands.AddrModeIs4 -> Maybe ThumbOperands.LowGPR interpTaddrmodeis4RegExtractor = Just . ThumbOperands.addrModeIs4Reg interpTaddrmodeis4Reg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpTaddrmodeis4Reg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCTAddrModeIs4 loc _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 'addrmode_is4_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) interpT2soimmImmExtractor :: ThumbOperands.T2SoImm -> W.W 12 interpT2soimmImmExtractor = fromInteger . toInteger . ThumbOperands.t2SoImmToBits | Extract values from Thumb T2SoReg operand interpT2soregImmExtractor :: ThumbOperands.T2SoReg -> W.W 5 interpT2soregImmExtractor = fromInteger . toInteger . ThumbOperands.t2SoRegImm5 interpT2soregRegExtractor :: ThumbOperands.T2SoReg -> Maybe ThumbOperands.GPR interpT2soregRegExtractor = Just . ThumbOperands.t2SoRegRm interpT2soregTypeExtractor :: ThumbOperands.T2SoReg -> W.W 2 interpT2soregTypeExtractor = fromInteger . toInteger . ThumbOperands.t2SoRegShiftType interpT2soregReg :: forall sh s arm tp sym . ( L.IsLocation (Location arm) , L.Location arm ~ Location arm , A.OperandComponents arm sym ~ AOC.OperandComponents arm sym ) => PL.List (A.AllocatedOperand arm sym) sh -> F.WrappedOperand arm sh s -> BaseTypeRepr tp -> Maybe (L.Location arm tp) interpT2soregReg operands (F.WrappedOperand _orep ix) rep = case operands PL.!! ix of A.CompoundOperand (AOC.OCT2SoReg loc _ _ _) | Just Refl <- testEquality (L.locationType loc) rep -> Just loc | otherwise -> error ("Invalid return type for location function 't2_so_reg_reg' at index " ++ show ix) _ -> error ("Invalid operand type at index " ++ show ix) | Extract values from the Thumb Reglist operand interpTReglistExtractor :: ThumbOperands.Reglist -> Int16 interpTReglistExtractor = fromInteger . toInteger . ThumbOperands.regListToBits class InterpIsR15 a where interpIsR15 :: a -> Bool instance InterpIsR15 ARMOperands.GPR where interpIsR15 gprReg = ARMOperands.unGPR gprReg == 15 instance InterpIsR15 (Maybe ARMOperands.GPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r instance InterpIsR15 ThumbOperands.GPR where interpIsR15 gprReg = ThumbOperands.unGPR gprReg == 15 instance InterpIsR15 (Maybe ThumbOperands.GPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r instance InterpIsR15 ThumbOperands.LowGPR where only 3 bits , can never be 15 instance InterpIsR15 (Maybe ThumbOperands.LowGPR) where interpIsR15 mr = case mr of Nothing -> True Just r -> interpIsR15 r
d638a9e2d9705807a6f0297467dad37144cb4ad55bc8646b574fba52423b8a6d
racket/redex
stlc-sub-3.rkt
#lang racket/base (require redex/benchmark "util.rkt" redex/reduction-semantics) (provide (all-defined-out)) (define the-error "swaps function and argument position in application") (define-rewrite bug3 ((subst M x M_x) (subst N x M_x)) ==> ((subst N x M_x) (subst M x M_x)) #:context (define-metafunction) #:once-only) (include/rewrite (lib "redex/examples/stlc+lists+subst.rkt") stlc-sub bug3) (include/rewrite "generators.rkt" generators bug-mod-rw subst-check-rw) (define small-counter-example (term ((λ (a int) (+ 0)) 0))) (test small-counter-example)
null
https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-benchmark/redex/benchmark/models/stlc-subst/stlc-sub-3.rkt
racket
#lang racket/base (require redex/benchmark "util.rkt" redex/reduction-semantics) (provide (all-defined-out)) (define the-error "swaps function and argument position in application") (define-rewrite bug3 ((subst M x M_x) (subst N x M_x)) ==> ((subst N x M_x) (subst M x M_x)) #:context (define-metafunction) #:once-only) (include/rewrite (lib "redex/examples/stlc+lists+subst.rkt") stlc-sub bug3) (include/rewrite "generators.rkt" generators bug-mod-rw subst-check-rw) (define small-counter-example (term ((λ (a int) (+ 0)) 0))) (test small-counter-example)
8bef4dccdb9ac759b7cc166ed8319ce482f203a21eeb26c421740a72b162233b
Eduap-com/WordMat
ar.lisp
-*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The data in this file contains enhancments. ;;;;; ;;; ;;;;; Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ; ;;; All rights reserved ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( c ) Copyright 1981 Massachusetts Institute of Technology ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (macsyma-module ar) (declare-top (special evarrp munbound flounbound fixunbound $use_fast_arrays)) (defstruct (mgenarray (:conc-name mgenarray-)) aref aset type null generator content) (defun marray-type (x) (cond ((arrayp x) 'array) ((hash-table-p x) 'hash-table) ((eq (type-of x) 'mgenarray) (mgenarray-type x)))) (defmfun $make_array (type &rest diml) (let ((ltype (assoc type '(($float . flonum) ($flonum . flonum) ($fixnum . fixnum))))) ;; Check the dimensions. No check for number of dimensions. (when (member nil (mapcar #'(lambda (u) (fixnump u)) ;; For a functional array the list of dimensions starts at the third element of the list diml (if (eq type '$functional) (cddr diml) diml)) :test #'eq) (merror (intl:gettext "make_array: dimensions must be integers; found ~M") `((mlist) ,@diml))) (if (not ltype) (case type ($any (make-array diml :initial-element nil)) ($hashed (make-equal-hash-table (cdr diml))) ($functional ;; MAKE_ARRAY('FUNCTIONAL, LAMBDA(...), 'ARRAY_TYPE, ...) This is a array . (unless (> (length diml) 1) (merror (intl:gettext "make_array: not enough arguments for functional array specification."))) (let ((ar (apply #'$make_array (cadr diml) (cddr diml))) (the-null)) (case (cadr diml) ($fixnum (fillarray ar (list (setq the-null fixunbound)))) (($flonum $float) (fillarray ar (list (setq the-null flounbound)))) ($any (fillarray ar (list (setq the-null munbound)))) (t ;; Nothing to do for hashed arrays. Is FUNCTIONAL here an error? ;; No, it is the most useful case for a FUNCTIONAL array. (setq the-null nil))) (make-mgenarray :type '$functional :content ar :generator (car diml) :null the-null))) (t (merror (intl:gettext "make_array: array type ~M not recognized.") type))) (make-array diml :initial-element (case (cdr ltype) (fixnum 0) (flonum 0.0) (otherwise nil)))))) (defun dimension-array-object (form result) (let ((mtype (marray-type form))) (if (eq mtype '$functional) (dimension-array-object (mgenarray-content form) result) (dimension-atom (format nil "{Lisp Array: ~A}" form) result)))) (defun msize-array-object (x l r) (let ((mtype (marray-type x))) (if (eq mtype '$functional) (msize-array-object (mgenarray-content x) l r) (msize-atom (format nil "{Lisp Array: ~A}" x) l r)))) (defun marray-check (a) (if (arrayp a) (case (marray-type a) (($fixnum $float) a) (($any) (mgenarray-content a)) (($hashed $functional) ;; BUG: It does have a number of dimensions! Gosh. -GJC (merror (intl:gettext "MARRAY-CHECK: hashed array ~M has no dimension data.") a)) (t (marray-type-unknown a))) (merror (intl:gettext "MARRAY-CHECK: not an array: ~M") a))) (defmfun $array_dimension_n (n a) (array-dimension (marray-check a) n)) (defun marray-type-unknown (x) (merror (intl:gettext "MARRAY-TYPE-UNKNOWN: array type ~S not recognized.") x)) (defun marrayref-gensub (aarray ind1 inds) (case (marray-type aarray) We are using a CASE on the TYPE instead of a FUNCALL , ( or ) ;; because we are losers. All this stuff uses too many functions from ;; the "MLISP" modual, which are not really suitable for the kind of ;; speed and simplicity we want anyway. Ah me. Also, passing the single unconsed index IND1 around is a dubious optimization , which causes ;; extra consing in the case of hashed arrays. ((array) (unless (and (integerp ind1) (every #'integerp inds)) (bad-index-error (cons ind1 inds))) (apply #'aref aarray ind1 inds)) ((hash-table) (gethash (if inds (cons ind1 inds) ind1) aarray)) (($functional) (let ((value (let ((evarrp t)) ;; special variable changes behavior of hashed-array ;; referencing functions in case of not finding an element. (catch 'evarrp (marrayref-gensub (mgenarray-content aarray) ind1 inds))))) (if (equal value (mgenarray-null aarray)) (marrayset-gensub (apply #'mfuncall (mgenarray-generator aarray) the first argument we pass the ;; function is a SELF variable. ; aarray extra consing here ! madness . ind1 inds) (mgenarray-content aarray) ind1 inds) value))) (t (marray-type-unknown aarray)))) INDICES is a Lisp list , not a Maxima list . (defun bad-index-error (indices) (let ((m-indices (cons '(mlist) indices))) (cond ((every #'(lambda (x) (or ($ratp x) (integerp x))) indices) (merror (intl::gettext "array: indices cannot be special expressions (CRE or Taylor); found: ~M") m-indices)) ((every #'(lambda (x) (or ($mapatom x) (integerp x))) indices) (merror (intl::gettext "array: indices cannot be plain or subscripted symbols; found: ~M") m-indices)) (t (merror (intl::gettext "array: indices must be literal integers; found: ~M") m-indices))))) (defun marrayset-gensub (val aarray ind1 inds) (case (marray-type aarray) ((array) (unless (and (integerp ind1) (every #'integerp inds)) (bad-index-error (cons ind1 inds))) (setf (apply #'aref aarray ind1 inds) val)) ((hash-table) (setf (gethash (if inds (cons ind1 inds) ind1) aarray) val)) (($functional) (marrayset-gensub val (mgenarray-content aarray) ind1 inds)) (t (marray-type-unknown aarray)))) ;; Extensions to MEVAL. (defun meval1-extend (form) (let ((l (mevalargs (cdr form)))) (marrayref-gensub (caar form) (car l) (cdr l)))) (defun arrstore-extend (a l r) (marrayset-gensub r a (car l) (cdr l)))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/src/ar.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; ; ; Check the dimensions. No check for number of dimensions. For a functional array the list of dimensions MAKE_ARRAY('FUNCTIONAL, LAMBDA(...), 'ARRAY_TYPE, ...) Nothing to do for hashed arrays. Is FUNCTIONAL here an error? No, it is the most useful case for a FUNCTIONAL array. BUG: It does have a number of dimensions! Gosh. -GJC because we are losers. All this stuff uses too many functions from the "MLISP" modual, which are not really suitable for the kind of speed and simplicity we want anyway. Ah me. Also, passing the single extra consing in the case of hashed arrays. special variable changes behavior of hashed-array referencing functions in case of not finding an element. function is a SELF variable. aarray Extensions to MEVAL.
(in-package :maxima) (macsyma-module ar) (declare-top (special evarrp munbound flounbound fixunbound $use_fast_arrays)) (defstruct (mgenarray (:conc-name mgenarray-)) aref aset type null generator content) (defun marray-type (x) (cond ((arrayp x) 'array) ((hash-table-p x) 'hash-table) ((eq (type-of x) 'mgenarray) (mgenarray-type x)))) (defmfun $make_array (type &rest diml) (let ((ltype (assoc type '(($float . flonum) ($flonum . flonum) ($fixnum . fixnum))))) (when (member nil (mapcar #'(lambda (u) (fixnump u)) starts at the third element of the list diml (if (eq type '$functional) (cddr diml) diml)) :test #'eq) (merror (intl:gettext "make_array: dimensions must be integers; found ~M") `((mlist) ,@diml))) (if (not ltype) (case type ($any (make-array diml :initial-element nil)) ($hashed (make-equal-hash-table (cdr diml))) ($functional This is a array . (unless (> (length diml) 1) (merror (intl:gettext "make_array: not enough arguments for functional array specification."))) (let ((ar (apply #'$make_array (cadr diml) (cddr diml))) (the-null)) (case (cadr diml) ($fixnum (fillarray ar (list (setq the-null fixunbound)))) (($flonum $float) (fillarray ar (list (setq the-null flounbound)))) ($any (fillarray ar (list (setq the-null munbound)))) (t (setq the-null nil))) (make-mgenarray :type '$functional :content ar :generator (car diml) :null the-null))) (t (merror (intl:gettext "make_array: array type ~M not recognized.") type))) (make-array diml :initial-element (case (cdr ltype) (fixnum 0) (flonum 0.0) (otherwise nil)))))) (defun dimension-array-object (form result) (let ((mtype (marray-type form))) (if (eq mtype '$functional) (dimension-array-object (mgenarray-content form) result) (dimension-atom (format nil "{Lisp Array: ~A}" form) result)))) (defun msize-array-object (x l r) (let ((mtype (marray-type x))) (if (eq mtype '$functional) (msize-array-object (mgenarray-content x) l r) (msize-atom (format nil "{Lisp Array: ~A}" x) l r)))) (defun marray-check (a) (if (arrayp a) (case (marray-type a) (($fixnum $float) a) (($any) (mgenarray-content a)) (($hashed $functional) (merror (intl:gettext "MARRAY-CHECK: hashed array ~M has no dimension data.") a)) (t (marray-type-unknown a))) (merror (intl:gettext "MARRAY-CHECK: not an array: ~M") a))) (defmfun $array_dimension_n (n a) (array-dimension (marray-check a) n)) (defun marray-type-unknown (x) (merror (intl:gettext "MARRAY-TYPE-UNKNOWN: array type ~S not recognized.") x)) (defun marrayref-gensub (aarray ind1 inds) (case (marray-type aarray) We are using a CASE on the TYPE instead of a FUNCALL , ( or ) unconsed index IND1 around is a dubious optimization , which causes ((array) (unless (and (integerp ind1) (every #'integerp inds)) (bad-index-error (cons ind1 inds))) (apply #'aref aarray ind1 inds)) ((hash-table) (gethash (if inds (cons ind1 inds) ind1) aarray)) (($functional) (let ((value (let ((evarrp t)) (catch 'evarrp (marrayref-gensub (mgenarray-content aarray) ind1 inds))))) (if (equal value (mgenarray-null aarray)) (marrayset-gensub (apply #'mfuncall (mgenarray-generator aarray) the first argument we pass the extra consing here ! madness . ind1 inds) (mgenarray-content aarray) ind1 inds) value))) (t (marray-type-unknown aarray)))) INDICES is a Lisp list , not a Maxima list . (defun bad-index-error (indices) (let ((m-indices (cons '(mlist) indices))) (cond ((every #'(lambda (x) (or ($ratp x) (integerp x))) indices) (merror (intl::gettext "array: indices cannot be special expressions (CRE or Taylor); found: ~M") m-indices)) ((every #'(lambda (x) (or ($mapatom x) (integerp x))) indices) (merror (intl::gettext "array: indices cannot be plain or subscripted symbols; found: ~M") m-indices)) (t (merror (intl::gettext "array: indices must be literal integers; found: ~M") m-indices))))) (defun marrayset-gensub (val aarray ind1 inds) (case (marray-type aarray) ((array) (unless (and (integerp ind1) (every #'integerp inds)) (bad-index-error (cons ind1 inds))) (setf (apply #'aref aarray ind1 inds) val)) ((hash-table) (setf (gethash (if inds (cons ind1 inds) ind1) aarray) val)) (($functional) (marrayset-gensub val (mgenarray-content aarray) ind1 inds)) (t (marray-type-unknown aarray)))) (defun meval1-extend (form) (let ((l (mevalargs (cdr form)))) (marrayref-gensub (caar form) (car l) (cdr l)))) (defun arrstore-extend (a l r) (marrayset-gensub r a (car l) (cdr l)))
d4e0f651b0c8f0b4472a4d844afeb207495c0d23a23524155eccf7ea80b844ac
PeterDWhite/Osker
BraidUtilities.hs
Copyright ( C ) , 2001 , 2002 , 2003 module BraidUtilities Braid of threads , B.ProgramType (..) -- Thread lifted, unlifted, or wait? , OC.ThreadId -- Abstract type of thread identifiers Creates MVar that is written when thread dies Like myForkIO , but waits on oneshot first , ForkInfo (..) -- Information generated about a thread An MVar to be written only once Create a new one shot Shoot the one shot Shoot a bunch of one shots ) where -- Haskell imports import Monad Braid imports import qualified OskerConcurrent as OC import qualified BraidExternal as B -- Utility imports import qualified BraidOneShot as OS import Null data ForkInfo m = ForkInfo { tiTid :: B.ThreadId -- Created by the resumption fork , tiChan :: OC.Chan m -- Input channel for the thread , tiDone :: OS.OneShot -- Can wait on this until thread is done , tiStart :: OS.OneShot -- Forked process waits on this to start } instance Show (ForkInfo m) where show ti = show (tiTid ti) Modified form of myForkIO from the GHC user manual . This fork creates an MVar , and puts something in it when -- it dies. This permits the creator to wait for the forked -- child to die. myFork :: (Null ls, Show ls, Show gs) => -- String -> -- Name of the new thread OC.Chan m -> -- Input channel of the process Program of the new thread B.Braid gs ls (ForkInfo m) -- Resulting braid myFork name chan program = do { mvar <- OC.newEmptyMVar name ; tid <- OC.fork name program ; OC.putMVar mvar OS.shoot ; return ( ForkInfo { tiTid = tid , tiChan = chan , tiDone = mvar , tiStart = error "No one shot for myForkIO" }) } Make an Braid action wait on a oneshot first wrapIo :: (Show ls, Show gs) => -- OS.OneShot -> -- Start up variable Program to wrap B.Braid gs ls a -- An Braid action wrapIo startShot threadProgram = do { OS.waitToBeShot startShot ; threadProgram } Another fork version . This one takes an MVar as argument . The MVar is a " one shot " . I.e. it is only written once . The forked thread waits on the one shot before it starts . This permits the -- creator to sequence the start up of operations of its child -- threads with a finer granularity. oskerFork :: ( Null ls, Show ls, Show gs ) => -- String -> -- Name of the process OC.Chan m -> -- Input channel of the process Program of the new thread B.Braid gs ls (ForkInfo m) -- Resulting braid oskerFork name chan program = do { -- Make the termination condition variable waitShot <- OS.newOneShot (name ++ ".wait") Make the new start up one shot ; startShot <- OS.newOneShot (name ++ ".start") -- Create the thread, and its associated data, -- and feed the input channel to the program ; tid <- OC.fork name ( do { wrapIo startShot program ; OC.putMVar waitShot OS.shoot ; return mkNull } ) Ready to format the KernelThread ; return ( ForkInfo { tiTid = tid , tiChan = chan , tiDone = waitShot , tiStart = startShot } ) }
null
https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Braid/BraidUtilities.hs
haskell
Thread lifted, unlifted, or wait? Abstract type of thread identifiers Information generated about a thread Haskell imports Utility imports Created by the resumption fork Input channel for the thread Can wait on this until thread is done Forked process waits on this to start it dies. This permits the creator to wait for the forked child to die. Name of the new thread Input channel of the process Resulting braid Start up variable An Braid action creator to sequence the start up of operations of its child threads with a finer granularity. Name of the process Input channel of the process Resulting braid Make the termination condition variable Create the thread, and its associated data, and feed the input channel to the program
Copyright ( C ) , 2001 , 2002 , 2003 module BraidUtilities Braid of threads Creates MVar that is written when thread dies Like myForkIO , but waits on oneshot first An MVar to be written only once Create a new one shot Shoot the one shot Shoot a bunch of one shots ) where import Monad Braid imports import qualified OskerConcurrent as OC import qualified BraidExternal as B import qualified BraidOneShot as OS import Null data ForkInfo m = ForkInfo } instance Show (ForkInfo m) where show ti = show (tiTid ti) Modified form of myForkIO from the GHC user manual . This fork creates an MVar , and puts something in it when Program of the new thread myFork name chan program = do { mvar <- OC.newEmptyMVar name ; tid <- OC.fork name program ; OC.putMVar mvar OS.shoot ; return ( ForkInfo { tiTid = tid , tiChan = chan , tiDone = mvar , tiStart = error "No one shot for myForkIO" }) } Make an Braid action wait on a oneshot first Program to wrap wrapIo startShot threadProgram = do { OS.waitToBeShot startShot ; threadProgram } Another fork version . This one takes an MVar as argument . The MVar is a " one shot " . I.e. it is only written once . The forked thread waits on the one shot before it starts . This permits the Program of the new thread oskerFork name chan program = waitShot <- OS.newOneShot (name ++ ".wait") Make the new start up one shot ; startShot <- OS.newOneShot (name ++ ".start") ; tid <- OC.fork name ( do { wrapIo startShot program ; OC.putMVar waitShot OS.shoot ; return mkNull } ) Ready to format the KernelThread ; return ( ForkInfo { tiTid = tid , tiChan = chan , tiDone = waitShot , tiStart = startShot } ) }
17850e9fdeb78e2046a98716c30aa7221d38ca7282add3fe8007fb17348e448b
inclojure-org/intermediate-clojure-workshop
users.clj
(ns workshop-app.handlers.users (:require [workshop-app.db.in-mem :as wadim] [cheshire.core :as json])) (defn get-handler [{:keys [params] :as request}] (def r* request) (let [{:keys [name surname]} params] (if (and name surname) {:status 200 :body (str "Hello, " name " " surname "!!!")} {:status 400 :body "Missing name and surname."}))) (defn add-person [{:keys [name dob]}] (if (and name dob) (do (wadim/create! wadim/conn name dob) {:status 201 :body "Created user."}) {:status 400 :body "User name or date of birth missing."})) (defn get-person [name] (let [dob (wadim/read wadim/conn name)] {:status 200 :headers {"content-type" "application/json"} :body (when dob (json/generate-string {:dob dob}))}))
null
https://raw.githubusercontent.com/inclojure-org/intermediate-clojure-workshop/3338a476aa815a587fa9e0b8b3804aa43492d15e/save-points/4/src/workshop_app/handlers/users.clj
clojure
(ns workshop-app.handlers.users (:require [workshop-app.db.in-mem :as wadim] [cheshire.core :as json])) (defn get-handler [{:keys [params] :as request}] (def r* request) (let [{:keys [name surname]} params] (if (and name surname) {:status 200 :body (str "Hello, " name " " surname "!!!")} {:status 400 :body "Missing name and surname."}))) (defn add-person [{:keys [name dob]}] (if (and name dob) (do (wadim/create! wadim/conn name dob) {:status 201 :body "Created user."}) {:status 400 :body "User name or date of birth missing."})) (defn get-person [name] (let [dob (wadim/read wadim/conn name)] {:status 200 :headers {"content-type" "application/json"} :body (when dob (json/generate-string {:dob dob}))}))
824fb2cf9e619acd4fa302476d29295fa8085542c3e9110402b4c8d2fb62920b
facebook/duckling
Tests.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Numeral.BN.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Numeral.BN.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "BN Tests" [ makeCorpusTest [Seal Numeral] corpus ]
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Numeral/BN/Tests.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.Numeral.BN.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Numeral.BN.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "BN Tests" [ makeCorpusTest [Seal Numeral] corpus ]
37703de4d70f5cb790d98303b4c8b53426f1722cb43c06429733ad84722b8c67
flussonic/sqlapi
sqlapi.erl
-module(sqlapi). -include("../include/sqlapi.hrl"). -include("myproto.hrl"). -export([start_server/1, stop_server/1, existing_port/1, load_config/1]). -export([password_hash/2, execute/3, terminate/2]). -export([create_temporary_table/2, drop_temporary_table/1]). -export([notify/2]). -export([apply_sql_filter/2, arith/3]). -export([mk_cond/1, filter/2, sqlite_flt/1, find_constraint/2]). -define(ERR_WRONG_PASS, {error, <<"Password incorrect!">>}). -define(ERR_WRONG_USER, {error, <<"No such user!">>}). -define(ERR_LOGIN_DISABLED, {error, <<"Login disabled">>}). -define(ERR_INFO(Code, Desc), #response{status=?STATUS_ERR, error_code=Code, info=Desc}). -define(field(Key,Dict), proplists:get_value(Key,Dict)). -define(COUNT_COL_NAME, ' COUNT '). load_config(#{handler := _} = Env0) -> Env = maps:merge(#{listener_name => sqlapi_ranch}, Env0), MysqlPort = maps:get(port, Env, undefined), OldMysql = existing_port(Env), if OldMysql == MysqlPort -> ok; OldMysql == undefined andalso MysqlPort =/= undefined -> start_server(Env); MysqlPort =/= undefined andalso MysqlPort =/= OldMysql andalso OldMysql =/= undefined -> stop_server(Env), start_server(Env); MysqlPort == undefined -> stop_server(Env) end. existing_port(#{listener_name := Ref, trivial := true}) -> case whereis(Ref) of undefined -> undefined; Pid -> case process_info(Pid, dictionary) of {dictionary, Dict} -> proplists:get_value('$my_listener_port',Dict); _ -> undefined end end; existing_port(#{listener_name := Ref}) -> existing_port(Ref); existing_port(Ref) when is_atom(Ref) -> Supervisors = supervisor:which_children(ranch_sup), case lists:keyfind({ranch_listener_sup,Ref}, 1, Supervisors) of {_, Pid, _, _} when is_pid(Pid) -> case process_info(Pid) of undefined -> undefined; _ -> ranch:get_port(Ref) end; _ -> undefined end. start_server(#{listener_name := Name, port := Port, handler := Handler, trivial := true} = Env) -> my_ranch_worker:start_trivial_server(Port, Name, Handler, Env); start_server(#{listener_name := Name, port := HostPort, handler := Handler} = Env) -> {Host,Port} = if is_number(HostPort) -> {[], HostPort}; is_binary(HostPort) -> [H,P] = binary:split(HostPort, <<":">>), {ok, Ip} = inet_parse:address(binary_to_list(H)), {[{ip,Ip}],binary_to_integer(P)} end, case gen_tcp:listen(Port, [binary, {reuseaddr, true}, {active, false}, {backlog, 4096}] ++ Host) of {ok, LSock} -> ranch:start_listener(Name, 5, ranch_tcp, [{socket, LSock},{max_connections,300}], my_ranch_worker, [Handler, Env]); {error, _}=Err -> Err end. stop_server(#{trivial := true, listener_name := Name}) -> case whereis(Name) of undefined -> ok; Pid -> erlang:exit(Pid, shutdown) end; stop_server(#{listener_name := Name}) -> stop_server(Name); stop_server(Name) when is_atom(Name) -> my_ranch_worker:stop_server(Name). notify(Event, Metadata) -> case application:get_env(sqlapi, error_handler) of {ok, {M,F}} -> M:F(Event, Metadata); undefined -> error_logger:error_msg("~p: ~p",[Event,Metadata]) end. password_hash(PlaintextPassword, Salt) -> my_protocol:hash_password(PlaintextPassword, Salt). create_temporary_table(TableName, TableSpec) -> Reply = sqlapi_ram_table:create_table(TableName, TableSpec), Reply. drop_temporary_table(TableName) -> Reply = sqlapi_ram_table:drop_table(TableName), Reply. %% filter, aggregate, order and limit rows after select query apply_sql_filter(Rows, #sql_filter{conditions = Conditions} = Filter) when is_list(Rows) -> Rows1 = lists:map(fun (R) when is_list(R) -> R; (R) -> maps:to_list(R) end, Rows), Rows2 = [[{to_a(C), V} || {C, V} <- Row] || Row <- Rows1], Cond = mk_cond(Conditions), Rows3 = lists:foldl(fun (_S, {error,Err}) -> {error,Err}; (S, Acc) -> case filter(Cond,S) of true -> [S|Acc]; false -> Acc; Err -> Err end end, [], Rows2), if not is_list(Rows3) -> {error, 1036, <<"such filtering is not supported yet">>}; true -> Rows4 = aggregate_by_sql(Rows3, Filter), Rows5 = order_by_sql(Rows4, Filter), Rows6 = limit_by_sql(Rows5, Filter), Rows7 = filter_columns_to_map(Rows6, Filter), Rows7 end; apply_sql_filter(Error, _Filter) when is_tuple(Error) -> Error. aggregate_by_sql({error,_,_} = Err, _) -> Err; aggregate_by_sql(Rows, #sql_filter{group = Group, columns = Columns}) -> Groupped = lists:foldl(fun(Row, Acc) -> Key = if Group == undefined -> undefined; true -> [proplists:lookup(C, Row) || C <- Group] end, RowsForKey = maps:get(Key, Acc, []), Acc#{Key => [Row| RowsForKey]} end, #{}, Rows), NeedCount = lists:member(?COUNT_COL_NAME, Columns), Rows1 = lists:flatmap(fun ({undefined, GroupRows}) when NeedCount -> add_count(GroupRows, length(GroupRows)); ({undefined, GroupRows}) -> GroupRows; ({_, GroupRows}) when NeedCount -> add_count([hd(GroupRows)], length(GroupRows)); ({_, GroupRows}) -> [hd(GroupRows)] end, maps:to_list(Groupped)), Rows1. add_count([Row| Rows], Count) -> Row1 = [{?COUNT_COL_NAME, Count}| Row], [Row1| add_count(Rows, Count)]; add_count([], _) -> []. order_by_sql(Rows, #sql_filter{order = Order, table_columns = TableColumns}) when length(Rows) > 0, Order /= undefined -> Keys = proplists:get_keys(TableColumns), KeyOrder = [{to_a(Key), Sort} || #order{key = Key, sort = Sort} <- Order, lists:member(to_a(Key), Keys)], if length(KeyOrder) /= length(Order) -> {error, 1036, <<"unknown column in order clause">>}; true -> Rows1 = lists:sort(fun(R1, R2) -> Pred = lists:foldl(fun ({Key, Sort}, undefined) -> Val1 = proplists:get_value(Key, R1, undefined), Val2 = proplists:get_value(Key, R2, undefined), case Sort of _ when Val1 == Val2 -> undefined; null first mysql default asc when Val2 == undefined -> false; asc -> Val1 < Val2; desc when Val1 == undefined -> false; % null last mysql default desc when Val2 == undefined -> true; desc -> Val1 > Val2 end; (_, Acc) -> Acc end, undefined, KeyOrder), Pred == undefined orelse Pred end, Rows), Rows1 end; order_by_sql(Rows, _Filter) -> Rows. %% limit/offset rows, convert to maps limit_by_sql(Rows, #sql_filter{limit = Limit, offset = Offset}) when is_list(Rows) andalso (Limit =/= undefined orelse Offset =/= undefined) -> case Limit of undefined -> Rows; Limit -> case Offset of undefined -> lists:sublist(Rows, 1, Limit); Offset when Offset < length(Rows) -> lists:sublist(Rows, Offset+1, Limit); _ -> [] end end; limit_by_sql(Rows, _) -> Rows. filter_columns_to_map(Rows, #sql_filter{columns = Columns}) when is_list(Rows) -> Rows1 = lists:map(fun (Row) when Columns == [] -> maps:from_list(Row); (Row) -> Row1 = [{C, proplists:get_value(C, Row)} || C <- Columns], maps:from_list(Row1) end, Rows), Rows1; filter_columns_to_map(Err, _) when is_tuple(Err) -> Err. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Erlang - side condition transformation % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% filter({nexo_or, Cond1, Cond2}, Item) -> filter(Cond1, Item) orelse filter(Cond2, Item); filter({nexo_and,Cond1, Cond2}, Item) -> filter(Cond1, Item) andalso filter(Cond2, Item); filter({eq, Arg1, Arg2}, Item) -> arith(eq, Arg1(Item), Arg2(Item)); filter({neq, Arg1, Arg2}, Item) -> not arith(eq, Arg1(Item), Arg2(Item)); filter({lt, Arg1, Arg2}, Item) -> arith(lt, Arg1(Item), Arg2(Item)); filter({gt, Arg1, Arg2}, Item) -> arith(gt, Arg1(Item), Arg2(Item)); filter({lte, Arg1, Arg2}, Item) -> arith(lte, Arg1(Item), Arg2(Item)); filter({gte, Arg1, Arg2}, Item) -> arith(gte, Arg1(Item), Arg2(Item)); filter({is, Arg1, Arg2}, Item) -> arith(is, Arg1(Item), Arg2(Item)); filter({is_not, Arg1, Arg2}, Item) -> not arith(is, Arg1(Item), Arg2(Item)); filter({not_in, Arg1, Arg2}, Item) -> not lists:member(Arg1(Item), Arg2(Item)); filter({in, Arg1, Arg2}, Item) -> V = Arg1(Item), lists:any(fun(Test) -> arith(eq, V, Test) end, Arg2(Item)); filter(no_cond,_) -> true; filter({like, Arg1, Arg2}, Item) -> like(Arg1(Item), Arg2); filter({not_like, Arg1, Arg2}, Item) -> not_like(Arg1(Item), Arg2); filter(_,_) -> {error, not_supported}. arith(Op, V1, V2) when Op == eq; Op == is -> IsFalse = fun(V) -> lists:member(V, [false, 0] ++ if Op == is -> [undefined, null]; true -> [] end) end, if V1 == true orelse V1 == 1 -> not IsFalse(V2); V1 == V2 -> true; true -> IsFalse(V1) andalso IsFalse(V2) end; arith(Op, V1, V2) when is_number(V1), is_number(V2) -> case Op of lt -> V1 < V2; gt -> V1 > V2; lte -> V1 =< V2; gte -> V1 >= V2 end; arith(_Op, _V1, _V2) -> false. like(Value, Pattern) when is_binary(Value), is_binary(Pattern) -> like0(unicode:characters_to_list(Pattern), unicode:characters_to_list(Value)); like(undefined, Pattern) -> like(<<>>, Pattern); like(_,_) -> {error, not_supported}. not_like(Value, Pattern) -> case like(Value, Pattern) of true -> false; false -> true; Error -> Error end. like0(P, V) when P == V -> true; %% check \_, \%, \\ like0([$\\, $_ | P], [$_| V]) -> like0(P, V); like0([$\\, $_ | _], _) -> false; like0([$\\, $% | P], [$%| V]) -> like0(P, V); like0([$\\, $% | _], _) -> false; like0([$\\, $\\ | P], [$\\| V]) -> like0(P, V); like0([$\\, $\\ | _], _) -> false; %% '_': skip symbol like0([$_| P], [_| V]) -> like0(P, V); %% '%': skip symbols, check further pattern like0([$%| []], _) -> true; like0([$%| P], V) -> case like0(P, V) of false when V == [] -> false; false -> like0([$%| P], tl(V)); % keep pattern and continue until end of the string true -> true end; like0([S| P], [S| V]) -> like0(P, V); like0(_, _) -> false. mk_cond(#condition{nexo=Op, op1=Arg1, op2=Arg2}) -> {Op, mk_cond(Arg1), mk_cond(Arg2)}; mk_cond(undefined) -> no_cond; mk_cond(#key{name = <<"false">>, table=undefined}) -> fun(_) -> false end; mk_cond(#key{name = <<"true">>, table=undefined}) -> fun(_) -> true end; mk_cond(#key{name=Field}) -> fun (Item) when is_list(Item) -> proplists:get_value(binary_to_existing_atom(Field,utf8), Item); (Item) when is_map(Item) -> maps:get(binary_to_existing_atom(Field,utf8), Item, undefined) end; mk_cond(#value{value=Value}) -> fun(_) -> Value end; mk_cond(#subquery{subquery=Set}) -> fun(_) -> Set end; mk_cond(Arg) -> Arg. unpack_filter_conditions({condition , nexo_and , Cond1 , Cond2 } ) - > % unpack_filter_conditions(Cond1) ++ unpack_filter_conditions(Cond2); % unpack_filter_conditions({condition, Op, {key, Key, _, _}, {value, _, Value}}) when Op = = eq ; Op = = gt ; Op = ; Op = = lt ; Op = = lte - > [ { { Key , Op},Value } ] . %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Extraction single condition from tree %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% find_constraint([], _) -> not_found; find_constraint([C|Rest], Cond) -> case find_constraint(C, Cond) of not_found -> find_constraint(Rest, Cond); Value -> Value end; %% single constraint search find_constraint({Op, Key}, {condition, Op, Value, #key{name=Key}}) -> Value; find_constraint({Op, Key}, {condition, Op, #key{name=Key}, Value}) -> Value; find_constraint(Part, {condition, _, Arg1, Arg2}) -> case find_constraint(Part, Arg1) of not_found -> find_constraint(Part, Arg2); Value -> Value end; find_constraint(_,_) -> not_found. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SQLite condition transformation % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sqlite_flt(undefined) -> {"",[]}; sqlite_flt(Cond) -> {C, Par} = sqlite_flt(Cond, []), {" WHERE " ++ C, Par}. sqlite_flt({key,Arg,_,_},Par) -> {binary_to_existing_atom(Arg,utf8), Par}; sqlite_flt({value,_,Arg},Par) -> {"?", [Arg|Par]}; sqlite_flt({subquery,_,Set},Par) -> {["(?", [",?"||_<-tl(Set)], ")"], [Set|Par]}; sqlite_flt({condition, Op, Arg1, Arg2}, Par) -> %% reverse argument traverse order to maintain resulting parameter order {A2, P2} = sqlite_flt(Arg2,Par), {A1, P1} = sqlite_flt(Arg1,P2), Query = lists:flatten(io_lib:format("(~s ~s ~s)", [A1,sqlite_op(Op),A2])), {Query,P1}. sqlite_op(nexo_and) -> "and"; sqlite_op(nexo_or) -> "or"; sqlite_op(eq) -> "="; sqlite_op(lt) -> "<"; sqlite_op(gt) -> ">"; sqlite_op(lte) -> "<="; sqlite_op(gte) -> ">="; sqlite_op(in) -> "in". $ $ \ $ $ \ $ $ | \__| $ $ | $ $ $ $ $ $ \ $ $ $ $ $ $ \ $ $ \ $ $ $ $ $ $ $ \ $ $ | $ $ _ _ $ $ \ $ $ _ _ $ $ \ $ $ |$$ _ _ _ _ _ | $ $ | $ $ / $ $ |$$ / $ $ |$$ |$$ / $ $ | $ $ | $ $ |$$ | $ $ |$$ |$$ | $ $ $ $ $ $ $ $ \\$$$$$$ |\$$$$$$$ |$$ |\$$$$$$$\ % \________|\______/ \____$$ |\__| \_______| % $$\ $$ | % \$$$$$$ | % \______/ execute(#request{text = Text} = Request, Handler, State) -> try execute0(Request, Handler, State) of {reply, #response{}, _} = Reply -> Reply catch _C:E -> ST = erlang:get_stacktrace(), notify(sql_handler_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi}, {query, Text}, {error, E}, {stacktrace, iolist_to_binary(io_lib:format("~p",[ST]))}]), {reply, #response{status=?STATUS_ERR, error_code=500, info= <<"Internal server error">>}, State} end. execute0(#request{info = #select{tables = [#table{name = Table}]} = Select}, Handler, State) when is_binary(Table) -> case Handler:columns(Table, State) of {error, no_table} -> {reply, #response{status=?STATUS_ERR, error_code=1146, info = <<"Table '",Table/binary,"' doesn't exist">>}, State}; TableColumns when is_list(TableColumns) -> Filter = build_sql_filter(Select, TableColumns), Columns = Filter#sql_filter.columns, case Handler:select(Table, Filter, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; Rows when is_list(Rows) -> ResponseColumns = [case lists:keyfind(Name,1,TableColumns) of _ when Name == ?COUNT_COL_NAME -> {<<"COUNT">>, integer}; false -> {Name, string}; Col -> Col end || Name <- Columns], Response = { response_columns(ResponseColumns), [response_row(Row, Columns) || Row <- Rows]}, Reply = #response{status=?STATUS_OK, info = Response}, {reply, Reply, State} end end; execute0(#request{info = #insert{table = #table{name = Table}, values = ValuesSpec}}, Handler, State) -> Values = lists:map(fun(Row) -> maps:from_list(lists:map(fun (#set{key = K, value = #value{value = V}}) -> {K,V}; (#set{key = K, value = #key{name = <<"true">>}}) -> {K,true}; (#set{key = K, value = #key{name = <<"TRUE">>}}) -> {K,true}; (#set{key = K, value = #key{name = <<"false">>}}) -> {K,false}; (#set{key = K, value = #key{name = <<"FALSE">>}}) -> {K,false} end, Row)) end, ValuesSpec), case Handler:insert(Table, Values, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info= #update{table = #table{name=Table}, set=ValuesSpec, conditions=Conditions}}, Handler, State) -> Values = maps:from_list([{K,V} || #set{key = K, value = #value{value = V}} <- ValuesSpec]), case Handler:update(Table, Values, Conditions, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info = #delete{table = #table{name = Table}, conditions = Conditions}}, Handler, State) -> case Handler:delete(Table, Conditions, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info = #select{params = [#function{name = Name, params = Params0}]}}, Handler, State) -> Params = [V || #value{value=V} <- Params0], case Handler:fncall(Name, Params, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, Columns, Rows} -> Columns1 = [C || {C,_} <- Columns], Response = {response_columns(Columns), [response_row(Row, Columns1) || Row <- Rows]}, % Response = {response_columns(Columns), Rows}, {reply, #response{status=?STATUS_OK, info = Response}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State}; ok -> {reply, #response{status=?STATUS_OK}, State} end; execute0(#request{text = Text, info = {error,{_,sql92_parser,Desc}}}, _Handler, State) -> Description = iolist_to_binary(["Invalid query: ",Desc]), notify(sql_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi},{query, Text}, {error, bad_query}]), {reply, #response{status=?STATUS_ERR, error_code=1065, info= Description}, State}; execute0(#request{text = Text}, _Handler, State) -> notify(sql_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi},{query, Text}, {error, unknown_query}]), {reply, #response{status=?STATUS_ERR, error_code=500, info= <<"Internal server error">>}, State}. build_sql_filter(#select{params = Params, conditions = Conditions0, order = Order, group = Group0, limit = Limit, offset = Offset}, TableColumns) when is_list(TableColumns) -> Conditions = normalize_condition_types(TableColumns, Conditions0), Columns = lists:flatmap(fun (#all{}) -> [N || {N,_} <- TableColumns]; (#key{name = Name}) -> [binary_to_existing_atom(Name,latin1)]; (#function{name = N}) when N == <<"COUNT">> orelse N == <<"count">> -> [?COUNT_COL_NAME]; (_) -> [] % other aggregate, etc end, Params), Group = if Group0 == undefined -> undefined; true -> [binary_to_existing_atom(C,latin1) || C <- Group0] end, #sql_filter{ conditions = Conditions, columns = Columns, table_columns = TableColumns, order = Order, group = Group, limit = Limit, offset = Offset}. normalize_condition_types(Columns, #condition{nexo = OrAnd, op1 = Op1, op2 = Op2}) when OrAnd == nexo_and; OrAnd == nexo_or -> #condition{nexo = OrAnd, op1 = normalize_condition_types(Columns, Op1), op2 = normalize_condition_types(Columns, Op2) }; normalize_condition_types(Columns, #condition{nexo = C, op1 = #key{name = Name} = K, op2 = #key{name = Bool}} = Cond) when Bool == <<"true">>; Bool == <<"false">>; Bool == <<"TRUE">>; Bool == <<"FALSE">> -> Column = binary_to_existing_atom(Name,latin1), case proplists:get_value(Column, Columns) of boolean when Bool == <<"true">>; Bool == <<"TRUE">> -> #condition{nexo = C, op1 = K, op2 = #value{value = true}}; boolean when Bool == <<"FALSE">>; Bool == <<"FALSE">> -> #condition{nexo = C, op1 = K, op2 = #value{value = false}}; _ -> Cond end; normalize_condition_types(Columns, #condition{nexo = C, op1 = #key{name = Name} = K, op2 = #value{value = V}} = Cond) when V == 1; V == 0-> Column = binary_to_existing_atom(Name,latin1), case proplists:get_value(Column, Columns) of boolean when V == 1 -> #condition{nexo = C, op1 = K, op2 = #value{value = true}}; boolean when V == 0 -> #condition{nexo = C, op1 = K, op2 = #value{value = false}}; _ -> Cond end; normalize_condition_types(_Columns, Cond) -> Cond. response_row(Row, Columns) when is_map(Row) -> [maps:get(Column, Row, undefined) || Column <- Columns]; response_row(Row, Columns) when is_list(Row) -> [proplists:get_value(Column, Row) || Column <- Columns]. response_columns(Columns) -> lists:map(fun ({Name,string}) -> #column{name = to_b(Name), type = ?TYPE_VAR_STRING, length = 20, org_name = to_b(Name)}; ({Name,boolean}) -> #column{name = to_b(Name), type = ?TYPE_TINY, length = 1, org_name = to_b(Name)}; ({Name,integer}) -> #column{name = to_b(Name), type = ?TYPE_LONGLONG, length = 20, org_name = to_b(Name)} end, Columns). to_b(Atom) when is_atom(Atom) -> atom_to_binary(Atom,latin1); to_b(Bin) when is_binary(Bin) -> Bin. to_a(Atom) when is_binary(Atom) -> binary_to_atom(Atom,latin1); to_a(Atom) when is_atom(Atom) -> Atom. terminate(_Reason,_) -> ok.
null
https://raw.githubusercontent.com/flussonic/sqlapi/a8f51e3cb5827366a6224585ee52024720b9c3ef/src/sqlapi.erl
erlang
filter, aggregate, order and limit rows after select query null last mysql default limit/offset rows, convert to maps % % check \_, \%, \\ | P], [$%| V]) -> like0(P, V); | _], _) -> false; '_': skip symbol '%': skip symbols, check further pattern | []], _) -> true; | P], V) -> | P], tl(V)); % keep pattern and continue until end of the string unpack_filter_conditions(Cond1) ++ unpack_filter_conditions(Cond2); unpack_filter_conditions({condition, Op, {key, Key, _, _}, {value, _, Value}}) when Extraction single condition from tree %%% single constraint search % % reverse argument traverse order to maintain resulting parameter order \________|\______/ \____$$ |\__| \_______| $$\ $$ | \$$$$$$ | \______/ Response = {response_columns(Columns), Rows}, other aggregate, etc
-module(sqlapi). -include("../include/sqlapi.hrl"). -include("myproto.hrl"). -export([start_server/1, stop_server/1, existing_port/1, load_config/1]). -export([password_hash/2, execute/3, terminate/2]). -export([create_temporary_table/2, drop_temporary_table/1]). -export([notify/2]). -export([apply_sql_filter/2, arith/3]). -export([mk_cond/1, filter/2, sqlite_flt/1, find_constraint/2]). -define(ERR_WRONG_PASS, {error, <<"Password incorrect!">>}). -define(ERR_WRONG_USER, {error, <<"No such user!">>}). -define(ERR_LOGIN_DISABLED, {error, <<"Login disabled">>}). -define(ERR_INFO(Code, Desc), #response{status=?STATUS_ERR, error_code=Code, info=Desc}). -define(field(Key,Dict), proplists:get_value(Key,Dict)). -define(COUNT_COL_NAME, ' COUNT '). load_config(#{handler := _} = Env0) -> Env = maps:merge(#{listener_name => sqlapi_ranch}, Env0), MysqlPort = maps:get(port, Env, undefined), OldMysql = existing_port(Env), if OldMysql == MysqlPort -> ok; OldMysql == undefined andalso MysqlPort =/= undefined -> start_server(Env); MysqlPort =/= undefined andalso MysqlPort =/= OldMysql andalso OldMysql =/= undefined -> stop_server(Env), start_server(Env); MysqlPort == undefined -> stop_server(Env) end. existing_port(#{listener_name := Ref, trivial := true}) -> case whereis(Ref) of undefined -> undefined; Pid -> case process_info(Pid, dictionary) of {dictionary, Dict} -> proplists:get_value('$my_listener_port',Dict); _ -> undefined end end; existing_port(#{listener_name := Ref}) -> existing_port(Ref); existing_port(Ref) when is_atom(Ref) -> Supervisors = supervisor:which_children(ranch_sup), case lists:keyfind({ranch_listener_sup,Ref}, 1, Supervisors) of {_, Pid, _, _} when is_pid(Pid) -> case process_info(Pid) of undefined -> undefined; _ -> ranch:get_port(Ref) end; _ -> undefined end. start_server(#{listener_name := Name, port := Port, handler := Handler, trivial := true} = Env) -> my_ranch_worker:start_trivial_server(Port, Name, Handler, Env); start_server(#{listener_name := Name, port := HostPort, handler := Handler} = Env) -> {Host,Port} = if is_number(HostPort) -> {[], HostPort}; is_binary(HostPort) -> [H,P] = binary:split(HostPort, <<":">>), {ok, Ip} = inet_parse:address(binary_to_list(H)), {[{ip,Ip}],binary_to_integer(P)} end, case gen_tcp:listen(Port, [binary, {reuseaddr, true}, {active, false}, {backlog, 4096}] ++ Host) of {ok, LSock} -> ranch:start_listener(Name, 5, ranch_tcp, [{socket, LSock},{max_connections,300}], my_ranch_worker, [Handler, Env]); {error, _}=Err -> Err end. stop_server(#{trivial := true, listener_name := Name}) -> case whereis(Name) of undefined -> ok; Pid -> erlang:exit(Pid, shutdown) end; stop_server(#{listener_name := Name}) -> stop_server(Name); stop_server(Name) when is_atom(Name) -> my_ranch_worker:stop_server(Name). notify(Event, Metadata) -> case application:get_env(sqlapi, error_handler) of {ok, {M,F}} -> M:F(Event, Metadata); undefined -> error_logger:error_msg("~p: ~p",[Event,Metadata]) end. password_hash(PlaintextPassword, Salt) -> my_protocol:hash_password(PlaintextPassword, Salt). create_temporary_table(TableName, TableSpec) -> Reply = sqlapi_ram_table:create_table(TableName, TableSpec), Reply. drop_temporary_table(TableName) -> Reply = sqlapi_ram_table:drop_table(TableName), Reply. apply_sql_filter(Rows, #sql_filter{conditions = Conditions} = Filter) when is_list(Rows) -> Rows1 = lists:map(fun (R) when is_list(R) -> R; (R) -> maps:to_list(R) end, Rows), Rows2 = [[{to_a(C), V} || {C, V} <- Row] || Row <- Rows1], Cond = mk_cond(Conditions), Rows3 = lists:foldl(fun (_S, {error,Err}) -> {error,Err}; (S, Acc) -> case filter(Cond,S) of true -> [S|Acc]; false -> Acc; Err -> Err end end, [], Rows2), if not is_list(Rows3) -> {error, 1036, <<"such filtering is not supported yet">>}; true -> Rows4 = aggregate_by_sql(Rows3, Filter), Rows5 = order_by_sql(Rows4, Filter), Rows6 = limit_by_sql(Rows5, Filter), Rows7 = filter_columns_to_map(Rows6, Filter), Rows7 end; apply_sql_filter(Error, _Filter) when is_tuple(Error) -> Error. aggregate_by_sql({error,_,_} = Err, _) -> Err; aggregate_by_sql(Rows, #sql_filter{group = Group, columns = Columns}) -> Groupped = lists:foldl(fun(Row, Acc) -> Key = if Group == undefined -> undefined; true -> [proplists:lookup(C, Row) || C <- Group] end, RowsForKey = maps:get(Key, Acc, []), Acc#{Key => [Row| RowsForKey]} end, #{}, Rows), NeedCount = lists:member(?COUNT_COL_NAME, Columns), Rows1 = lists:flatmap(fun ({undefined, GroupRows}) when NeedCount -> add_count(GroupRows, length(GroupRows)); ({undefined, GroupRows}) -> GroupRows; ({_, GroupRows}) when NeedCount -> add_count([hd(GroupRows)], length(GroupRows)); ({_, GroupRows}) -> [hd(GroupRows)] end, maps:to_list(Groupped)), Rows1. add_count([Row| Rows], Count) -> Row1 = [{?COUNT_COL_NAME, Count}| Row], [Row1| add_count(Rows, Count)]; add_count([], _) -> []. order_by_sql(Rows, #sql_filter{order = Order, table_columns = TableColumns}) when length(Rows) > 0, Order /= undefined -> Keys = proplists:get_keys(TableColumns), KeyOrder = [{to_a(Key), Sort} || #order{key = Key, sort = Sort} <- Order, lists:member(to_a(Key), Keys)], if length(KeyOrder) /= length(Order) -> {error, 1036, <<"unknown column in order clause">>}; true -> Rows1 = lists:sort(fun(R1, R2) -> Pred = lists:foldl(fun ({Key, Sort}, undefined) -> Val1 = proplists:get_value(Key, R1, undefined), Val2 = proplists:get_value(Key, R2, undefined), case Sort of _ when Val1 == Val2 -> undefined; null first mysql default asc when Val2 == undefined -> false; asc -> Val1 < Val2; desc when Val2 == undefined -> true; desc -> Val1 > Val2 end; (_, Acc) -> Acc end, undefined, KeyOrder), Pred == undefined orelse Pred end, Rows), Rows1 end; order_by_sql(Rows, _Filter) -> Rows. limit_by_sql(Rows, #sql_filter{limit = Limit, offset = Offset}) when is_list(Rows) andalso (Limit =/= undefined orelse Offset =/= undefined) -> case Limit of undefined -> Rows; Limit -> case Offset of undefined -> lists:sublist(Rows, 1, Limit); Offset when Offset < length(Rows) -> lists:sublist(Rows, Offset+1, Limit); _ -> [] end end; limit_by_sql(Rows, _) -> Rows. filter_columns_to_map(Rows, #sql_filter{columns = Columns}) when is_list(Rows) -> Rows1 = lists:map(fun (Row) when Columns == [] -> maps:from_list(Row); (Row) -> Row1 = [{C, proplists:get_value(C, Row)} || C <- Columns], maps:from_list(Row1) end, Rows), Rows1; filter_columns_to_map(Err, _) when is_tuple(Err) -> Err. filter({nexo_or, Cond1, Cond2}, Item) -> filter(Cond1, Item) orelse filter(Cond2, Item); filter({nexo_and,Cond1, Cond2}, Item) -> filter(Cond1, Item) andalso filter(Cond2, Item); filter({eq, Arg1, Arg2}, Item) -> arith(eq, Arg1(Item), Arg2(Item)); filter({neq, Arg1, Arg2}, Item) -> not arith(eq, Arg1(Item), Arg2(Item)); filter({lt, Arg1, Arg2}, Item) -> arith(lt, Arg1(Item), Arg2(Item)); filter({gt, Arg1, Arg2}, Item) -> arith(gt, Arg1(Item), Arg2(Item)); filter({lte, Arg1, Arg2}, Item) -> arith(lte, Arg1(Item), Arg2(Item)); filter({gte, Arg1, Arg2}, Item) -> arith(gte, Arg1(Item), Arg2(Item)); filter({is, Arg1, Arg2}, Item) -> arith(is, Arg1(Item), Arg2(Item)); filter({is_not, Arg1, Arg2}, Item) -> not arith(is, Arg1(Item), Arg2(Item)); filter({not_in, Arg1, Arg2}, Item) -> not lists:member(Arg1(Item), Arg2(Item)); filter({in, Arg1, Arg2}, Item) -> V = Arg1(Item), lists:any(fun(Test) -> arith(eq, V, Test) end, Arg2(Item)); filter(no_cond,_) -> true; filter({like, Arg1, Arg2}, Item) -> like(Arg1(Item), Arg2); filter({not_like, Arg1, Arg2}, Item) -> not_like(Arg1(Item), Arg2); filter(_,_) -> {error, not_supported}. arith(Op, V1, V2) when Op == eq; Op == is -> IsFalse = fun(V) -> lists:member(V, [false, 0] ++ if Op == is -> [undefined, null]; true -> [] end) end, if V1 == true orelse V1 == 1 -> not IsFalse(V2); V1 == V2 -> true; true -> IsFalse(V1) andalso IsFalse(V2) end; arith(Op, V1, V2) when is_number(V1), is_number(V2) -> case Op of lt -> V1 < V2; gt -> V1 > V2; lte -> V1 =< V2; gte -> V1 >= V2 end; arith(_Op, _V1, _V2) -> false. like(Value, Pattern) when is_binary(Value), is_binary(Pattern) -> like0(unicode:characters_to_list(Pattern), unicode:characters_to_list(Value)); like(undefined, Pattern) -> like(<<>>, Pattern); like(_,_) -> {error, not_supported}. not_like(Value, Pattern) -> case like(Value, Pattern) of true -> false; false -> true; Error -> Error end. like0(P, V) when P == V -> true; like0([$\\, $_ | P], [$_| V]) -> like0(P, V); like0([$\\, $_ | _], _) -> false; like0([$\\, $\\ | P], [$\\| V]) -> like0(P, V); like0([$\\, $\\ | _], _) -> false; like0([$_| P], [_| V]) -> like0(P, V); case like0(P, V) of false when V == [] -> false; true -> true end; like0([S| P], [S| V]) -> like0(P, V); like0(_, _) -> false. mk_cond(#condition{nexo=Op, op1=Arg1, op2=Arg2}) -> {Op, mk_cond(Arg1), mk_cond(Arg2)}; mk_cond(undefined) -> no_cond; mk_cond(#key{name = <<"false">>, table=undefined}) -> fun(_) -> false end; mk_cond(#key{name = <<"true">>, table=undefined}) -> fun(_) -> true end; mk_cond(#key{name=Field}) -> fun (Item) when is_list(Item) -> proplists:get_value(binary_to_existing_atom(Field,utf8), Item); (Item) when is_map(Item) -> maps:get(binary_to_existing_atom(Field,utf8), Item, undefined) end; mk_cond(#value{value=Value}) -> fun(_) -> Value end; mk_cond(#subquery{subquery=Set}) -> fun(_) -> Set end; mk_cond(Arg) -> Arg. unpack_filter_conditions({condition , nexo_and , Cond1 , Cond2 } ) - > Op = = eq ; Op = = gt ; Op = ; Op = = lt ; Op = = lte - > [ { { Key , Op},Value } ] . find_constraint([], _) -> not_found; find_constraint([C|Rest], Cond) -> case find_constraint(C, Cond) of not_found -> find_constraint(Rest, Cond); Value -> Value end; find_constraint({Op, Key}, {condition, Op, Value, #key{name=Key}}) -> Value; find_constraint({Op, Key}, {condition, Op, #key{name=Key}, Value}) -> Value; find_constraint(Part, {condition, _, Arg1, Arg2}) -> case find_constraint(Part, Arg1) of not_found -> find_constraint(Part, Arg2); Value -> Value end; find_constraint(_,_) -> not_found. sqlite_flt(undefined) -> {"",[]}; sqlite_flt(Cond) -> {C, Par} = sqlite_flt(Cond, []), {" WHERE " ++ C, Par}. sqlite_flt({key,Arg,_,_},Par) -> {binary_to_existing_atom(Arg,utf8), Par}; sqlite_flt({value,_,Arg},Par) -> {"?", [Arg|Par]}; sqlite_flt({subquery,_,Set},Par) -> {["(?", [",?"||_<-tl(Set)], ")"], [Set|Par]}; sqlite_flt({condition, Op, Arg1, Arg2}, Par) -> {A2, P2} = sqlite_flt(Arg2,Par), {A1, P1} = sqlite_flt(Arg1,P2), Query = lists:flatten(io_lib:format("(~s ~s ~s)", [A1,sqlite_op(Op),A2])), {Query,P1}. sqlite_op(nexo_and) -> "and"; sqlite_op(nexo_or) -> "or"; sqlite_op(eq) -> "="; sqlite_op(lt) -> "<"; sqlite_op(gt) -> ">"; sqlite_op(lte) -> "<="; sqlite_op(gte) -> ">="; sqlite_op(in) -> "in". $ $ \ $ $ \ $ $ | \__| $ $ | $ $ $ $ $ $ \ $ $ $ $ $ $ \ $ $ \ $ $ $ $ $ $ $ \ $ $ | $ $ _ _ $ $ \ $ $ _ _ $ $ \ $ $ |$$ _ _ _ _ _ | $ $ | $ $ / $ $ |$$ / $ $ |$$ |$$ / $ $ | $ $ | $ $ |$$ | $ $ |$$ |$$ | $ $ $ $ $ $ $ $ \\$$$$$$ |\$$$$$$$ |$$ |\$$$$$$$\ execute(#request{text = Text} = Request, Handler, State) -> try execute0(Request, Handler, State) of {reply, #response{}, _} = Reply -> Reply catch _C:E -> ST = erlang:get_stacktrace(), notify(sql_handler_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi}, {query, Text}, {error, E}, {stacktrace, iolist_to_binary(io_lib:format("~p",[ST]))}]), {reply, #response{status=?STATUS_ERR, error_code=500, info= <<"Internal server error">>}, State} end. execute0(#request{info = #select{tables = [#table{name = Table}]} = Select}, Handler, State) when is_binary(Table) -> case Handler:columns(Table, State) of {error, no_table} -> {reply, #response{status=?STATUS_ERR, error_code=1146, info = <<"Table '",Table/binary,"' doesn't exist">>}, State}; TableColumns when is_list(TableColumns) -> Filter = build_sql_filter(Select, TableColumns), Columns = Filter#sql_filter.columns, case Handler:select(Table, Filter, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; Rows when is_list(Rows) -> ResponseColumns = [case lists:keyfind(Name,1,TableColumns) of _ when Name == ?COUNT_COL_NAME -> {<<"COUNT">>, integer}; false -> {Name, string}; Col -> Col end || Name <- Columns], Response = { response_columns(ResponseColumns), [response_row(Row, Columns) || Row <- Rows]}, Reply = #response{status=?STATUS_OK, info = Response}, {reply, Reply, State} end end; execute0(#request{info = #insert{table = #table{name = Table}, values = ValuesSpec}}, Handler, State) -> Values = lists:map(fun(Row) -> maps:from_list(lists:map(fun (#set{key = K, value = #value{value = V}}) -> {K,V}; (#set{key = K, value = #key{name = <<"true">>}}) -> {K,true}; (#set{key = K, value = #key{name = <<"TRUE">>}}) -> {K,true}; (#set{key = K, value = #key{name = <<"false">>}}) -> {K,false}; (#set{key = K, value = #key{name = <<"FALSE">>}}) -> {K,false} end, Row)) end, ValuesSpec), case Handler:insert(Table, Values, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info= #update{table = #table{name=Table}, set=ValuesSpec, conditions=Conditions}}, Handler, State) -> Values = maps:from_list([{K,V} || #set{key = K, value = #value{value = V}} <- ValuesSpec]), case Handler:update(Table, Values, Conditions, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info = #delete{table = #table{name = Table}, conditions = Conditions}}, Handler, State) -> case Handler:delete(Table, Conditions, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State} end; execute0(#request{info = #select{params = [#function{name = Name, params = Params0}]}}, Handler, State) -> Params = [V || #value{value=V} <- Params0], case Handler:fncall(Name, Params, State) of {error, Code, Desc} -> {reply, #response{status=?STATUS_ERR, error_code=Code, info=Desc}, State}; {ok, Columns, Rows} -> Columns1 = [C || {C,_} <- Columns], Response = {response_columns(Columns), [response_row(Row, Columns1) || Row <- Rows]}, {reply, #response{status=?STATUS_OK, info = Response}, State}; {ok, #{status := Status} = Reply} -> StatusCode = case Status of ok -> ?STATUS_OK end, AffectedRows = maps:get(affected_rows, Reply, 1), Id = maps:get(id, Reply, 0), Info = maps:get(info, Reply, <<>>), Warnings = maps:get(warnings, Reply, 0), {reply, #response{status=StatusCode, affected_rows = AffectedRows, last_insert_id = Id, status_flags = 0, warnings = Warnings, info = Info}, State}; {ok, Id} when is_integer(Id) -> {reply, #response{status=?STATUS_OK, affected_rows = 1, last_insert_id = Id, status_flags = 0, warnings = 0, info = <<>>}, State}; ok -> {reply, #response{status=?STATUS_OK}, State} end; execute0(#request{text = Text, info = {error,{_,sql92_parser,Desc}}}, _Handler, State) -> Description = iolist_to_binary(["Invalid query: ",Desc]), notify(sql_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi},{query, Text}, {error, bad_query}]), {reply, #response{status=?STATUS_ERR, error_code=1065, info= Description}, State}; execute0(#request{text = Text}, _Handler, State) -> notify(sql_error,[{module,?MODULE},{line,?LINE},{pid,self()},{application,sqlapi},{query, Text}, {error, unknown_query}]), {reply, #response{status=?STATUS_ERR, error_code=500, info= <<"Internal server error">>}, State}. build_sql_filter(#select{params = Params, conditions = Conditions0, order = Order, group = Group0, limit = Limit, offset = Offset}, TableColumns) when is_list(TableColumns) -> Conditions = normalize_condition_types(TableColumns, Conditions0), Columns = lists:flatmap(fun (#all{}) -> [N || {N,_} <- TableColumns]; (#key{name = Name}) -> [binary_to_existing_atom(Name,latin1)]; (#function{name = N}) when N == <<"COUNT">> orelse N == <<"count">> -> [?COUNT_COL_NAME]; end, Params), Group = if Group0 == undefined -> undefined; true -> [binary_to_existing_atom(C,latin1) || C <- Group0] end, #sql_filter{ conditions = Conditions, columns = Columns, table_columns = TableColumns, order = Order, group = Group, limit = Limit, offset = Offset}. normalize_condition_types(Columns, #condition{nexo = OrAnd, op1 = Op1, op2 = Op2}) when OrAnd == nexo_and; OrAnd == nexo_or -> #condition{nexo = OrAnd, op1 = normalize_condition_types(Columns, Op1), op2 = normalize_condition_types(Columns, Op2) }; normalize_condition_types(Columns, #condition{nexo = C, op1 = #key{name = Name} = K, op2 = #key{name = Bool}} = Cond) when Bool == <<"true">>; Bool == <<"false">>; Bool == <<"TRUE">>; Bool == <<"FALSE">> -> Column = binary_to_existing_atom(Name,latin1), case proplists:get_value(Column, Columns) of boolean when Bool == <<"true">>; Bool == <<"TRUE">> -> #condition{nexo = C, op1 = K, op2 = #value{value = true}}; boolean when Bool == <<"FALSE">>; Bool == <<"FALSE">> -> #condition{nexo = C, op1 = K, op2 = #value{value = false}}; _ -> Cond end; normalize_condition_types(Columns, #condition{nexo = C, op1 = #key{name = Name} = K, op2 = #value{value = V}} = Cond) when V == 1; V == 0-> Column = binary_to_existing_atom(Name,latin1), case proplists:get_value(Column, Columns) of boolean when V == 1 -> #condition{nexo = C, op1 = K, op2 = #value{value = true}}; boolean when V == 0 -> #condition{nexo = C, op1 = K, op2 = #value{value = false}}; _ -> Cond end; normalize_condition_types(_Columns, Cond) -> Cond. response_row(Row, Columns) when is_map(Row) -> [maps:get(Column, Row, undefined) || Column <- Columns]; response_row(Row, Columns) when is_list(Row) -> [proplists:get_value(Column, Row) || Column <- Columns]. response_columns(Columns) -> lists:map(fun ({Name,string}) -> #column{name = to_b(Name), type = ?TYPE_VAR_STRING, length = 20, org_name = to_b(Name)}; ({Name,boolean}) -> #column{name = to_b(Name), type = ?TYPE_TINY, length = 1, org_name = to_b(Name)}; ({Name,integer}) -> #column{name = to_b(Name), type = ?TYPE_LONGLONG, length = 20, org_name = to_b(Name)} end, Columns). to_b(Atom) when is_atom(Atom) -> atom_to_binary(Atom,latin1); to_b(Bin) when is_binary(Bin) -> Bin. to_a(Atom) when is_binary(Atom) -> binary_to_atom(Atom,latin1); to_a(Atom) when is_atom(Atom) -> Atom. terminate(_Reason,_) -> ok.
a8056ff7b7ad0c0c6aa9ec797032cbdf00f8285d087f7e8921b1aa756a1b6862
TrustInSoft/tis-kernel
logic_preprocess.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) ( Institut National de Recherche en Informatique et en (* Automatique) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** adds another pre-processing step in order to expand macros in annotations. *) * [ file suffix file ] takes the file to preprocess , and the pre - processing directive , and returns the name of the file containing the completely pre - processed source . suffix will be appended to the name of intermediate files generated for pre - processing annotations ( gcc pre - processing differs between .c and .cxx files ) @raises Sys_error if the file can not be opened . @modifies Oxygen-20120901 : added suffix argument and the pre-processing directive, and returns the name of the file containing the completely pre-processed source. suffix will be appended to the name of intermediate files generated for pre-processing annotations (gcc pre-processing differs between .c and .cxx files) @raises Sys_error if the file cannot be opened. @modifies Oxygen-20120901: added suffix argument *) val file: string -> (string -> string -> string) -> string -> string
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_internals/parsing/logic_preprocess.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) Automatique) 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. ************************************************************************ * adds another pre-processing step in order to expand macros in annotations.
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies ( Institut National de Recherche en Informatique et en Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * [ file suffix file ] takes the file to preprocess , and the pre - processing directive , and returns the name of the file containing the completely pre - processed source . suffix will be appended to the name of intermediate files generated for pre - processing annotations ( gcc pre - processing differs between .c and .cxx files ) @raises Sys_error if the file can not be opened . @modifies Oxygen-20120901 : added suffix argument and the pre-processing directive, and returns the name of the file containing the completely pre-processed source. suffix will be appended to the name of intermediate files generated for pre-processing annotations (gcc pre-processing differs between .c and .cxx files) @raises Sys_error if the file cannot be opened. @modifies Oxygen-20120901: added suffix argument *) val file: string -> (string -> string -> string) -> string -> string
5c407ede1ddf4dbabcd8ce5147913ee6859d2e2a4d4de8096c2a9f76c2381fb7
justinethier/cyclone
convert-doc-index.scm
;;;; Cyclone Scheme ;;;; ;;;; Copyright ( c ) 2014 - 2016 , ;;;; All rights reserved. ;;;; ;;;; A simple program to format links for the API index page. ;;;; (import (scheme base) (scheme write) (scheme cyclone util)) ;; TODO: move this somewhere useful (define (index-of lst x) (define (find lst idx) (cond ((null? lst) #f) ((eq? (car lst) x) idx) (else (find (cdr lst) (+ idx 1))))) (find lst 0)) ;; goal is: ;; [`load`](api/scheme/load.md#load) ;(define line "docs/api/scheme/base.md:- [`denominator`](#denominator)") ;(define line "docs/api/scheme/process-context.md:- [`get-environment-variables`](#get-environment-variables)") ;(define line "docs/api/scheme/char.md:- [`string-ci>=?`](#string-ci-3)") (define (convert-line line) (let* ((lis (string->list line)) (s-file 5) (e-file (index-of lis #\:)) (file (substring line s-file e-file)) (s-fnc (+ 1 (index-of lis #\`))) (e-fnc (+ s-fnc (index-of (string->list (substring line (+ 0 s-fnc) (string-length line))) #\`))) (fnc (substring line s-fnc e-fnc)) (s-link (index-of lis #\#)) (e-link (string-length line)) (link (substring line s-link e-link)) ) (string-append (string (string-ref fnc 0)) "[`" fnc "`](" file "" link ""))) ;(display (convert-line line)) (define (loop) (let ((line (read-line))) (when (not (eof-object? line)) (with-handler (lambda (obj) (display `(Error processing line ,line details ,obj) (current-error-port))) (display (convert-line line)) (newline)) #;(call/cc (lambda (k) (with-exception-handler (lambda (obj) (display `(Error processing line ,line details ,obj)) (k #t)) (lambda () (display (convert-line line)) (newline))))) (loop)))) (loop)
null
https://raw.githubusercontent.com/justinethier/cyclone/cf66cf1057fcd687cc42d4d7dcaeeef00cba089b/scripts/convert-doc-index.scm
scheme
Cyclone Scheme All rights reserved. A simple program to format links for the API index page. TODO: move this somewhere useful goal is: [`load`](api/scheme/load.md#load) (define line "docs/api/scheme/base.md:- [`denominator`](#denominator)") (define line "docs/api/scheme/process-context.md:- [`get-environment-variables`](#get-environment-variables)") (define line "docs/api/scheme/char.md:- [`string-ci>=?`](#string-ci-3)") (display (convert-line line)) (call/cc
Copyright ( c ) 2014 - 2016 , (import (scheme base) (scheme write) (scheme cyclone util)) (define (index-of lst x) (define (find lst idx) (cond ((null? lst) #f) ((eq? (car lst) x) idx) (else (find (cdr lst) (+ idx 1))))) (find lst 0)) (define (convert-line line) (let* ((lis (string->list line)) (s-file 5) (e-file (index-of lis #\:)) (file (substring line s-file e-file)) (s-fnc (+ 1 (index-of lis #\`))) (e-fnc (+ s-fnc (index-of (string->list (substring line (+ 0 s-fnc) (string-length line))) #\`))) (fnc (substring line s-fnc e-fnc)) (s-link (index-of lis #\#)) (e-link (string-length line)) (link (substring line s-link e-link)) ) (string-append (string (string-ref fnc 0)) "[`" fnc "`](" file "" link ""))) (define (loop) (let ((line (read-line))) (when (not (eof-object? line)) (with-handler (lambda (obj) (display `(Error processing line ,line details ,obj) (current-error-port))) (display (convert-line line)) (newline)) (lambda (k) (with-exception-handler (lambda (obj) (display `(Error processing line ,line details ,obj)) (k #t)) (lambda () (display (convert-line line)) (newline))))) (loop)))) (loop)
ed479a803b0b77eb98d9504d190d82b3f043c01dd6a5b025c338c2424a9c3c90
rroohhh/guix_packages
caps2esc.scm
(define-module (vup caps2esc) #:use-module (gnu) #:use-module (gnu services shepherd) #:use-module (gnu packages pkg-config) #:use-module (gnu packages xorg) #:use-module (gnu packages linux) #:use-module (guix packages) #:use-module (guix licenses) #:use-module (guix git-download) #:use-module (guix build-system gnu)) (define-public caps2esc (package (name "caps2esc") (version "1.0.4") (source (origin (method git-fetch) (uri (git-reference (url "") (commit "v1.0.4"))) (file-name (git-file-name name version)) (sha256 (base32 "0frxp0yfk293jknwgi6knbz2vk5i1ylj0g4gvrpn7d1z87s3r2hv")))) (build-system gnu-build-system) (arguments '(#:phases (modify-phases %standard-phases (delete 'configure) (delete 'check) ;; The upstream makefile does not include an install phase. (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin"))) (for-each (lambda (file) (install-file file bin) (delete-file file)) '("caps2esc"))) #t))))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("libevdev" ,libevdev) ("libudev" ,eudev))) (home-page "") (synopsis "Transforming the most useless key ever in the most useful one") (description "Making caps work as esc and space as shift") (license gpl3))) (define (caps2esc-shepherd-service _) (list (shepherd-service (documentation "Making caps work as esc and space as shift") (provision '(caps2esc)) (start #~(make-forkexec-constructor (list (string-append #$caps2esc "/bin/caps2esc")))) (stop #~(make-kill-destructor))))) (define-public caps2esc-service-type (service-type (name 'caps2esc) (description "Making caps work as esc and space as shift") (extensions (list (service-extension shepherd-root-service-type caps2esc-shepherd-service))) (default-value '())))
null
https://raw.githubusercontent.com/rroohhh/guix_packages/117480ede867def846fa3120766864ed634e9321/vup/caps2esc.scm
scheme
The upstream makefile does not include an install phase.
(define-module (vup caps2esc) #:use-module (gnu) #:use-module (gnu services shepherd) #:use-module (gnu packages pkg-config) #:use-module (gnu packages xorg) #:use-module (gnu packages linux) #:use-module (guix packages) #:use-module (guix licenses) #:use-module (guix git-download) #:use-module (guix build-system gnu)) (define-public caps2esc (package (name "caps2esc") (version "1.0.4") (source (origin (method git-fetch) (uri (git-reference (url "") (commit "v1.0.4"))) (file-name (git-file-name name version)) (sha256 (base32 "0frxp0yfk293jknwgi6knbz2vk5i1ylj0g4gvrpn7d1z87s3r2hv")))) (build-system gnu-build-system) (arguments '(#:phases (modify-phases %standard-phases (delete 'configure) (delete 'check) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin"))) (for-each (lambda (file) (install-file file bin) (delete-file file)) '("caps2esc"))) #t))))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("libevdev" ,libevdev) ("libudev" ,eudev))) (home-page "") (synopsis "Transforming the most useless key ever in the most useful one") (description "Making caps work as esc and space as shift") (license gpl3))) (define (caps2esc-shepherd-service _) (list (shepherd-service (documentation "Making caps work as esc and space as shift") (provision '(caps2esc)) (start #~(make-forkexec-constructor (list (string-append #$caps2esc "/bin/caps2esc")))) (stop #~(make-kill-destructor))))) (define-public caps2esc-service-type (service-type (name 'caps2esc) (description "Making caps work as esc and space as shift") (extensions (list (service-extension shepherd-root-service-type caps2esc-shepherd-service))) (default-value '())))
8a03883f37c31046cf9672a5da093762160bc792134741d1e0fef25f8b42c901
Gbury/dolmen
base.mli
* { 2 Builtin functions manipulations } val noop : _ -> _ -> [> `Not_found ] * Noop builtins function . val merge : ('a -> 'b -> ([> `Not_found ] as 'c)) list -> 'a -> 'b -> 'c (** A convenient function for merging a list of builtin parser functions into a single builtin function. *) * { 2 Smtlib Indexed i d helpers } type 'ret indexed = [ | `Not_indexed | `Unary of (string -> 'ret) | `Binary of (string -> string -> 'ret) | `Ternary of (string -> string -> string -> 'ret) | `Nary of int * (string list -> 'ret) ] (** The type of indexed family of operators. *) val parse_indexed : string -> string list -> (string -> 'ret indexed) -> err:(string -> int -> int -> 'ret) -> k:(unit -> 'ret) -> 'ret (** [parse_id basename indexes f ~err ~k] uses the function [f] to get an expected arity for the indexed identifier, and then tries and parse the index list according to the returned specification. *) val bad_ty_index_arity : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> 'env -> string -> int -> int -> [> `Ty of (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) ] (** Suitable [err] function for {parse_id} for typing sort indexed families. *) val bad_term_index_arity : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> 'env -> string -> int -> int -> [> `Term of (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) ] (** Suitable [err] function for {parse_id} for typing term indexed families. *) * { 2 Low - level helpers } type ('env, 'args, 'ret) helper = (module Tff_intf.S with type env = 'env) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'args -> 'ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val make_op0: (_, unit, _) helper * [ make_op ( module Type ) env ast op arity args ret ] checks that args is the empty list and returns [ Some ( ret ( ) ) ] , else it raises the appropriate exception from the typechecking module . that args is the empty list and returns [Some (ret ())], else it raises the appropriate exception from the typechecking module. *) val make_op1: (_, Dolmen.Std.Term.t, _) helper (** Same as {!make_op0} but the returning function takes a term as argument. *) val make_op2 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper (** Same as {!make_op0} but the returning function takes a couple of terms as argument. *) val make_op3 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper (** Same as {!make_op0} but the returning function takes a triple of terms as argument. *) val make_op4 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper (** Same as {!make_op0} but the returning function takes a quadruple of terms as argument. *) val make_opn : int -> (_, Dolmen.Std.Term.t list, _) helper * Same as { ! make_op0 } but takes an arity first , and the returning function takes a list of terms as argument . The list is guaranteed to have the same length as the given arity . and the returning function takes a list of terms as argument. The list is guaranteed to have the same length as the given arity. *) val make_assoc : (_, Dolmen.Std.Term.t list, _) helper * Ensures the list of arguments is at least of size 2 ( used for associative symbols ) . symbols). *) val fold_left_assoc : ('a -> 'a -> 'a) -> 'a list -> 'a (** Fold application of a left-associative function on a list. @raise Invalid_argument if the list is empty. *) val fold_right_assoc : ('a -> 'a -> 'a) -> 'a list -> 'a (** Fold application of a right-associative function on a list. @raise Invalid_argument if the list is empty. *) val make_chain : (_, Dolmen.Std.Term.t list, _) helper * Ensures the list of arguments is at least of size 2 ( used for chainable symbols ) . symbols). *) val map_chain : (module Tff_intf.S with type T.t = 't) -> ('t -> 't -> 't) -> 't list -> 't * Map a function on succesive pairs of elements in the arguments lists , and build the resulting conjunction . [ map_chain ( module Type ) mk \[t1 ; t2 ; .. ; tn\ ] ] is [ Type . T._and \[mk t1 t2 ; mk t2 t3 ; .. \ ] ] and build the resulting conjunction. [map_chain (module Type) mk \[t1; t2; ..; tn\]] is [Type.T._and \[mk t1 t2; mk t2 t3; ..\]] *) * { 2 High level helpers } val app0 : (module Tff_intf.S with type env = 'env) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val app0_ast : (module Tff_intf.S with type env = 'env) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val ty_app1 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app1_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app1 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app1_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app2 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app2_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app2 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app2_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app3 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app3_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app3 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app3_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app4 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app4_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app4 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app4_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_list : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term list -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_list_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term list -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_left : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_left_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_right : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_right_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_chain : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_chain_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_cst : (module Tff_intf.S with type env = 'env and type T.t = 'term and type T.Const.t = 'cst) -> 'env -> 'cst -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_ho : (module Thf_intf.S with type env = 'env and type T.t = 'term) -> 'env -> 'term -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_ho_ast : (module Thf_intf.S with type env = 'env and type T.t = 'term) -> 'env -> (Dolmen.Std.Term.t -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term)
null
https://raw.githubusercontent.com/Gbury/dolmen/21bfd8d221b39dfd72a7938a09a6b2ae85b3c391/src/typecheck/base.mli
ocaml
* A convenient function for merging a list of builtin parser functions into a single builtin function. * The type of indexed family of operators. * [parse_id basename indexes f ~err ~k] uses the function [f] to get an expected arity for the indexed identifier, and then tries and parse the index list according to the returned specification. * Suitable [err] function for {parse_id} for typing sort indexed families. * Suitable [err] function for {parse_id} for typing term indexed families. * Same as {!make_op0} but the returning function takes a term as argument. * Same as {!make_op0} but the returning function takes a couple of terms as argument. * Same as {!make_op0} but the returning function takes a triple of terms as argument. * Same as {!make_op0} but the returning function takes a quadruple of terms as argument. * Fold application of a left-associative function on a list. @raise Invalid_argument if the list is empty. * Fold application of a right-associative function on a list. @raise Invalid_argument if the list is empty.
* { 2 Builtin functions manipulations } val noop : _ -> _ -> [> `Not_found ] * Noop builtins function . val merge : ('a -> 'b -> ([> `Not_found ] as 'c)) list -> 'a -> 'b -> 'c * { 2 Smtlib Indexed i d helpers } type 'ret indexed = [ | `Not_indexed | `Unary of (string -> 'ret) | `Binary of (string -> string -> 'ret) | `Ternary of (string -> string -> string -> 'ret) | `Nary of int * (string list -> 'ret) ] val parse_indexed : string -> string list -> (string -> 'ret indexed) -> err:(string -> int -> int -> 'ret) -> k:(unit -> 'ret) -> 'ret val bad_ty_index_arity : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> 'env -> string -> int -> int -> [> `Ty of (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) ] val bad_term_index_arity : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> 'env -> string -> int -> int -> [> `Term of (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) ] * { 2 Low - level helpers } type ('env, 'args, 'ret) helper = (module Tff_intf.S with type env = 'env) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'args -> 'ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val make_op0: (_, unit, _) helper * [ make_op ( module Type ) env ast op arity args ret ] checks that args is the empty list and returns [ Some ( ret ( ) ) ] , else it raises the appropriate exception from the typechecking module . that args is the empty list and returns [Some (ret ())], else it raises the appropriate exception from the typechecking module. *) val make_op1: (_, Dolmen.Std.Term.t, _) helper val make_op2 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper val make_op3 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper val make_op4 : (_, Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t * Dolmen.Std.Term.t, _) helper val make_opn : int -> (_, Dolmen.Std.Term.t list, _) helper * Same as { ! make_op0 } but takes an arity first , and the returning function takes a list of terms as argument . The list is guaranteed to have the same length as the given arity . and the returning function takes a list of terms as argument. The list is guaranteed to have the same length as the given arity. *) val make_assoc : (_, Dolmen.Std.Term.t list, _) helper * Ensures the list of arguments is at least of size 2 ( used for associative symbols ) . symbols). *) val fold_left_assoc : ('a -> 'a -> 'a) -> 'a list -> 'a val fold_right_assoc : ('a -> 'a -> 'a) -> 'a list -> 'a val make_chain : (_, Dolmen.Std.Term.t list, _) helper * Ensures the list of arguments is at least of size 2 ( used for chainable symbols ) . symbols). *) val map_chain : (module Tff_intf.S with type T.t = 't) -> ('t -> 't -> 't) -> 't list -> 't * Map a function on succesive pairs of elements in the arguments lists , and build the resulting conjunction . [ map_chain ( module Type ) mk \[t1 ; t2 ; .. ; tn\ ] ] is [ Type . T._and \[mk t1 t2 ; mk t2 t3 ; .. \ ] ] and build the resulting conjunction. [map_chain (module Type) mk \[t1; t2; ..; tn\]] is [Type.T._and \[mk t1 t2; mk t2 t3; ..\]] *) * { 2 High level helpers } val app0 : (module Tff_intf.S with type env = 'env) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val app0_ast : (module Tff_intf.S with type env = 'env) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ret) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ret) val ty_app1 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app1_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app1 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app1_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app2 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app2_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app2 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app2_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app3 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app3_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app3 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app3_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val ty_app4 : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('ty -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val ty_app4_ast : (module Tff_intf.S with type env = 'env and type Ty.t = 'ty) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'ty -> 'ty -> 'ty -> 'ty -> 'ty) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'ty) val term_app4 : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app4_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_list : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> ('term list -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_list_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term list -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_left : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_left_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_right : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_right_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_chain : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> ('term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_chain_ast : (module Tff_intf.S with type env = 'env and type T.t = 'term) -> ?check:(Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> unit) -> 'env -> Intf.symbol -> (Dolmen.Std.Term.t -> 'term -> 'term -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_cst : (module Tff_intf.S with type env = 'env and type T.t = 'term and type T.Const.t = 'cst) -> 'env -> 'cst -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_ho : (module Thf_intf.S with type env = 'env and type T.t = 'term) -> 'env -> 'term -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term) val term_app_ho_ast : (module Thf_intf.S with type env = 'env and type T.t = 'term) -> 'env -> (Dolmen.Std.Term.t -> 'term) -> (Dolmen.Std.Term.t -> Dolmen.Std.Term.t list -> 'term)
2924b1383992b6b7a3e0f2fce1d7cf34a5cd390aacbb4523df3dc64a47d5cdb5
ocaml-multicore/tezos
delegate_services.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > Copyright ( c ) 2021 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Alpha_context type error += Balance_rpc_non_delegate of public_key_hash let () = register_error_kind `Temporary ~id:"delegate_service.balance_rpc_on_non_delegate" ~title:"Balance request for an unregistered delegate" ~description:"The account whose balance was requested is not a delegate." ~pp:(fun ppf pkh -> Format.fprintf ppf "The implicit account (%a) whose balance was requested is not a \ registered delegate. To get the balance of this account you can use \ the ../context/contracts/%a/balance RPC." Signature.Public_key_hash.pp pkh Signature.Public_key_hash.pp pkh) Data_encoding.(obj1 (req "pkh" Signature.Public_key_hash.encoding)) (function Balance_rpc_non_delegate pkh -> Some pkh | _ -> None) (fun pkh -> Balance_rpc_non_delegate pkh) type info = { full_balance : Tez.t; current_frozen_deposits : Tez.t; frozen_deposits : Tez.t; staking_balance : Tez.t; frozen_deposits_limit : Tez.t option; delegated_contracts : Contract.t list; delegated_balance : Tez.t; deactivated : bool; grace_period : Cycle.t; voting_power : int64; } let info_encoding = let open Data_encoding in conv (fun { full_balance; current_frozen_deposits; frozen_deposits; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; } -> ( full_balance, current_frozen_deposits, frozen_deposits, staking_balance, frozen_deposits_limit, delegated_contracts, delegated_balance, deactivated, grace_period, voting_power )) (fun ( full_balance, current_frozen_deposits, frozen_deposits, staking_balance, frozen_deposits_limit, delegated_contracts, delegated_balance, deactivated, grace_period, voting_power ) -> { full_balance; current_frozen_deposits; frozen_deposits; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; }) (obj10 (req "full_balance" Tez.encoding) (req "current_frozen_deposits" Tez.encoding) (req "frozen_deposits" Tez.encoding) (req "staking_balance" Tez.encoding) (opt "frozen_deposits_limit" Tez.encoding) (req "delegated_contracts" (list Contract.encoding)) (req "delegated_balance" Tez.encoding) (req "deactivated" bool) (req "grace_period" Cycle.encoding) (req "voting_power" int64)) let participation_info_encoding = let open Data_encoding in conv (fun { Delegate.expected_cycle_activity; minimal_cycle_activity; missed_slots; missed_levels; remaining_allowed_missed_slots; expected_endorsing_rewards; } -> ( expected_cycle_activity, minimal_cycle_activity, missed_slots, missed_levels, remaining_allowed_missed_slots, expected_endorsing_rewards )) (fun ( expected_cycle_activity, minimal_cycle_activity, missed_slots, missed_levels, remaining_allowed_missed_slots, expected_endorsing_rewards ) -> { expected_cycle_activity; minimal_cycle_activity; missed_slots; missed_levels; remaining_allowed_missed_slots; expected_endorsing_rewards; }) (obj6 (req "expected_cycle_activity" int31) (req "minimal_cycle_activity" int31) (req "missed_slots" int31) (req "missed_levels" int31) (req "remaining_allowed_missed_slots" int31) (req "expected_endorsing_rewards" Tez.encoding)) module S = struct let raw_path = RPC_path.(open_root / "context" / "delegates") open Data_encoding type list_query = { active : bool; inactive : bool; with_minimal_stake : bool; without_minimal_stake : bool; } let list_query : list_query RPC_query.t = let open RPC_query in query (fun active inactive with_minimal_stake without_minimal_stake -> {active; inactive; with_minimal_stake; without_minimal_stake}) |+ flag "active" (fun t -> t.active) |+ flag "inactive" (fun t -> t.inactive) |+ flag "with_minimal_stake" (fun t -> t.with_minimal_stake) |+ flag "without_minimal_stake" (fun t -> t.without_minimal_stake) |> seal let list_delegate = RPC_service.get_service ~description: "Lists all registered delegates. The arguments `active`, `inactive`, \ `with_minimal_stake`, and `without_minimal_stake` allow to enumerate \ only the delegates that are active, inactive, have at least a minimal \ stake to participate in consensus and in governance, or do not have \ such a minimal stake, respectively." ~query:list_query ~output:(list Signature.Public_key_hash.encoding) raw_path let path = RPC_path.(raw_path /: Signature.Public_key_hash.rpc_arg) let info = RPC_service.get_service ~description:"Everything about a delegate." ~query:RPC_query.empty ~output:info_encoding path let full_balance = RPC_service.get_service ~description: "Returns the full balance (in mutez) of a given delegate, including \ the frozen deposits. It does not include its delegated balance." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "full_balance") let current_frozen_deposits = RPC_service.get_service ~description: "Returns the current amount of the frozen deposits (in mutez)." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "current_frozen_deposits") let frozen_deposits = RPC_service.get_service ~description: "Returns the initial amount (that is, at the beginning of a cycle) of \ the frozen deposits (in mutez). This amount is the same as the \ current amount of the frozen deposits, unless the delegate has been \ punished." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "frozen_deposits") let staking_balance = RPC_service.get_service ~description: "Returns the total amount of tokens (in mutez) delegated to a given \ delegate. This includes the balances of all the contracts that \ delegate to it, but also the balance of the delegate itself and its \ frozen deposits." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "staking_balance") let frozen_deposits_limit = RPC_service.get_service ~description: "Returns the frozen deposits limit for the given delegate or none if \ no limit is set." ~query:RPC_query.empty ~output:(Data_encoding.option Tez.encoding) RPC_path.(path / "frozen_deposits_limit") let delegated_contracts = RPC_service.get_service ~description: "Returns the list of contracts that delegate to a given delegate." ~query:RPC_query.empty ~output:(list Contract.encoding) RPC_path.(path / "delegated_contracts") let delegated_balance = RPC_service.get_service ~description: "Returns the sum (in mutez) of all balances of all the contracts that \ delegate to a given delegate. This excludes the delegate's own \ balance and its frozen deposits." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "delegated_balance") let deactivated = RPC_service.get_service ~description: "Tells whether the delegate is currently tagged as deactivated or not." ~query:RPC_query.empty ~output:bool RPC_path.(path / "deactivated") let grace_period = RPC_service.get_service ~description: "Returns the cycle by the end of which the delegate might be \ deactivated if she fails to execute any delegate action. A \ deactivated delegate might be reactivated (without loosing any stake) \ by simply re-registering as a delegate. For deactivated delegates, \ this value contains the cycle at which they were deactivated." ~query:RPC_query.empty ~output:Cycle.encoding RPC_path.(path / "grace_period") let voting_power = RPC_service.get_service ~description:"The voting power in the vote listings for a given delegate." ~query:RPC_query.empty ~output:Data_encoding.int64 RPC_path.(path / "voting_power") let participation = RPC_service.get_service ~description: "Returns cycle and level participation information. In particular this \ indicates, in the field 'expected_cycle_activity', the number of \ slots the delegate is expected to have in the cycle based on its \ active stake. The field 'minimal_cycle_activity' indicates the \ minimal endorsing slots in the cycle required to get endorsing \ rewards. It is computed based on 'expected_cycle_activity. The fields \ 'missed_slots' and 'missed_levels' indicate the number of missed \ endorsing slots and missed levels (for endorsing) in the cycle so \ far. 'missed_slots' indicates the number of missed endorsing slots in \ the cycle so far. The field 'remaining_allowed_missed_slots' \ indicates the remaining amount of endorsing slots that can be missed \ in the cycle before forfeiting the rewards. Finally, \ 'expected_endorsing_rewards' indicates the endorsing rewards that \ will be distributed at the end of the cycle if activity at that point \ will be greater than the minimal required; if the activity is already \ known to be below the required minimum, then the rewards are zero." ~query:RPC_query.empty ~output:participation_info_encoding RPC_path.(path / "participation") end let register () = let open Services_registration in register0 ~chunked:true S.list_delegate (fun ctxt q () -> Delegate.list ctxt >>= fun delegates -> (match q with | {active = true; inactive = false; _} -> List.filter_es (fun pkh -> Delegate.deactivated ctxt pkh >|=? not) delegates | {active = false; inactive = true; _} -> List.filter_es (fun pkh -> Delegate.deactivated ctxt pkh) delegates | {active = false; inactive = false; _} (* This case is counter-intuitive, but it represents the default behavior, when no arguments are given *) | {active = true; inactive = true; _} -> return delegates) >>=? fun delegates -> let tokens_per_roll = Constants.tokens_per_roll ctxt in match q with | {with_minimal_stake = true; without_minimal_stake = false; _} -> List.filter_es (fun pkh -> Delegate.staking_balance ctxt pkh >|=? fun staking_balance -> Tez.(staking_balance >= tokens_per_roll)) delegates | {with_minimal_stake = false; without_minimal_stake = true; _} -> List.filter_es (fun pkh -> Delegate.staking_balance ctxt pkh >|=? fun staking_balance -> Tez.(staking_balance < tokens_per_roll)) delegates | {with_minimal_stake = true; without_minimal_stake = true; _} | {with_minimal_stake = false; without_minimal_stake = false; _} -> return delegates) ; register1 ~chunked:false S.info (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.full_balance ctxt pkh >>=? fun full_balance -> Delegate.frozen_deposits ctxt pkh >>=? fun frozen_deposits -> Delegate.staking_balance ctxt pkh >>=? fun staking_balance -> Delegate.frozen_deposits_limit ctxt pkh >>=? fun frozen_deposits_limit -> Delegate.delegated_contracts ctxt pkh >>= fun delegated_contracts -> Delegate.delegated_balance ctxt pkh >>=? fun delegated_balance -> Delegate.deactivated ctxt pkh >>=? fun deactivated -> Delegate.grace_period ctxt pkh >>=? fun grace_period -> Vote.get_voting_power_free ctxt pkh >|=? fun voting_power -> { full_balance; current_frozen_deposits = frozen_deposits.current_amount; frozen_deposits = frozen_deposits.initial_amount; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; }) ; register1 ~chunked:false S.full_balance (fun ctxt pkh () () -> trace (Balance_rpc_non_delegate pkh) (Delegate.check_delegate ctxt pkh) >>=? fun () -> Delegate.full_balance ctxt pkh) ; register1 ~chunked:false S.current_frozen_deposits (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits ctxt pkh >>=? fun deposits -> return deposits.current_amount) ; register1 ~chunked:false S.frozen_deposits (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits ctxt pkh >>=? fun deposits -> return deposits.initial_amount) ; register1 ~chunked:false S.staking_balance (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.staking_balance ctxt pkh) ; register1 ~chunked:false S.frozen_deposits_limit (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits_limit ctxt pkh) ; register1 ~chunked:true S.delegated_contracts (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegated_contracts ctxt pkh >|= ok) ; register1 ~chunked:false S.delegated_balance (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegated_balance ctxt pkh) ; register1 ~chunked:false S.deactivated (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.deactivated ctxt pkh) ; register1 ~chunked:false S.grace_period (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.grace_period ctxt pkh) ; register1 ~chunked:false S.voting_power (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Vote.get_voting_power_free ctxt pkh) ; register1 ~chunked:false S.participation (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegate_participation_info ctxt pkh) let list ctxt block ?(active = true) ?(inactive = false) ?(with_minimal_stake = true) ?(without_minimal_stake = false) () = RPC_context.make_call0 S.list_delegate ctxt block {active; inactive; with_minimal_stake; without_minimal_stake} () let info ctxt block pkh = RPC_context.make_call1 S.info ctxt block pkh () () let full_balance ctxt block pkh = RPC_context.make_call1 S.full_balance ctxt block pkh () () let current_frozen_deposits ctxt block pkh = RPC_context.make_call1 S.current_frozen_deposits ctxt block pkh () () let frozen_deposits ctxt block pkh = RPC_context.make_call1 S.frozen_deposits ctxt block pkh () () let staking_balance ctxt block pkh = RPC_context.make_call1 S.staking_balance ctxt block pkh () () let frozen_deposits_limit ctxt block pkh = RPC_context.make_call1 S.frozen_deposits_limit ctxt block pkh () () let delegated_contracts ctxt block pkh = RPC_context.make_call1 S.delegated_contracts ctxt block pkh () () let delegated_balance ctxt block pkh = RPC_context.make_call1 S.delegated_balance ctxt block pkh () () let deactivated ctxt block pkh = RPC_context.make_call1 S.deactivated ctxt block pkh () () let grace_period ctxt block pkh = RPC_context.make_call1 S.grace_period ctxt block pkh () () let voting_power ctxt block pkh = RPC_context.make_call1 S.voting_power ctxt block pkh () () let participation ctxt block pkh = RPC_context.make_call1 S.participation ctxt block pkh () ()
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/delegate_services.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** This case is counter-intuitive, but it represents the default behavior, when no arguments are given
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > Copyright ( c ) 2021 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Alpha_context type error += Balance_rpc_non_delegate of public_key_hash let () = register_error_kind `Temporary ~id:"delegate_service.balance_rpc_on_non_delegate" ~title:"Balance request for an unregistered delegate" ~description:"The account whose balance was requested is not a delegate." ~pp:(fun ppf pkh -> Format.fprintf ppf "The implicit account (%a) whose balance was requested is not a \ registered delegate. To get the balance of this account you can use \ the ../context/contracts/%a/balance RPC." Signature.Public_key_hash.pp pkh Signature.Public_key_hash.pp pkh) Data_encoding.(obj1 (req "pkh" Signature.Public_key_hash.encoding)) (function Balance_rpc_non_delegate pkh -> Some pkh | _ -> None) (fun pkh -> Balance_rpc_non_delegate pkh) type info = { full_balance : Tez.t; current_frozen_deposits : Tez.t; frozen_deposits : Tez.t; staking_balance : Tez.t; frozen_deposits_limit : Tez.t option; delegated_contracts : Contract.t list; delegated_balance : Tez.t; deactivated : bool; grace_period : Cycle.t; voting_power : int64; } let info_encoding = let open Data_encoding in conv (fun { full_balance; current_frozen_deposits; frozen_deposits; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; } -> ( full_balance, current_frozen_deposits, frozen_deposits, staking_balance, frozen_deposits_limit, delegated_contracts, delegated_balance, deactivated, grace_period, voting_power )) (fun ( full_balance, current_frozen_deposits, frozen_deposits, staking_balance, frozen_deposits_limit, delegated_contracts, delegated_balance, deactivated, grace_period, voting_power ) -> { full_balance; current_frozen_deposits; frozen_deposits; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; }) (obj10 (req "full_balance" Tez.encoding) (req "current_frozen_deposits" Tez.encoding) (req "frozen_deposits" Tez.encoding) (req "staking_balance" Tez.encoding) (opt "frozen_deposits_limit" Tez.encoding) (req "delegated_contracts" (list Contract.encoding)) (req "delegated_balance" Tez.encoding) (req "deactivated" bool) (req "grace_period" Cycle.encoding) (req "voting_power" int64)) let participation_info_encoding = let open Data_encoding in conv (fun { Delegate.expected_cycle_activity; minimal_cycle_activity; missed_slots; missed_levels; remaining_allowed_missed_slots; expected_endorsing_rewards; } -> ( expected_cycle_activity, minimal_cycle_activity, missed_slots, missed_levels, remaining_allowed_missed_slots, expected_endorsing_rewards )) (fun ( expected_cycle_activity, minimal_cycle_activity, missed_slots, missed_levels, remaining_allowed_missed_slots, expected_endorsing_rewards ) -> { expected_cycle_activity; minimal_cycle_activity; missed_slots; missed_levels; remaining_allowed_missed_slots; expected_endorsing_rewards; }) (obj6 (req "expected_cycle_activity" int31) (req "minimal_cycle_activity" int31) (req "missed_slots" int31) (req "missed_levels" int31) (req "remaining_allowed_missed_slots" int31) (req "expected_endorsing_rewards" Tez.encoding)) module S = struct let raw_path = RPC_path.(open_root / "context" / "delegates") open Data_encoding type list_query = { active : bool; inactive : bool; with_minimal_stake : bool; without_minimal_stake : bool; } let list_query : list_query RPC_query.t = let open RPC_query in query (fun active inactive with_minimal_stake without_minimal_stake -> {active; inactive; with_minimal_stake; without_minimal_stake}) |+ flag "active" (fun t -> t.active) |+ flag "inactive" (fun t -> t.inactive) |+ flag "with_minimal_stake" (fun t -> t.with_minimal_stake) |+ flag "without_minimal_stake" (fun t -> t.without_minimal_stake) |> seal let list_delegate = RPC_service.get_service ~description: "Lists all registered delegates. The arguments `active`, `inactive`, \ `with_minimal_stake`, and `without_minimal_stake` allow to enumerate \ only the delegates that are active, inactive, have at least a minimal \ stake to participate in consensus and in governance, or do not have \ such a minimal stake, respectively." ~query:list_query ~output:(list Signature.Public_key_hash.encoding) raw_path let path = RPC_path.(raw_path /: Signature.Public_key_hash.rpc_arg) let info = RPC_service.get_service ~description:"Everything about a delegate." ~query:RPC_query.empty ~output:info_encoding path let full_balance = RPC_service.get_service ~description: "Returns the full balance (in mutez) of a given delegate, including \ the frozen deposits. It does not include its delegated balance." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "full_balance") let current_frozen_deposits = RPC_service.get_service ~description: "Returns the current amount of the frozen deposits (in mutez)." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "current_frozen_deposits") let frozen_deposits = RPC_service.get_service ~description: "Returns the initial amount (that is, at the beginning of a cycle) of \ the frozen deposits (in mutez). This amount is the same as the \ current amount of the frozen deposits, unless the delegate has been \ punished." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "frozen_deposits") let staking_balance = RPC_service.get_service ~description: "Returns the total amount of tokens (in mutez) delegated to a given \ delegate. This includes the balances of all the contracts that \ delegate to it, but also the balance of the delegate itself and its \ frozen deposits." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "staking_balance") let frozen_deposits_limit = RPC_service.get_service ~description: "Returns the frozen deposits limit for the given delegate or none if \ no limit is set." ~query:RPC_query.empty ~output:(Data_encoding.option Tez.encoding) RPC_path.(path / "frozen_deposits_limit") let delegated_contracts = RPC_service.get_service ~description: "Returns the list of contracts that delegate to a given delegate." ~query:RPC_query.empty ~output:(list Contract.encoding) RPC_path.(path / "delegated_contracts") let delegated_balance = RPC_service.get_service ~description: "Returns the sum (in mutez) of all balances of all the contracts that \ delegate to a given delegate. This excludes the delegate's own \ balance and its frozen deposits." ~query:RPC_query.empty ~output:Tez.encoding RPC_path.(path / "delegated_balance") let deactivated = RPC_service.get_service ~description: "Tells whether the delegate is currently tagged as deactivated or not." ~query:RPC_query.empty ~output:bool RPC_path.(path / "deactivated") let grace_period = RPC_service.get_service ~description: "Returns the cycle by the end of which the delegate might be \ deactivated if she fails to execute any delegate action. A \ deactivated delegate might be reactivated (without loosing any stake) \ by simply re-registering as a delegate. For deactivated delegates, \ this value contains the cycle at which they were deactivated." ~query:RPC_query.empty ~output:Cycle.encoding RPC_path.(path / "grace_period") let voting_power = RPC_service.get_service ~description:"The voting power in the vote listings for a given delegate." ~query:RPC_query.empty ~output:Data_encoding.int64 RPC_path.(path / "voting_power") let participation = RPC_service.get_service ~description: "Returns cycle and level participation information. In particular this \ indicates, in the field 'expected_cycle_activity', the number of \ slots the delegate is expected to have in the cycle based on its \ active stake. The field 'minimal_cycle_activity' indicates the \ minimal endorsing slots in the cycle required to get endorsing \ rewards. It is computed based on 'expected_cycle_activity. The fields \ 'missed_slots' and 'missed_levels' indicate the number of missed \ endorsing slots and missed levels (for endorsing) in the cycle so \ far. 'missed_slots' indicates the number of missed endorsing slots in \ the cycle so far. The field 'remaining_allowed_missed_slots' \ indicates the remaining amount of endorsing slots that can be missed \ in the cycle before forfeiting the rewards. Finally, \ 'expected_endorsing_rewards' indicates the endorsing rewards that \ will be distributed at the end of the cycle if activity at that point \ will be greater than the minimal required; if the activity is already \ known to be below the required minimum, then the rewards are zero." ~query:RPC_query.empty ~output:participation_info_encoding RPC_path.(path / "participation") end let register () = let open Services_registration in register0 ~chunked:true S.list_delegate (fun ctxt q () -> Delegate.list ctxt >>= fun delegates -> (match q with | {active = true; inactive = false; _} -> List.filter_es (fun pkh -> Delegate.deactivated ctxt pkh >|=? not) delegates | {active = false; inactive = true; _} -> List.filter_es (fun pkh -> Delegate.deactivated ctxt pkh) delegates | {active = false; inactive = false; _} | {active = true; inactive = true; _} -> return delegates) >>=? fun delegates -> let tokens_per_roll = Constants.tokens_per_roll ctxt in match q with | {with_minimal_stake = true; without_minimal_stake = false; _} -> List.filter_es (fun pkh -> Delegate.staking_balance ctxt pkh >|=? fun staking_balance -> Tez.(staking_balance >= tokens_per_roll)) delegates | {with_minimal_stake = false; without_minimal_stake = true; _} -> List.filter_es (fun pkh -> Delegate.staking_balance ctxt pkh >|=? fun staking_balance -> Tez.(staking_balance < tokens_per_roll)) delegates | {with_minimal_stake = true; without_minimal_stake = true; _} | {with_minimal_stake = false; without_minimal_stake = false; _} -> return delegates) ; register1 ~chunked:false S.info (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.full_balance ctxt pkh >>=? fun full_balance -> Delegate.frozen_deposits ctxt pkh >>=? fun frozen_deposits -> Delegate.staking_balance ctxt pkh >>=? fun staking_balance -> Delegate.frozen_deposits_limit ctxt pkh >>=? fun frozen_deposits_limit -> Delegate.delegated_contracts ctxt pkh >>= fun delegated_contracts -> Delegate.delegated_balance ctxt pkh >>=? fun delegated_balance -> Delegate.deactivated ctxt pkh >>=? fun deactivated -> Delegate.grace_period ctxt pkh >>=? fun grace_period -> Vote.get_voting_power_free ctxt pkh >|=? fun voting_power -> { full_balance; current_frozen_deposits = frozen_deposits.current_amount; frozen_deposits = frozen_deposits.initial_amount; staking_balance; frozen_deposits_limit; delegated_contracts; delegated_balance; deactivated; grace_period; voting_power; }) ; register1 ~chunked:false S.full_balance (fun ctxt pkh () () -> trace (Balance_rpc_non_delegate pkh) (Delegate.check_delegate ctxt pkh) >>=? fun () -> Delegate.full_balance ctxt pkh) ; register1 ~chunked:false S.current_frozen_deposits (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits ctxt pkh >>=? fun deposits -> return deposits.current_amount) ; register1 ~chunked:false S.frozen_deposits (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits ctxt pkh >>=? fun deposits -> return deposits.initial_amount) ; register1 ~chunked:false S.staking_balance (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.staking_balance ctxt pkh) ; register1 ~chunked:false S.frozen_deposits_limit (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.frozen_deposits_limit ctxt pkh) ; register1 ~chunked:true S.delegated_contracts (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegated_contracts ctxt pkh >|= ok) ; register1 ~chunked:false S.delegated_balance (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegated_balance ctxt pkh) ; register1 ~chunked:false S.deactivated (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.deactivated ctxt pkh) ; register1 ~chunked:false S.grace_period (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.grace_period ctxt pkh) ; register1 ~chunked:false S.voting_power (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Vote.get_voting_power_free ctxt pkh) ; register1 ~chunked:false S.participation (fun ctxt pkh () () -> Delegate.check_delegate ctxt pkh >>=? fun () -> Delegate.delegate_participation_info ctxt pkh) let list ctxt block ?(active = true) ?(inactive = false) ?(with_minimal_stake = true) ?(without_minimal_stake = false) () = RPC_context.make_call0 S.list_delegate ctxt block {active; inactive; with_minimal_stake; without_minimal_stake} () let info ctxt block pkh = RPC_context.make_call1 S.info ctxt block pkh () () let full_balance ctxt block pkh = RPC_context.make_call1 S.full_balance ctxt block pkh () () let current_frozen_deposits ctxt block pkh = RPC_context.make_call1 S.current_frozen_deposits ctxt block pkh () () let frozen_deposits ctxt block pkh = RPC_context.make_call1 S.frozen_deposits ctxt block pkh () () let staking_balance ctxt block pkh = RPC_context.make_call1 S.staking_balance ctxt block pkh () () let frozen_deposits_limit ctxt block pkh = RPC_context.make_call1 S.frozen_deposits_limit ctxt block pkh () () let delegated_contracts ctxt block pkh = RPC_context.make_call1 S.delegated_contracts ctxt block pkh () () let delegated_balance ctxt block pkh = RPC_context.make_call1 S.delegated_balance ctxt block pkh () () let deactivated ctxt block pkh = RPC_context.make_call1 S.deactivated ctxt block pkh () () let grace_period ctxt block pkh = RPC_context.make_call1 S.grace_period ctxt block pkh () () let voting_power ctxt block pkh = RPC_context.make_call1 S.voting_power ctxt block pkh () () let participation ctxt block pkh = RPC_context.make_call1 S.participation ctxt block pkh () ()
df53744b6242c3e90dab3b56daca95eeab975cc8f7d09bcf42325ffa3e6a8ac4
ocsigen/ocsimore
ocsimore_pam.ml
Ocsimore * Copyright ( C ) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * 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. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * @author @author Vincent Balat *) let mutex = Lwt_mutex.create () let pam_auth ?(service = "") ~name ~pwd = (* Lwt_mutex.lock mutex >>= fun () -> Lwt.finalize (fun () -> Lwt_preemptive.detach (fun () -> *) try let pam = Pam.pam_start service ~user:name (fun _ _ -> pwd) in Pam.pam_set_item pam Pam.pam_item_fail_delay; Pam.pam_authenticate pam [] ~silent:true; ignore (Pam.pam_end pam); Lwt.return () with (Pam.Pam_Error _) as exn -> Lwt_log.ign_debug ~section ~exn "Ocsimore_pam" ; Lwt.fail User.BadPassword | exn -> Lwt_log.ign_debug ~section ~exn "Ocsimore_pam" ; Lwt.fail exn (* ) () ) (fun () -> Lwt_mutex.unlock mutex; Lwt.return ()) *) let parse_config conf = let inner = function | [] -> None | [Simplexmlparser.Element ("pam", ["service", s], [])] -> Some s | _ -> raise (Ocsigen_extensions.Error_in_config_file ("Unexpected content inside User_site config")) in let service = inner conf in User_external_auth.add_external_auth { User_external_auth.ext_auth_authenticate = pam_auth ?service; ext_user_exists = (fun _ -> Lwt_log.ign_warning "PAM authentification not supported by wikiperso"; Lwt.return false ); } let () = Ocsigen_extensions.register_extension ~name:"ocsimore-pam" ~init_fun:parse_config ()
null
https://raw.githubusercontent.com/ocsigen/ocsimore/8eeaf043ed6f1f167a96cbdc5f72a5225d9516d5/src/user/pam/ocsimore_pam.ml
ocaml
Lwt_mutex.lock mutex >>= fun () -> Lwt.finalize (fun () -> Lwt_preemptive.detach (fun () -> ) () ) (fun () -> Lwt_mutex.unlock mutex; Lwt.return ())
Ocsimore * Copyright ( C ) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * 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. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (C) 2008 * Laboratoire PPS - Université Paris Diderot - CNRS * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) * @author @author Vincent Balat *) let mutex = Lwt_mutex.create () let pam_auth ?(service = "") ~name ~pwd = try let pam = Pam.pam_start service ~user:name (fun _ _ -> pwd) in Pam.pam_set_item pam Pam.pam_item_fail_delay; Pam.pam_authenticate pam [] ~silent:true; ignore (Pam.pam_end pam); Lwt.return () with (Pam.Pam_Error _) as exn -> Lwt_log.ign_debug ~section ~exn "Ocsimore_pam" ; Lwt.fail User.BadPassword | exn -> Lwt_log.ign_debug ~section ~exn "Ocsimore_pam" ; Lwt.fail exn let parse_config conf = let inner = function | [] -> None | [Simplexmlparser.Element ("pam", ["service", s], [])] -> Some s | _ -> raise (Ocsigen_extensions.Error_in_config_file ("Unexpected content inside User_site config")) in let service = inner conf in User_external_auth.add_external_auth { User_external_auth.ext_auth_authenticate = pam_auth ?service; ext_user_exists = (fun _ -> Lwt_log.ign_warning "PAM authentification not supported by wikiperso"; Lwt.return false ); } let () = Ocsigen_extensions.register_extension ~name:"ocsimore-pam" ~init_fun:parse_config ()
ebe88185df5583395c461b1064997ba4385521e8815f357720a8e732f5f92e5b
ocharles/opaleye-tf
BaseTypes.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Opaleye.TF.BaseTypes where import qualified Data.Aeson as Aeson import Data.ByteString (ByteString) import Data.Fixed (E0, E1, E2, E3, E6, E9, Fixed) import Data.Int (Int32, Int64) import Data.Text import Data.Time (LocalTime, UTCTime) import Data.UUID (UUID) import GHC.TypeLits (Nat) import qualified Opaleye.Internal.Column as Op import qualified Opaleye.PGTypes as Op import Opaleye.TF.Col import Opaleye.TF.Expr import Opaleye.TF.Interpretation import Opaleye.TF.Lit import Opaleye.TF.Nullable import Opaleye.TF.Machinery data WithTimeZone = WithTimeZone | WithoutTimeZone deriving (Eq,Ord,Read,Show,Enum,Bounded) -- | The universe of base types known about by PostgreSQL. data PGType ^ @bigint@ | PGBigserial -- ^ @bigserial@ | PGBit (Maybe Nat) -- ^ @bit [ (n) ]@ | PGBitVarying (Maybe Nat) -- ^ @bit varying [ (n) ]@ | PGBoolean -- ^ @boolean@ | PGBox -- ^ @box@ | PGBytea -- ^ @bytea@ | PGCharacter (Maybe Nat) -- ^ @character [ (n) ]@ | PGVarchar Nat -- ^ @character varying (n)@ (unbound @character varying@ is 'PGText') | PGCidr -- ^ @cidr@ | PGCircle -- ^ @circle@ ^ @date@ ^ precision@ | PGInet -- ^ @inet@ | PGInteger -- ^ @integer@ | PGInterval -- ^ @interval@. There is no ability to specify the precision or fields, if you require this please open a feature request. | PGJSON -- ^ @json@ ^ | PGLine -- ^ @line@ | PGLseg -- ^ @lseg@ ^ @macaddr@ | PGMoney -- ^ @money@ | PGNumeric Nat ^ @numeric(p , s)@ | PGPath -- ^ @path@ | PGPGLSN -- ^ @pg_lsn@ ^ @point@ | PGPolygon -- ^ @polygon@ | PGReal -- ^ @real@ | PGSmallint -- ^ @smallint@ | PGSmallserial -- ^ @smallserial@ | PGSerial -- ^ @serial@ | PGText -- ^ @text@ and @character varying@ ^ @time with / without time ^ @timestamp with / without time | PGTSQuery -- ^ @tsquery@ | PGTSVector -- ^ @tsvector@ | PGTXIDSnapshot -- ^ @txid_sapnshot@ | PGUUID -- ^ @uuid@ | PGXML -- ^ @xml@ type instance Col (Expr s) (t :: PGType) = Expr s t type instance Col (Compose (Expr s) 'Nullable) (a :: PGType) = Expr s ('Nullable a) type instance Col (Compose (Expr s) 'NotNullable) (a :: PGType) = Expr s a type instance Col Interpret 'PGBigint = Int64 type instance Col Interpret 'PGBoolean = Bool type instance Col Interpret 'PGInteger = Int32 type instance Col Interpret 'PGReal = Float type instance Col Interpret 'PGText = Text type instance Col Interpret ('PGTimestamp 'WithoutTimeZone) = LocalTime type instance Col Interpret ('PGTimestamp 'WithTimeZone) = UTCTime type instance Col Interpret 'PGDouble = Double type instance Col Interpret ('PGNumeric p 0) = Fixed E0 type instance Col Interpret ('PGNumeric p 1) = Fixed E1 type instance Col Interpret ('PGNumeric p 2) = Fixed E2 type instance Col Interpret ('PGNumeric p 3) = Fixed E3 type instance Col Interpret ('PGNumeric p 6) = Fixed E6 type instance Col Interpret ('PGNumeric p 9) = Fixed E9 type instance Col Interpret 'PGBytea = ByteString type instance Col Interpret ('PGCharacter len) = Text type instance Col Interpret ('PGVarchar len) = Text type instance Col Interpret 'PGJSON = Aeson.Value type instance Col Interpret 'PGJSONB = Aeson.Value type instance Col Interpret 'PGUUID = UUID instance Lit 'PGBigint where lit = Expr . Op.unColumn . Op.pgInt8 instance Lit 'PGBoolean where lit = Expr . Op.unColumn . Op.pgBool instance Lit 'PGInteger where lit = Expr . Op.unColumn . Op.pgInt4 . fromIntegral instance Lit 'PGReal where lit = Expr . Op.unColumn . Op.pgDouble . realToFrac instance Lit 'PGText where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGCharacter n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGVarchar n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGTimestamp 'WithoutTimeZone) where lit = Expr . Op.unColumn . Op.pgLocalTime instance Lit ('PGTimestamp 'WithTimeZone) where lit = Expr . Op.unColumn . Op.pgUTCTime instance Lit 'PGDouble where lit = Expr . Op.unColumn . Op.pgDouble instance Lit 'PGJSON where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGJSONB where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGUUID where lit = Expr . Op.unColumn . Op.pgUUID pgNow :: Expr s ('PGTimestamp 'WithTimeZone) pgNow = mapExpr Cast (lit (pack "now") :: Expr s 'PGText)
null
https://raw.githubusercontent.com/ocharles/opaleye-tf/b4b27f51e6f6137e5eb037b3bf36e00091cd1b8a/src/Opaleye/TF/BaseTypes.hs
haskell
| The universe of base types known about by PostgreSQL. ^ @bigserial@ ^ @bit [ (n) ]@ ^ @bit varying [ (n) ]@ ^ @boolean@ ^ @box@ ^ @bytea@ ^ @character [ (n) ]@ ^ @character varying (n)@ (unbound @character varying@ is 'PGText') ^ @cidr@ ^ @circle@ ^ @inet@ ^ @integer@ ^ @interval@. There is no ability to specify the precision or fields, if you require this please open a feature request. ^ @json@ ^ @line@ ^ @lseg@ ^ @money@ ^ @path@ ^ @pg_lsn@ ^ @polygon@ ^ @real@ ^ @smallint@ ^ @smallserial@ ^ @serial@ ^ @text@ and @character varying@ ^ @tsquery@ ^ @tsvector@ ^ @txid_sapnshot@ ^ @uuid@ ^ @xml@
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Opaleye.TF.BaseTypes where import qualified Data.Aeson as Aeson import Data.ByteString (ByteString) import Data.Fixed (E0, E1, E2, E3, E6, E9, Fixed) import Data.Int (Int32, Int64) import Data.Text import Data.Time (LocalTime, UTCTime) import Data.UUID (UUID) import GHC.TypeLits (Nat) import qualified Opaleye.Internal.Column as Op import qualified Opaleye.PGTypes as Op import Opaleye.TF.Col import Opaleye.TF.Expr import Opaleye.TF.Interpretation import Opaleye.TF.Lit import Opaleye.TF.Nullable import Opaleye.TF.Machinery data WithTimeZone = WithTimeZone | WithoutTimeZone deriving (Eq,Ord,Read,Show,Enum,Bounded) data PGType ^ @bigint@ ^ @date@ ^ precision@ ^ ^ @macaddr@ | PGNumeric Nat ^ @numeric(p , s)@ ^ @point@ ^ @time with / without time ^ @timestamp with / without time type instance Col (Expr s) (t :: PGType) = Expr s t type instance Col (Compose (Expr s) 'Nullable) (a :: PGType) = Expr s ('Nullable a) type instance Col (Compose (Expr s) 'NotNullable) (a :: PGType) = Expr s a type instance Col Interpret 'PGBigint = Int64 type instance Col Interpret 'PGBoolean = Bool type instance Col Interpret 'PGInteger = Int32 type instance Col Interpret 'PGReal = Float type instance Col Interpret 'PGText = Text type instance Col Interpret ('PGTimestamp 'WithoutTimeZone) = LocalTime type instance Col Interpret ('PGTimestamp 'WithTimeZone) = UTCTime type instance Col Interpret 'PGDouble = Double type instance Col Interpret ('PGNumeric p 0) = Fixed E0 type instance Col Interpret ('PGNumeric p 1) = Fixed E1 type instance Col Interpret ('PGNumeric p 2) = Fixed E2 type instance Col Interpret ('PGNumeric p 3) = Fixed E3 type instance Col Interpret ('PGNumeric p 6) = Fixed E6 type instance Col Interpret ('PGNumeric p 9) = Fixed E9 type instance Col Interpret 'PGBytea = ByteString type instance Col Interpret ('PGCharacter len) = Text type instance Col Interpret ('PGVarchar len) = Text type instance Col Interpret 'PGJSON = Aeson.Value type instance Col Interpret 'PGJSONB = Aeson.Value type instance Col Interpret 'PGUUID = UUID instance Lit 'PGBigint where lit = Expr . Op.unColumn . Op.pgInt8 instance Lit 'PGBoolean where lit = Expr . Op.unColumn . Op.pgBool instance Lit 'PGInteger where lit = Expr . Op.unColumn . Op.pgInt4 . fromIntegral instance Lit 'PGReal where lit = Expr . Op.unColumn . Op.pgDouble . realToFrac instance Lit 'PGText where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGCharacter n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGVarchar n) where lit = Expr . Op.unColumn . Op.pgStrictText instance Lit ('PGTimestamp 'WithoutTimeZone) where lit = Expr . Op.unColumn . Op.pgLocalTime instance Lit ('PGTimestamp 'WithTimeZone) where lit = Expr . Op.unColumn . Op.pgUTCTime instance Lit 'PGDouble where lit = Expr . Op.unColumn . Op.pgDouble instance Lit 'PGJSON where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGJSONB where lit = Expr . Op.unColumn . Op.pgValueJSON instance Lit 'PGUUID where lit = Expr . Op.unColumn . Op.pgUUID pgNow :: Expr s ('PGTimestamp 'WithTimeZone) pgNow = mapExpr Cast (lit (pack "now") :: Expr s 'PGText)
07225abbdde5efdab7f5f01795159d990b54ada8e08933fc15374a2288d92a96
vikram/lisplibraries
url.lisp
(in-package :weblocks-test) ;;; Test url-presentation render-view-field-value (deftest-html url-presentation-1 (render-view-field-value "www.hello.com" (make-instance 'url-presentation) (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Link")) (deftest-html url-presentation-2 (render-view-field-value "www.hello.com" (make-instance 'url-presentation :body "Foo") (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Foo")) (deftest-html url-presentation-3 (render-view-field-value "www.hello.com" (make-instance 'url-presentation :body (lambda (&rest args) (declare (ignore args)) (with-html "Bar"))) (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Bar"))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/test/views/types/presentations/url.lisp
lisp
Test url-presentation render-view-field-value
(in-package :weblocks-test) (deftest-html url-presentation-1 (render-view-field-value "www.hello.com" (make-instance 'url-presentation) (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Link")) (deftest-html url-presentation-2 (render-view-field-value "www.hello.com" (make-instance 'url-presentation :body "Foo") (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Foo")) (deftest-html url-presentation-3 (render-view-field-value "www.hello.com" (make-instance 'url-presentation :body (lambda (&rest args) (declare (ignore args)) (with-html "Bar"))) (make-instance 'data-view-field :slot-name 'foo) (make-instance 'data-view) nil *joe*) (:a :href "www.hello.com" :onclick "stopPropagation(event);" "Bar"))
7431d437265c72a7154c88684a6e964a30b26df9a8a1a264561cce9d9c452da8
anwarmamat/cmsc330spring19-public
lexer.mli
open SmallCTypes open TokenTypes val tokenize : string -> token list
null
https://raw.githubusercontent.com/anwarmamat/cmsc330spring19-public/98af1e8efc3d8756972731eaca19e55fe8febb69/project5/src/lexer.mli
ocaml
open SmallCTypes open TokenTypes val tokenize : string -> token list
f710ff254d8e9a67724db475b1a40b4e242bd267af821c886b81ec097000f4e7
ndmitchell/uniplate
SYB.hs
| SYB compatibility layer . This module serves as a drop - in replacement in some situations for some of the SYB operations . Users should also import " Data . Generics . Uniplate . Data " . SYB is described in the paper : \"Scrap your boilerplate : a practical design pattern for generic programming\ " by and . * < / > * < > * < > SYB compatibility layer. This module serves as a drop-in replacement in some situations for some of the SYB operations. Users should also import "Data.Generics.Uniplate.Data". SYB is described in the paper: \"Scrap your boilerplate: a practical design pattern for generic programming\" by Ralf Lammel and Simon Peyton Jones. * </> * <> * <> -} module Data.Generics.SYB where import Data.Generics.Uniplate.Operations -- | @gmapT == 'descend'@ gmapT :: Uniplate a => (a -> a) -> a -> a gmapT = descend -- | Use 'children' and 'foldl' gmapQl :: Uniplate a => (r -> r' -> r) -> r -> (a -> r') -> a -> r gmapQl combine zero op = foldl combine zero . map op . children -- | Use 'children' and 'foldr' gmapQr :: Uniplate a => (r' -> r -> r) -> r -> (a -> r') -> a -> r gmapQr combine zero op = foldr combine zero . map op . children -- | Use 'children' gmapQ :: Uniplate a => (a -> u) -> a -> [u] gmapQ f = map f . children -- | Use 'children' and '!!' gmapQi :: Uniplate a => Int -> (a -> u) -> a -> u gmapQi i f x = gmapQ f x !! i -- | @gmapM == 'descendM'@ gmapM :: (Uniplate a, Applicative m) => (a -> m a) -> a -> m a gmapM = descendM | = = ' id'@ mkT :: (a -> a) -> (a -> a) mkT = id | @everywhere = = ' transformBi'@ everywhere :: Biplate b a => (a -> a) -> b -> b everywhere = transformBi -- | @mkM == id@ mkM :: (a -> m a) -> a -> m a mkM = id -- | @everywhereM == 'transformBiM'@ everywhereM :: (Biplate b a, Monad m, Applicative m) => (a -> m a) -> b -> m b everywhereM = transformBiM -- | Only for use with 'everything' mkQ :: r -> (a -> r) -> (r, a -> r) mkQ = (,) -- | Use 'universe' or 'universeBi', perhaps followed by a fold. -- -- Not an exact equivalent to the SYB @everything@, as the -- operators may be applied in different orders. everything :: Biplate b a => (r -> r -> r) -> (r, a -> r) -> b -> r everything combine (nil, op) = foldl combine nil . map op . universeBi
null
https://raw.githubusercontent.com/ndmitchell/uniplate/7d3039606d7a083f6d77f9f960c919668788de91/Data/Generics/SYB.hs
haskell
| @gmapT == 'descend'@ | Use 'children' and 'foldl' | Use 'children' and 'foldr' | Use 'children' | Use 'children' and '!!' | @gmapM == 'descendM'@ | @mkM == id@ | @everywhereM == 'transformBiM'@ | Only for use with 'everything' | Use 'universe' or 'universeBi', perhaps followed by a fold. Not an exact equivalent to the SYB @everything@, as the operators may be applied in different orders.
| SYB compatibility layer . This module serves as a drop - in replacement in some situations for some of the SYB operations . Users should also import " Data . Generics . Uniplate . Data " . SYB is described in the paper : \"Scrap your boilerplate : a practical design pattern for generic programming\ " by and . * < / > * < > * < > SYB compatibility layer. This module serves as a drop-in replacement in some situations for some of the SYB operations. Users should also import "Data.Generics.Uniplate.Data". SYB is described in the paper: \"Scrap your boilerplate: a practical design pattern for generic programming\" by Ralf Lammel and Simon Peyton Jones. * </> * <> * <> -} module Data.Generics.SYB where import Data.Generics.Uniplate.Operations gmapT :: Uniplate a => (a -> a) -> a -> a gmapT = descend gmapQl :: Uniplate a => (r -> r' -> r) -> r -> (a -> r') -> a -> r gmapQl combine zero op = foldl combine zero . map op . children gmapQr :: Uniplate a => (r' -> r -> r) -> r -> (a -> r') -> a -> r gmapQr combine zero op = foldr combine zero . map op . children gmapQ :: Uniplate a => (a -> u) -> a -> [u] gmapQ f = map f . children gmapQi :: Uniplate a => Int -> (a -> u) -> a -> u gmapQi i f x = gmapQ f x !! i gmapM :: (Uniplate a, Applicative m) => (a -> m a) -> a -> m a gmapM = descendM | = = ' id'@ mkT :: (a -> a) -> (a -> a) mkT = id | @everywhere = = ' transformBi'@ everywhere :: Biplate b a => (a -> a) -> b -> b everywhere = transformBi mkM :: (a -> m a) -> a -> m a mkM = id everywhereM :: (Biplate b a, Monad m, Applicative m) => (a -> m a) -> b -> m b everywhereM = transformBiM mkQ :: r -> (a -> r) -> (r, a -> r) mkQ = (,) everything :: Biplate b a => (r -> r -> r) -> (r, a -> r) -> b -> r everything combine (nil, op) = foldl combine nil . map op . universeBi
034a5077dd1331d4eb47d2672be26c9185c291d2c2bbb8f83315479a68c03f0a
msakai/data-interval
Base.hs
# OPTIONS_GHC -Wall # # LANGUAGE CPP , LambdaCase , ScopedTypeVariables , TypeFamilies , DeriveDataTypeable , MultiWayIf , # LANGUAGE Trustworthy # #if __GLASGOW_HASKELL__ >= 708 # LANGUAGE RoleAnnotations # #endif ----------------------------------------------------------------------------- -- | Module : Data . . Base Copyright : ( c ) 2016 -- License : BSD-style -- -- Maintainer : -- Stability : provisional Portability : non - portable ( CPP , ScopedTypeVariables , TypeFamilies , DeriveDataTypeable , MultiWayIf , ) -- -- Interval datatype and interval arithmetic. -- ----------------------------------------------------------------------------- module Data.IntervalMap.Base ( * type IntervalMap (..) , module Data.ExtendedReal -- * Operators , (!) , (\\) -- * Query , null , member , notMember , lookup , findWithDefault , span -- * Construction , whole , empty , singleton -- ** Insertion , insert , insertWith -- ** Delete\/Update , delete , adjust , update , alter -- * Combine , union , unionWith , unions , unionsWith , intersection , intersectionWith , difference -- * Traversal , map , mapKeysMonotonic -- * Conversion , elems , keys , assocs , keysSet -- ** List , fromList , fromListWith , toList -- ** Ordered List , toAscList , toDescList -- * Filter , filter , split -- * Submap , isSubmapOf , isSubmapOfBy , isProperSubmapOf , isProperSubmapOfBy ) where import Prelude hiding (null, lookup, map, filter, span, and) import Control.DeepSeq import Data.Data import Data.ExtendedReal import Data.Hashable import Data.Foldable hiding (null, toList) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import qualified Data.Semigroup as Semigroup import Data.Interval (Interval) import qualified Data.Interval as Interval import Data.IntervalSet (IntervalSet) import qualified Data.IntervalSet as IntervalSet #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) import Data.Traversable (Traversable(..)) #endif #if __GLASGOW_HASKELL__ < 804 import Data.Monoid (Monoid(..)) #endif #if __GLASGOW_HASKELL__ >= 708 import qualified GHC.Exts as GHCExts #endif -- ------------------------------------------------------------------------ The type -- | A Map from non-empty, disjoint intervals over k to values a. -- Unlike ' IntervalSet ' , ' ' never merge adjacent mappings , -- even if adjacent intervals are connected and mapped to the same value. newtype IntervalMap r a = IntervalMap (Map (LB r) (Interval r, a)) deriving (Eq, Typeable) #if __GLASGOW_HASKELL__ >= 708 type role IntervalMap nominal representational #endif instance (Ord k, Show k, Show a) => Show (IntervalMap k a) where showsPrec p (IntervalMap m) = showParen (p > appPrec) $ showString "fromList " . showsPrec (appPrec+1) (Map.elems m) instance (Ord k, Read k, Read a) => Read (IntervalMap k a) where readsPrec p = (readParen (p > appPrec) $ \s0 -> do ("fromList",s1) <- lex s0 (xs,s2) <- readsPrec (appPrec+1) s1 return (fromList xs, s2)) appPrec :: Int appPrec = 10 -- This instance preserves data abstraction at the cost of inefficiency. -- We provide limited reflection services for the sake of data abstraction. instance (Data k, Data a, Ord k) => Data (IntervalMap k a) where gfoldl k z x = z fromList `k` toList x toConstr _ = fromListConstr gunfold k z c = case constrIndex c of 1 -> k (z fromList) _ -> error "gunfold" dataTypeOf _ = mapDataType dataCast1 f = gcast1 f fromListConstr :: Constr fromListConstr = mkConstr mapDataType "fromList" [] Prefix mapDataType :: DataType mapDataType = mkDataType "Data.IntervalMap.Base.IntervalMap" [fromListConstr] instance (NFData k, NFData a) => NFData (IntervalMap k a) where rnf (IntervalMap m) = rnf m instance (Hashable k, Hashable a) => Hashable (IntervalMap k a) where hashWithSalt s m = hashWithSalt s (toList m) instance Ord k => Monoid (IntervalMap k a) where mempty = empty mappend = union mconcat = unions instance Ord k => Semigroup.Semigroup (IntervalMap k a) where (<>) = union #if !defined(VERSION_semigroups) stimes = Semigroup.stimesIdempotentMonoid #else #if MIN_VERSION_semigroups(0,17,0) stimes = Semigroup.stimesIdempotentMonoid #else times1p _ a = a #endif #endif #if __GLASGOW_HASKELL__ >= 708 instance Ord k => GHCExts.IsList (IntervalMap k a) where type Item (IntervalMap k a) = (Interval k, a) fromList = fromList toList = toList #endif -- ------------------------------------------------------------------------ newtype LB r = LB (Extended r, Interval.Boundary) deriving (Eq, NFData, Typeable) instance Ord r => Ord (LB r) where compare (LB (lb1, lb1in)) (LB (lb2, lb2in)) = -- inclusive lower endpoint shuold be considered smaller (lb1 `compare` lb2) `mappend` (lb2in `compare` lb1in) -- ------------------------------------------------------------------------ Operators infixl 9 !,\\ -- -- | Find the value at a key. Calls 'error' when the element can not be found. (!) :: Ord k => IntervalMap k a -> k -> a IntervalMap m ! k = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> a _ -> error "IntervalMap.!: given key is not an element in the map" -- | Same as 'difference'. (\\) :: Ord k => IntervalMap k a -> IntervalMap k b -> IntervalMap k a m1 \\ m2 = difference m1 m2 -- ------------------------------------------------------------------------ -- Query -- | Is the map empty? null :: Ord k => IntervalMap k a -> Bool null (IntervalMap m) = Map.null m | Is the key a member of the map ? See also ' ' . member :: Ord k => k -> IntervalMap k a -> Bool member k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, _)) -> k `Interval.member` i Nothing -> False -- | Is the key not a member of the map? See also 'member'. notMember :: Ord k => k -> IntervalMap k a -> Bool notMember k m = not $ member k m -- | Lookup the value at a key in the map. -- -- The function will return the corresponding value as @('Just' value)@, -- or 'Nothing' if the key isn't in the map. lookup :: Ord k => k -> IntervalMap k a -> Maybe a lookup k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> Just a _ -> Nothing | The expression ' def k map)@ returns the value at key @k@ or returns default value -- when the key is not in the map. findWithDefault :: Ord k => a -> k -> IntervalMap k a -> a findWithDefault def k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> a _ -> def lookupInterval :: Ord k => Interval k -> IntervalMap k a -> Maybe a lookupInterval i (IntervalMap m) = case Map.lookupLE (LB (Interval.lowerBound' i)) m of Just (_, (j, a)) | i `Interval.isSubsetOf` j -> Just a _ -> Nothing -- | convex hull of key intervals. span :: Ord k => IntervalMap k a -> Interval k span = IntervalSet.span . keysSet -- ------------------------------------------------------------------------ -- Construction -- | The empty map. empty :: Ord k => IntervalMap k a empty = IntervalMap Map.empty -- | The map that maps whole range of k to a. whole :: Ord k => a -> IntervalMap k a whole a = IntervalMap $ Map.singleton (LB (Interval.lowerBound' i)) (i, a) where i = Interval.whole -- | A map with a single interval. singleton :: Ord k => Interval k -> a -> IntervalMap k a singleton i a | Interval.null i = empty | otherwise = IntervalMap $ Map.singleton (LB (Interval.lowerBound' i)) (i, a) -- ------------------------------------------------------------------------ -- Insertion -- | insert a new key and value in the map. -- If the key is already present in the map, the associated value is -- replaced with the supplied value. insert :: Ord k => Interval k -> a -> IntervalMap k a -> IntervalMap k a insert i _ m | Interval.null i = m insert i a m = case split i m of (IntervalMap m1, _, IntervalMap m2) -> IntervalMap $ Map.union m1 (Map.insert (LB (Interval.lowerBound' i)) (i,a) m2) -- | Insert with a function, combining new value and old value. @'insertWith ' f key value mp@ will insert the pair ( interval , value ) into @mp@. -- If the interval overlaps with existing entries, the value for the entry is replace -- with @(f new_value old_value)@. insertWith :: Ord k => (a -> a -> a) -> Interval k -> a -> IntervalMap k a -> IntervalMap k a insertWith _ i _ m | Interval.null i = m insertWith f i a m = alter g i m where g Nothing = Just a g (Just a') = Just $ f a a' -- ------------------------------------------------------------------------ -- Delete/Update -- | Delete an interval and its value from the map. -- When the interval does not overlap with the map, the original map is returned. delete :: Ord k => Interval k -> IntervalMap k a -> IntervalMap k a delete i m | Interval.null i = m delete i m = case split i m of (IntervalMap m1, _, IntervalMap m2) -> IntervalMap $ Map.union m1 m2 -- | Update a value at a specific interval with the result of the provided function. -- When the interval does not overlatp with the map, the original map is returned. adjust :: Ord k => (a -> a) -> Interval k -> IntervalMap k a -> IntervalMap k a adjust f = update (Just . f) | The expression ( ' f i map@ ) updates the value @x@ at @i@ ( if it is in the map ) . If ( @f ) is ' Nothing ' , the element is deleted . If it is ( @'Just ' y@ ) , the key @i@ is bound to the new value @y@. update :: Ord k => (a -> Maybe a) -> Interval k -> IntervalMap k a -> IntervalMap k a update _ i m | Interval.null i = m update f i m = case split i m of (IntervalMap m1, IntervalMap m2, IntervalMap m3) -> IntervalMap $ Map.unions [m1, Map.mapMaybe (\(j,a) -> (\b -> (j,b)) <$> f a) m2, m3] | The expression ( @'alter ' f i map@ ) alters the value @x@ at @i@ , or absence thereof . ' alter ' can be used to insert , delete , or update a value in a ' ' . alter :: Ord k => (Maybe a -> Maybe a) -> Interval k -> IntervalMap k a -> IntervalMap k a alter _ i m | Interval.null i = m alter f i m = case split i m of (IntervalMap m1, IntervalMap m2, IntervalMap m3) -> let m2' = Map.mapMaybe (\(j,a) -> (\b -> (j,b)) <$> f (Just a)) m2 js = IntervalSet.singleton i `IntervalSet.difference` keysSet (IntervalMap m2) IntervalMap m2'' = case f Nothing of Nothing -> empty Just a -> fromList [(j,a) | j <- IntervalSet.toList js] in IntervalMap $ Map.unions [m1, m2', m2'', m3] -- ------------------------------------------------------------------------ Combine | The expression ( @'union ' t1 t2@ ) takes the left - biased union of @t1@ and @t2@. It prefers @t1@ when overlapping keys are encountered , union :: Ord k => IntervalMap k a -> IntervalMap k a -> IntervalMap k a union m1 m2 = foldl' (\m (i,a) -> insert i a m) m2 (toList m1) -- | Union with a combining function. unionWith :: Ord k => (a -> a -> a) -> IntervalMap k a -> IntervalMap k a -> IntervalMap k a unionWith f m1 m2 = foldl' (\m (i,a) -> insertWith f i a m) m2 (toList m1) -- | The union of a list of maps: -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@). unions :: Ord k => [IntervalMap k a] -> IntervalMap k a unions = foldl' union empty -- | The union of a list of maps, with a combining operation: -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@). unionsWith :: Ord k => (a -> a -> a) -> [IntervalMap k a] -> IntervalMap k a unionsWith f = foldl' (unionWith f) empty | Return elements of the first map not existing in the second map . difference :: Ord k => IntervalMap k a -> IntervalMap k b -> IntervalMap k a difference m1 m2 = foldl' (\m i -> delete i m) m1 (IntervalSet.toList (keysSet m2)) | Intersection of two maps . Return data in the first map for the keys existing in both maps . intersection :: Ord k => IntervalMap k a -> IntervalMap k a -> IntervalMap k a intersection = intersectionWith const -- | Intersection with a combining function. intersectionWith :: Ord k => (a -> b -> c) -> IntervalMap k a -> IntervalMap k b -> IntervalMap k c intersectionWith f im1@(IntervalMap m1) im2@(IntervalMap m2) | Map.size m1 >= Map.size m2 = g f im1 im2 | otherwise = g (flip f) im2 im1 where g :: Ord k => (a -> b -> c) -> IntervalMap k a -> IntervalMap k b -> IntervalMap k c g h jm1 (IntervalMap m3) = IntervalMap $ Map.unions $ go jm1 (Map.elems m3) where go _ [] = [] go im ((i,b) : xs) = case split i im of (_, IntervalMap m, jm2) -> Map.map (\(j, a) -> (j, h a b)) m : go jm2 xs -- ------------------------------------------------------------------------ -- Traversal instance Ord k => Functor (IntervalMap k) where fmap = map instance Ord k => Foldable (IntervalMap k) where foldMap f (IntervalMap m) = foldMap (\(_,a) -> f a) m instance Ord k => Traversable (IntervalMap k) where traverse f (IntervalMap m) = IntervalMap <$> traverse (\(i,a) -> (\b -> (i,b)) <$> f a) m -- | Map a function over all values in the map. map :: (a -> b) -> IntervalMap k a -> IntervalMap k b map f (IntervalMap m) = IntervalMap $ Map.map (\(i, a) -> (i, f a)) m | @'mapKeysMonotonic ' f s@ is the map obtained by applying @f@ to each key of @s@. @f@ must be strictly monotonic . -- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@. mapKeysMonotonic :: forall k1 k2 a. (Ord k1, Ord k2) => (k1 -> k2) -> IntervalMap k1 a -> IntervalMap k2 a mapKeysMonotonic f = fromList . fmap g . toList where g :: (Interval k1, a) -> (Interval k2, a) g (i, a) = (Interval.mapMonotonic f i, a) -- ------------------------------------------------------------------------ -- | Return all elements of the map in the ascending order of their keys. elems :: IntervalMap k a -> [a] elems (IntervalMap m) = [a | (_,a) <- Map.elems m] -- | Return all keys of the map in ascending order. Subject to list keys :: IntervalMap k a -> [Interval k] keys (IntervalMap m) = [i | (i,_) <- Map.elems m] -- | An alias for 'toAscList'. Return all key\/value pairs in the map -- in ascending key order. assocs :: IntervalMap k a -> [(Interval k, a)] assocs = toAscList -- | The set of all keys of the map. keysSet :: Ord k => IntervalMap k a -> IntervalSet k keysSet (IntervalMap m) = IntervalSet.fromAscList [i | (i,_) <- Map.elems m] -- | Convert the map to a list of key\/value pairs. toList :: IntervalMap k a -> [(Interval k, a)] toList = toAscList -- | Convert the map to a list of key/value pairs where the keys are in ascending order. toAscList :: IntervalMap k a -> [(Interval k, a)] toAscList (IntervalMap m) = Map.elems m -- | Convert the map to a list of key/value pairs where the keys are in descending order. toDescList :: IntervalMap k a -> [(Interval k, a)] toDescList (IntervalMap m) = fmap snd $ Map.toDescList m -- | Build a map from a list of key\/value pairs. If the list contains more than one value for the same key , the last value -- for the key is retained. fromList :: Ord k => [(Interval k, a)] -> IntervalMap k a fromList = foldl' (\m (i,a) -> insert i a m) empty -- | Build a map from a list of key\/value pairs with a combining function. fromListWith :: Ord k => (a -> a -> a) -> [(Interval k, a)] -> IntervalMap k a fromListWith f = foldl' (\m (i,a) -> insertWith f i a m) empty -- ------------------------------------------------------------------------ -- Filter -- | Filter all values that satisfy some predicate. filter :: Ord k => (a -> Bool) -> IntervalMap k a -> IntervalMap k a filter p (IntervalMap m) = IntervalMap $ Map.filter (\(_,a) -> p a) m | The expression ( ' i map@ ) is a triple @(map1,map2,map3)@ where the keys in @map1@ are smaller than @i@ , the keys in @map2@ are included in @i@ , and the keys in @map3@ are larger than split :: Ord k => Interval k -> IntervalMap k a -> (IntervalMap k a, IntervalMap k a, IntervalMap k a) split i (IntervalMap m) = case splitLookupLE (LB (Interval.lowerBound' i)) m of (smaller, m1, xs) -> case splitLookupLE (LB (Interval.upperBound i, Interval.Closed)) xs of (middle, m2, larger) -> ( IntervalMap $ case m1 of Nothing -> Map.empty Just (j,b) -> let k = Interval.intersection (upTo i) j in if Interval.null k then smaller else Map.insert (LB (Interval.lowerBound' k)) (k,b) smaller , IntervalMap $ Map.unions $ middle : [ Map.singleton (LB (Interval.lowerBound' k)) (k, b) | (j, b) <- maybeToList m1 ++ maybeToList m2 , let k = Interval.intersection i j , not (Interval.null k) ] , IntervalMap $ Map.unions $ larger : [ Map.singleton (LB (Interval.lowerBound' k)) (k, b) | (j, b) <- maybeToList m1 ++ maybeToList m2 , let k = Interval.intersection (downTo i) j , not (Interval.null k) ] ) -- ------------------------------------------------------------------------ Submap -- | This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@). isSubmapOf :: (Ord k, Eq a) => IntervalMap k a -> IntervalMap k a -> Bool isSubmapOf = isSubmapOfBy (==) -- | The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if all keys in @t1@ are in tree @t2@ , and when returns ' True ' when -- applied to their respective values. isSubmapOfBy :: Ord k => (a -> b -> Bool) -> IntervalMap k a -> IntervalMap k b -> Bool isSubmapOfBy f m1 m2 = and $ [ case lookupInterval i m2 of Nothing -> False Just b -> f a b | (i,a) <- toList m1 ] -- | Is this a proper submap? (ie. a submap but not equal). -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@). isProperSubmapOf :: (Ord k, Eq a) => IntervalMap k a -> IntervalMap k a -> Bool isProperSubmapOf = isProperSubmapOfBy (==) -- | Is this a proper submap? (ie. a submap but not equal). -- The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when @m1@ and @m2@ are not equal , all keys in @m1@ are in @m2@ , and when returns ' True ' when -- applied to their respective values. isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> IntervalMap k a -> IntervalMap k b -> Bool isProperSubmapOfBy f m1 m2 = isSubmapOfBy f m1 m2 && keysSet m1 `IntervalSet.isProperSubsetOf` keysSet m2 -- ------------------------------------------------------------------------ splitLookupLE :: Ord k => k -> Map k v -> (Map k v, Maybe v, Map k v) splitLookupLE k m = case Map.splitLookup k m of (smaller, Just v, larger) -> (smaller, Just v, larger) (smaller, Nothing, larger) -> case Map.maxView smaller of Just (v, smaller') -> (smaller', Just v, larger) Nothing -> (smaller, Nothing, larger) upTo :: Ord r => Interval r -> Interval r upTo i = case Interval.lowerBound' i of (NegInf, _) -> Interval.empty (PosInf, _) -> Interval.whole (Finite lb, incl) -> Interval.interval (NegInf, Interval.Open) (Finite lb, notB incl) downTo :: Ord r => Interval r -> Interval r downTo i = case Interval.upperBound' i of (PosInf, _) -> Interval.empty (NegInf, _) -> Interval.whole (Finite ub, incl) -> Interval.interval (Finite ub, notB incl) (PosInf, Interval.Open) notB :: Interval.Boundary -> Interval.Boundary notB = \case Interval.Open -> Interval.Closed Interval.Closed -> Interval.Open
null
https://raw.githubusercontent.com/msakai/data-interval/8c7596ff71fd2055b006c3bbf8c6765b00ebeabe/src/Data/IntervalMap/Base.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : provisional Interval datatype and interval arithmetic. --------------------------------------------------------------------------- * Operators * Query * Construction ** Insertion ** Delete\/Update * Combine * Traversal * Conversion ** List ** Ordered List * Filter * Submap ------------------------------------------------------------------------ | A Map from non-empty, disjoint intervals over k to values a. even if adjacent intervals are connected and mapped to the same value. This instance preserves data abstraction at the cost of inefficiency. We provide limited reflection services for the sake of data abstraction. ------------------------------------------------------------------------ inclusive lower endpoint shuold be considered smaller ------------------------------------------------------------------------ | Find the value at a key. Calls 'error' when the element can not be found. | Same as 'difference'. ------------------------------------------------------------------------ Query | Is the map empty? | Is the key not a member of the map? See also 'member'. | Lookup the value at a key in the map. The function will return the corresponding value as @('Just' value)@, or 'Nothing' if the key isn't in the map. when the key is not in the map. | convex hull of key intervals. ------------------------------------------------------------------------ Construction | The empty map. | The map that maps whole range of k to a. | A map with a single interval. ------------------------------------------------------------------------ Insertion | insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value. | Insert with a function, combining new value and old value. If the interval overlaps with existing entries, the value for the entry is replace with @(f new_value old_value)@. ------------------------------------------------------------------------ Delete/Update | Delete an interval and its value from the map. When the interval does not overlap with the map, the original map is returned. | Update a value at a specific interval with the result of the provided function. When the interval does not overlatp with the map, the original map is returned. ------------------------------------------------------------------------ | Union with a combining function. | The union of a list of maps: (@'unions' == 'Prelude.foldl' 'union' 'empty'@). | The union of a list of maps, with a combining operation: (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@). | Intersection with a combining function. ------------------------------------------------------------------------ Traversal | Map a function over all values in the map. That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@. ------------------------------------------------------------------------ | Return all elements of the map in the ascending order of their keys. | Return all keys of the map in ascending order. Subject to list | An alias for 'toAscList'. Return all key\/value pairs in the map in ascending key order. | The set of all keys of the map. | Convert the map to a list of key\/value pairs. | Convert the map to a list of key/value pairs where the keys are in ascending order. | Convert the map to a list of key/value pairs where the keys are in descending order. | Build a map from a list of key\/value pairs. for the key is retained. | Build a map from a list of key\/value pairs with a combining function. ------------------------------------------------------------------------ Filter | Filter all values that satisfy some predicate. ------------------------------------------------------------------------ | This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@). | The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if applied to their respective values. | Is this a proper submap? (ie. a submap but not equal). Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@). | Is this a proper submap? (ie. a submap but not equal). The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when applied to their respective values. ------------------------------------------------------------------------
# OPTIONS_GHC -Wall # # LANGUAGE CPP , LambdaCase , ScopedTypeVariables , TypeFamilies , DeriveDataTypeable , MultiWayIf , # LANGUAGE Trustworthy # #if __GLASGOW_HASKELL__ >= 708 # LANGUAGE RoleAnnotations # #endif Module : Data . . Base Copyright : ( c ) 2016 Portability : non - portable ( CPP , ScopedTypeVariables , TypeFamilies , DeriveDataTypeable , MultiWayIf , ) module Data.IntervalMap.Base ( * type IntervalMap (..) , module Data.ExtendedReal , (!) , (\\) , null , member , notMember , lookup , findWithDefault , span , whole , empty , singleton , insert , insertWith , delete , adjust , update , alter , union , unionWith , unions , unionsWith , intersection , intersectionWith , difference , map , mapKeysMonotonic , elems , keys , assocs , keysSet , fromList , fromListWith , toList , toAscList , toDescList , filter , split , isSubmapOf , isSubmapOfBy , isProperSubmapOf , isProperSubmapOfBy ) where import Prelude hiding (null, lookup, map, filter, span, and) import Control.DeepSeq import Data.Data import Data.ExtendedReal import Data.Hashable import Data.Foldable hiding (null, toList) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import qualified Data.Semigroup as Semigroup import Data.Interval (Interval) import qualified Data.Interval as Interval import Data.IntervalSet (IntervalSet) import qualified Data.IntervalSet as IntervalSet #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) import Data.Traversable (Traversable(..)) #endif #if __GLASGOW_HASKELL__ < 804 import Data.Monoid (Monoid(..)) #endif #if __GLASGOW_HASKELL__ >= 708 import qualified GHC.Exts as GHCExts #endif The type Unlike ' IntervalSet ' , ' ' never merge adjacent mappings , newtype IntervalMap r a = IntervalMap (Map (LB r) (Interval r, a)) deriving (Eq, Typeable) #if __GLASGOW_HASKELL__ >= 708 type role IntervalMap nominal representational #endif instance (Ord k, Show k, Show a) => Show (IntervalMap k a) where showsPrec p (IntervalMap m) = showParen (p > appPrec) $ showString "fromList " . showsPrec (appPrec+1) (Map.elems m) instance (Ord k, Read k, Read a) => Read (IntervalMap k a) where readsPrec p = (readParen (p > appPrec) $ \s0 -> do ("fromList",s1) <- lex s0 (xs,s2) <- readsPrec (appPrec+1) s1 return (fromList xs, s2)) appPrec :: Int appPrec = 10 instance (Data k, Data a, Ord k) => Data (IntervalMap k a) where gfoldl k z x = z fromList `k` toList x toConstr _ = fromListConstr gunfold k z c = case constrIndex c of 1 -> k (z fromList) _ -> error "gunfold" dataTypeOf _ = mapDataType dataCast1 f = gcast1 f fromListConstr :: Constr fromListConstr = mkConstr mapDataType "fromList" [] Prefix mapDataType :: DataType mapDataType = mkDataType "Data.IntervalMap.Base.IntervalMap" [fromListConstr] instance (NFData k, NFData a) => NFData (IntervalMap k a) where rnf (IntervalMap m) = rnf m instance (Hashable k, Hashable a) => Hashable (IntervalMap k a) where hashWithSalt s m = hashWithSalt s (toList m) instance Ord k => Monoid (IntervalMap k a) where mempty = empty mappend = union mconcat = unions instance Ord k => Semigroup.Semigroup (IntervalMap k a) where (<>) = union #if !defined(VERSION_semigroups) stimes = Semigroup.stimesIdempotentMonoid #else #if MIN_VERSION_semigroups(0,17,0) stimes = Semigroup.stimesIdempotentMonoid #else times1p _ a = a #endif #endif #if __GLASGOW_HASKELL__ >= 708 instance Ord k => GHCExts.IsList (IntervalMap k a) where type Item (IntervalMap k a) = (Interval k, a) fromList = fromList toList = toList #endif newtype LB r = LB (Extended r, Interval.Boundary) deriving (Eq, NFData, Typeable) instance Ord r => Ord (LB r) where compare (LB (lb1, lb1in)) (LB (lb2, lb2in)) = (lb1 `compare` lb2) `mappend` (lb2in `compare` lb1in) Operators (!) :: Ord k => IntervalMap k a -> k -> a IntervalMap m ! k = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> a _ -> error "IntervalMap.!: given key is not an element in the map" (\\) :: Ord k => IntervalMap k a -> IntervalMap k b -> IntervalMap k a m1 \\ m2 = difference m1 m2 null :: Ord k => IntervalMap k a -> Bool null (IntervalMap m) = Map.null m | Is the key a member of the map ? See also ' ' . member :: Ord k => k -> IntervalMap k a -> Bool member k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, _)) -> k `Interval.member` i Nothing -> False notMember :: Ord k => k -> IntervalMap k a -> Bool notMember k m = not $ member k m lookup :: Ord k => k -> IntervalMap k a -> Maybe a lookup k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> Just a _ -> Nothing | The expression ' def k map)@ returns the value at key @k@ or returns default value findWithDefault :: Ord k => a -> k -> IntervalMap k a -> a findWithDefault def k (IntervalMap m) = case Map.lookupLE (LB (Finite k, Interval.Closed)) m of Just (_, (i, a)) | k `Interval.member` i -> a _ -> def lookupInterval :: Ord k => Interval k -> IntervalMap k a -> Maybe a lookupInterval i (IntervalMap m) = case Map.lookupLE (LB (Interval.lowerBound' i)) m of Just (_, (j, a)) | i `Interval.isSubsetOf` j -> Just a _ -> Nothing span :: Ord k => IntervalMap k a -> Interval k span = IntervalSet.span . keysSet empty :: Ord k => IntervalMap k a empty = IntervalMap Map.empty whole :: Ord k => a -> IntervalMap k a whole a = IntervalMap $ Map.singleton (LB (Interval.lowerBound' i)) (i, a) where i = Interval.whole singleton :: Ord k => Interval k -> a -> IntervalMap k a singleton i a | Interval.null i = empty | otherwise = IntervalMap $ Map.singleton (LB (Interval.lowerBound' i)) (i, a) insert :: Ord k => Interval k -> a -> IntervalMap k a -> IntervalMap k a insert i _ m | Interval.null i = m insert i a m = case split i m of (IntervalMap m1, _, IntervalMap m2) -> IntervalMap $ Map.union m1 (Map.insert (LB (Interval.lowerBound' i)) (i,a) m2) @'insertWith ' f key value mp@ will insert the pair ( interval , value ) into @mp@. insertWith :: Ord k => (a -> a -> a) -> Interval k -> a -> IntervalMap k a -> IntervalMap k a insertWith _ i _ m | Interval.null i = m insertWith f i a m = alter g i m where g Nothing = Just a g (Just a') = Just $ f a a' delete :: Ord k => Interval k -> IntervalMap k a -> IntervalMap k a delete i m | Interval.null i = m delete i m = case split i m of (IntervalMap m1, _, IntervalMap m2) -> IntervalMap $ Map.union m1 m2 adjust :: Ord k => (a -> a) -> Interval k -> IntervalMap k a -> IntervalMap k a adjust f = update (Just . f) | The expression ( ' f i map@ ) updates the value @x@ at @i@ ( if it is in the map ) . If ( @f ) is ' Nothing ' , the element is deleted . If it is ( @'Just ' y@ ) , the key @i@ is bound to the new value @y@. update :: Ord k => (a -> Maybe a) -> Interval k -> IntervalMap k a -> IntervalMap k a update _ i m | Interval.null i = m update f i m = case split i m of (IntervalMap m1, IntervalMap m2, IntervalMap m3) -> IntervalMap $ Map.unions [m1, Map.mapMaybe (\(j,a) -> (\b -> (j,b)) <$> f a) m2, m3] | The expression ( @'alter ' f i map@ ) alters the value @x@ at @i@ , or absence thereof . ' alter ' can be used to insert , delete , or update a value in a ' ' . alter :: Ord k => (Maybe a -> Maybe a) -> Interval k -> IntervalMap k a -> IntervalMap k a alter _ i m | Interval.null i = m alter f i m = case split i m of (IntervalMap m1, IntervalMap m2, IntervalMap m3) -> let m2' = Map.mapMaybe (\(j,a) -> (\b -> (j,b)) <$> f (Just a)) m2 js = IntervalSet.singleton i `IntervalSet.difference` keysSet (IntervalMap m2) IntervalMap m2'' = case f Nothing of Nothing -> empty Just a -> fromList [(j,a) | j <- IntervalSet.toList js] in IntervalMap $ Map.unions [m1, m2', m2'', m3] Combine | The expression ( @'union ' t1 t2@ ) takes the left - biased union of @t1@ and @t2@. It prefers @t1@ when overlapping keys are encountered , union :: Ord k => IntervalMap k a -> IntervalMap k a -> IntervalMap k a union m1 m2 = foldl' (\m (i,a) -> insert i a m) m2 (toList m1) unionWith :: Ord k => (a -> a -> a) -> IntervalMap k a -> IntervalMap k a -> IntervalMap k a unionWith f m1 m2 = foldl' (\m (i,a) -> insertWith f i a m) m2 (toList m1) unions :: Ord k => [IntervalMap k a] -> IntervalMap k a unions = foldl' union empty unionsWith :: Ord k => (a -> a -> a) -> [IntervalMap k a] -> IntervalMap k a unionsWith f = foldl' (unionWith f) empty | Return elements of the first map not existing in the second map . difference :: Ord k => IntervalMap k a -> IntervalMap k b -> IntervalMap k a difference m1 m2 = foldl' (\m i -> delete i m) m1 (IntervalSet.toList (keysSet m2)) | Intersection of two maps . Return data in the first map for the keys existing in both maps . intersection :: Ord k => IntervalMap k a -> IntervalMap k a -> IntervalMap k a intersection = intersectionWith const intersectionWith :: Ord k => (a -> b -> c) -> IntervalMap k a -> IntervalMap k b -> IntervalMap k c intersectionWith f im1@(IntervalMap m1) im2@(IntervalMap m2) | Map.size m1 >= Map.size m2 = g f im1 im2 | otherwise = g (flip f) im2 im1 where g :: Ord k => (a -> b -> c) -> IntervalMap k a -> IntervalMap k b -> IntervalMap k c g h jm1 (IntervalMap m3) = IntervalMap $ Map.unions $ go jm1 (Map.elems m3) where go _ [] = [] go im ((i,b) : xs) = case split i im of (_, IntervalMap m, jm2) -> Map.map (\(j, a) -> (j, h a b)) m : go jm2 xs instance Ord k => Functor (IntervalMap k) where fmap = map instance Ord k => Foldable (IntervalMap k) where foldMap f (IntervalMap m) = foldMap (\(_,a) -> f a) m instance Ord k => Traversable (IntervalMap k) where traverse f (IntervalMap m) = IntervalMap <$> traverse (\(i,a) -> (\b -> (i,b)) <$> f a) m map :: (a -> b) -> IntervalMap k a -> IntervalMap k b map f (IntervalMap m) = IntervalMap $ Map.map (\(i, a) -> (i, f a)) m | @'mapKeysMonotonic ' f s@ is the map obtained by applying @f@ to each key of @s@. @f@ must be strictly monotonic . mapKeysMonotonic :: forall k1 k2 a. (Ord k1, Ord k2) => (k1 -> k2) -> IntervalMap k1 a -> IntervalMap k2 a mapKeysMonotonic f = fromList . fmap g . toList where g :: (Interval k1, a) -> (Interval k2, a) g (i, a) = (Interval.mapMonotonic f i, a) elems :: IntervalMap k a -> [a] elems (IntervalMap m) = [a | (_,a) <- Map.elems m] keys :: IntervalMap k a -> [Interval k] keys (IntervalMap m) = [i | (i,_) <- Map.elems m] assocs :: IntervalMap k a -> [(Interval k, a)] assocs = toAscList keysSet :: Ord k => IntervalMap k a -> IntervalSet k keysSet (IntervalMap m) = IntervalSet.fromAscList [i | (i,_) <- Map.elems m] toList :: IntervalMap k a -> [(Interval k, a)] toList = toAscList toAscList :: IntervalMap k a -> [(Interval k, a)] toAscList (IntervalMap m) = Map.elems m toDescList :: IntervalMap k a -> [(Interval k, a)] toDescList (IntervalMap m) = fmap snd $ Map.toDescList m If the list contains more than one value for the same key , the last value fromList :: Ord k => [(Interval k, a)] -> IntervalMap k a fromList = foldl' (\m (i,a) -> insert i a m) empty fromListWith :: Ord k => (a -> a -> a) -> [(Interval k, a)] -> IntervalMap k a fromListWith f = foldl' (\m (i,a) -> insertWith f i a m) empty filter :: Ord k => (a -> Bool) -> IntervalMap k a -> IntervalMap k a filter p (IntervalMap m) = IntervalMap $ Map.filter (\(_,a) -> p a) m | The expression ( ' i map@ ) is a triple @(map1,map2,map3)@ where the keys in @map1@ are smaller than @i@ , the keys in @map2@ are included in @i@ , and the keys in @map3@ are larger than split :: Ord k => Interval k -> IntervalMap k a -> (IntervalMap k a, IntervalMap k a, IntervalMap k a) split i (IntervalMap m) = case splitLookupLE (LB (Interval.lowerBound' i)) m of (smaller, m1, xs) -> case splitLookupLE (LB (Interval.upperBound i, Interval.Closed)) xs of (middle, m2, larger) -> ( IntervalMap $ case m1 of Nothing -> Map.empty Just (j,b) -> let k = Interval.intersection (upTo i) j in if Interval.null k then smaller else Map.insert (LB (Interval.lowerBound' k)) (k,b) smaller , IntervalMap $ Map.unions $ middle : [ Map.singleton (LB (Interval.lowerBound' k)) (k, b) | (j, b) <- maybeToList m1 ++ maybeToList m2 , let k = Interval.intersection i j , not (Interval.null k) ] , IntervalMap $ Map.unions $ larger : [ Map.singleton (LB (Interval.lowerBound' k)) (k, b) | (j, b) <- maybeToList m1 ++ maybeToList m2 , let k = Interval.intersection (downTo i) j , not (Interval.null k) ] ) Submap isSubmapOf :: (Ord k, Eq a) => IntervalMap k a -> IntervalMap k a -> Bool isSubmapOf = isSubmapOfBy (==) all keys in @t1@ are in tree @t2@ , and when returns ' True ' when isSubmapOfBy :: Ord k => (a -> b -> Bool) -> IntervalMap k a -> IntervalMap k b -> Bool isSubmapOfBy f m1 m2 = and $ [ case lookupInterval i m2 of Nothing -> False Just b -> f a b | (i,a) <- toList m1 ] isProperSubmapOf :: (Ord k, Eq a) => IntervalMap k a -> IntervalMap k a -> Bool isProperSubmapOf = isProperSubmapOfBy (==) @m1@ and @m2@ are not equal , all keys in @m1@ are in @m2@ , and when returns ' True ' when isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> IntervalMap k a -> IntervalMap k b -> Bool isProperSubmapOfBy f m1 m2 = isSubmapOfBy f m1 m2 && keysSet m1 `IntervalSet.isProperSubsetOf` keysSet m2 splitLookupLE :: Ord k => k -> Map k v -> (Map k v, Maybe v, Map k v) splitLookupLE k m = case Map.splitLookup k m of (smaller, Just v, larger) -> (smaller, Just v, larger) (smaller, Nothing, larger) -> case Map.maxView smaller of Just (v, smaller') -> (smaller', Just v, larger) Nothing -> (smaller, Nothing, larger) upTo :: Ord r => Interval r -> Interval r upTo i = case Interval.lowerBound' i of (NegInf, _) -> Interval.empty (PosInf, _) -> Interval.whole (Finite lb, incl) -> Interval.interval (NegInf, Interval.Open) (Finite lb, notB incl) downTo :: Ord r => Interval r -> Interval r downTo i = case Interval.upperBound' i of (PosInf, _) -> Interval.empty (NegInf, _) -> Interval.whole (Finite ub, incl) -> Interval.interval (Finite ub, notB incl) (PosInf, Interval.Open) notB :: Interval.Boundary -> Interval.Boundary notB = \case Interval.Open -> Interval.Closed Interval.Closed -> Interval.Open
074c0bb0c7f772355c46021cae28cf207ba83d131599e2c0b8ea19ce8068a9c4
GNOME/gimp-tiny-fu
difference-clouds.scm
; Plugin for the GNU Image Manipulation Program Copyright ( C ) 2006 ; ; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; You should have received a copy of the GNU General Public License ; along with this program. If not, see </>. ; ; Renders Difference Clouds onto a layer, i.e. solid noise merged down with the ; Difference Mode ; (define (script-fu-difference-clouds image drawable) (let* ((draw-offset-x (car (gimp-drawable-offsets drawable))) (draw-offset-y (cadr (gimp-drawable-offsets drawable))) (has-sel (car (gimp-drawable-mask-intersect drawable))) (sel-offset-x (cadr (gimp-drawable-mask-intersect drawable))) (sel-offset-y (caddr (gimp-drawable-mask-intersect drawable))) (width (cadddr (gimp-drawable-mask-intersect drawable))) (height (caddr (cddr (gimp-drawable-mask-intersect drawable)))) (type (car (gimp-drawable-type-with-alpha drawable))) (diff-clouds (car (gimp-layer-new image width height type "Clouds" 100 DIFFERENCE-MODE))) (offset-x 0) (offset-y 0) ) (gimp-image-undo-group-start image) ; Add the cloud layer above the current layer (gimp-image-insert-layer image diff-clouds 0 -1) ; Clear the layer (so there are no noise in it) (gimp-drawable-fill diff-clouds TRANSPARENT-FILL) ; Selections are relative to the drawable; adjust the final offset (set! offset-x (+ draw-offset-x sel-offset-x)) (set! offset-y (+ draw-offset-y sel-offset-y)) ; Offset the clouds layer (if (gimp-item-is-layer drawable) (gimp-layer-translate diff-clouds offset-x offset-y)) ; Show the solid noise dialog (plug-in-solid-noise SF-RUN-MODE image diff-clouds 0 0 0 1 4.0 4.0) ; Merge the clouds layer with the layer below (gimp-image-merge-down image diff-clouds EXPAND-AS-NECESSARY) (gimp-image-undo-group-end image) (gimp-displays-flush) ) ) (script-fu-register "script-fu-difference-clouds" _"Difference Clouds..." _"Solid noise applied with Difference layer mode" "Martin Nordholts <>" "Martin Nordholts" "2006/10/25" "RGB* GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0) (script-fu-menu-register "script-fu-difference-clouds" "<Image>/Filters/Render/Clouds")
null
https://raw.githubusercontent.com/GNOME/gimp-tiny-fu/a64d85eec23b997e535488d67f55b44395ba3f2e/scripts/difference-clouds.scm
scheme
Plugin for the GNU Image Manipulation Program This program is free software: you can redistribute it and/or modify either version 3 of the License , or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Renders Difference Clouds onto a layer, i.e. solid noise merged down with the Difference Mode Add the cloud layer above the current layer Clear the layer (so there are no noise in it) Selections are relative to the drawable; adjust the final offset Offset the clouds layer Show the solid noise dialog Merge the clouds layer with the layer below
Copyright ( C ) 2006 it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License (define (script-fu-difference-clouds image drawable) (let* ((draw-offset-x (car (gimp-drawable-offsets drawable))) (draw-offset-y (cadr (gimp-drawable-offsets drawable))) (has-sel (car (gimp-drawable-mask-intersect drawable))) (sel-offset-x (cadr (gimp-drawable-mask-intersect drawable))) (sel-offset-y (caddr (gimp-drawable-mask-intersect drawable))) (width (cadddr (gimp-drawable-mask-intersect drawable))) (height (caddr (cddr (gimp-drawable-mask-intersect drawable)))) (type (car (gimp-drawable-type-with-alpha drawable))) (diff-clouds (car (gimp-layer-new image width height type "Clouds" 100 DIFFERENCE-MODE))) (offset-x 0) (offset-y 0) ) (gimp-image-undo-group-start image) (gimp-image-insert-layer image diff-clouds 0 -1) (gimp-drawable-fill diff-clouds TRANSPARENT-FILL) (set! offset-x (+ draw-offset-x sel-offset-x)) (set! offset-y (+ draw-offset-y sel-offset-y)) (if (gimp-item-is-layer drawable) (gimp-layer-translate diff-clouds offset-x offset-y)) (plug-in-solid-noise SF-RUN-MODE image diff-clouds 0 0 0 1 4.0 4.0) (gimp-image-merge-down image diff-clouds EXPAND-AS-NECESSARY) (gimp-image-undo-group-end image) (gimp-displays-flush) ) ) (script-fu-register "script-fu-difference-clouds" _"Difference Clouds..." _"Solid noise applied with Difference layer mode" "Martin Nordholts <>" "Martin Nordholts" "2006/10/25" "RGB* GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0) (script-fu-menu-register "script-fu-difference-clouds" "<Image>/Filters/Render/Clouds")
f5179ef2fdd59141f7c90b5fa32b62e89fcb6f7f2606288ef798def03c982a8f
raghavkarol/edt
edt_app.erl
%% Copyright 2020 . %% -module(edt_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> Cmd = os:cmd("ps " ++ os:getpid()), Profile = edt:rebar3_profile(), case edt_lib:parse_rebar3_profile(Cmd) of Profile -> ok; Other -> case application:get_env(edt, warn_rebar3_profile, true) of true -> edt_out:stdout( "--------------------------------------------------------------------------------" ), edt_out:stdout( "WARNING configured with rebar3 profile: ~s but running with ~p ", [ Profile, Other ] ), edt_out:stdout("~s", [Cmd], no_nl), edt_out:stdout( "--------------------------------------------------------------------------------", [] ); false -> ok end end, start_cowboy(edt:enable_http_server()), edt_sup:start_link(). stop(_State) -> stop_cowboy(edt:enable_http_server()), ok. start_cowboy(true) -> Dispatch = cowboy_router:compile( [{'_', [{'_', edt_http, #{}}]}] ), Port = edt:http_port(), {ok, _Ref} = cowboy:start_clear( edt_http_listener, [{port, Port}], #{env => #{dispatch => Dispatch}} ), ok; start_cowboy(_) -> ok. stop_cowboy(true) -> cowboy:stop_listener(edt_http_listener), ok; stop_cowboy(_) -> ok.
null
https://raw.githubusercontent.com/raghavkarol/edt/619bb788767dbb0d8e144e1c58af9e6e4925460c/src/edt_app.erl
erlang
Copyright 2020 . -module(edt_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> Cmd = os:cmd("ps " ++ os:getpid()), Profile = edt:rebar3_profile(), case edt_lib:parse_rebar3_profile(Cmd) of Profile -> ok; Other -> case application:get_env(edt, warn_rebar3_profile, true) of true -> edt_out:stdout( "--------------------------------------------------------------------------------" ), edt_out:stdout( "WARNING configured with rebar3 profile: ~s but running with ~p ", [ Profile, Other ] ), edt_out:stdout("~s", [Cmd], no_nl), edt_out:stdout( "--------------------------------------------------------------------------------", [] ); false -> ok end end, start_cowboy(edt:enable_http_server()), edt_sup:start_link(). stop(_State) -> stop_cowboy(edt:enable_http_server()), ok. start_cowboy(true) -> Dispatch = cowboy_router:compile( [{'_', [{'_', edt_http, #{}}]}] ), Port = edt:http_port(), {ok, _Ref} = cowboy:start_clear( edt_http_listener, [{port, Port}], #{env => #{dispatch => Dispatch}} ), ok; start_cowboy(_) -> ok. stop_cowboy(true) -> cowboy:stop_listener(edt_http_listener), ok; stop_cowboy(_) -> ok.
65cd0c2db2cd3f091543a653dc915ad98a7ad25d400a9c80ab2020efc7837550
monadfix/ormolu-live
TcEvidence.hs
( c ) The University of Glasgow 2006 # LANGUAGE CPP , DeriveDataTypeable # module TcEvidence ( HsWrapper HsWrapper(..), (<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams, mkWpLams, mkWpLet, mkWpCastN, mkWpCastR, collectHsWrapBinders, mkWpFun, idHsWrapper, isIdHsWrapper, isErasableHsWrapper, pprHsWrapper, -- Evidence bindings TcEvBinds(..), EvBindsVar(..), EvBindMap(..), emptyEvBindMap, extendEvBinds, lookupEvBind, evBindMapBinds, foldEvBindMap, filterEvBindMap, isEmptyEvBindMap, EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind, evBindVar, isCoEvBindsVar, EvTerm ( already a CoreExpr ) EvTerm(..), EvExpr, evId, evCoercion, evCast, evDFunApp, evDataConApp, evSelector, mkEvCast, evVarsOfTerm, mkEvScSelectors, evTypeable, findNeededEvVars, evTermCoercion, evTermCoercion_maybe, EvCallStack(..), EvTypeable(..), -- TcCoercion TcCoercion, TcCoercionR, TcCoercionN, TcCoercionP, CoercionHole, TcMCoercion, Role(..), LeftOrRight(..), pickLR, mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo, mkTcTyConAppCo, mkTcAppCo, mkTcFunCo, mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos, mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo, tcDowngradeRole, mkTcAxiomRuleCo, mkTcGReflRightCo, mkTcGReflLeftCo, mkTcPhantomCo, mkTcCoherenceLeftCo, mkTcCoherenceRightCo, mkTcKindCo, tcCoercionKind, coVarsOfTcCo, mkTcCoVarCo, isTcReflCo, isTcReflexiveCo, isTcGReflMCo, tcCoToMCo, tcCoercionRole, unwrapIP, wrapIP ) where #include "HsVersions2.h" import GhcPrelude import Var import CoAxiom import Coercion Instance OutputableBndr TyVar import TcType import Type import TyCon import DataCon( DataCon, dataConWrapId ) import Class( Class ) import PrelNames import DynFlags ( gopt, GeneralFlag(Opt_PrintTypecheckerElaboration) ) import VarEnv import VarSet import Predicate import Name import Pair import CoreSyn import Class ( classSCSelId ) import CoreFVs ( exprSomeFreeVars ) import Util import Bag import qualified Data.Data as Data import Outputable import SrcLoc import Data.IORef( IORef ) import UniqSet Note [ TcCoercions ] ~~~~~~~~~~~~~~~~~~ | TcCoercions are a hack used by the typechecker . Normally , Coercions have free variables of type ( a ~ # b ): we call these CoVars . However , the type checker passes around equality evidence ( boxed up ) at type ( a ~ b ) . An TcCoercion is simply a Coercion whose free variables have may be either boxed or unboxed . After we are done with typechecking the desugarer finds the boxed free variables , unboxes them , and creates a resulting real Coercion with kosher free variables . Note [TcCoercions] ~~~~~~~~~~~~~~~~~~ | TcCoercions are a hack used by the typechecker. Normally, Coercions have free variables of type (a ~# b): we call these CoVars. However, the type checker passes around equality evidence (boxed up) at type (a ~ b). An TcCoercion is simply a Coercion whose free variables have may be either boxed or unboxed. After we are done with typechecking the desugarer finds the boxed free variables, unboxes them, and creates a resulting real Coercion with kosher free variables. -} type TcCoercion = Coercion A Nominal coercion ~N A Representational coercion type TcCoercionP = CoercionP -- a phantom coercion type TcMCoercion = MCoercion mkTcReflCo :: Role -> TcType -> TcCoercion mkTcSymCo :: TcCoercion -> TcCoercion mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion mkTcNomReflCo :: TcType -> TcCoercionN mkTcRepReflCo :: TcType -> TcCoercionR mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion mkTcAppCo :: TcCoercion -> TcCoercionN -> TcCoercion mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion mkTcAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [TcType] -> [TcCoercion] -> TcCoercion mkTcUnbranchedAxInstCo :: CoAxiom Unbranched -> [TcType] -> [TcCoercion] -> TcCoercionR mkTcForAllCo :: TyVar -> TcCoercionN -> TcCoercion -> TcCoercion mkTcForAllCos :: [(TyVar, TcCoercionN)] -> TcCoercion -> TcCoercion mkTcNthCo :: Role -> Int -> TcCoercion -> TcCoercion mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion mkTcSubCo :: TcCoercionN -> TcCoercionR tcDowngradeRole :: Role -> Role -> TcCoercion -> TcCoercion mkTcAxiomRuleCo :: CoAxiomRule -> [TcCoercion] -> TcCoercionR mkTcGReflRightCo :: Role -> TcType -> TcCoercionN -> TcCoercion mkTcGReflLeftCo :: Role -> TcType -> TcCoercionN -> TcCoercion mkTcCoherenceLeftCo :: Role -> TcType -> TcCoercionN -> TcCoercion -> TcCoercion mkTcCoherenceRightCo :: Role -> TcType -> TcCoercionN -> TcCoercion -> TcCoercion mkTcPhantomCo :: TcCoercionN -> TcType -> TcType -> TcCoercionP mkTcKindCo :: TcCoercion -> TcCoercionN mkTcCoVarCo :: CoVar -> TcCoercion tcCoercionKind :: TcCoercion -> Pair TcType tcCoercionRole :: TcCoercion -> Role coVarsOfTcCo :: TcCoercion -> TcTyCoVarSet isTcReflCo :: TcCoercion -> Bool isTcGReflMCo :: TcMCoercion -> Bool -- | This version does a slow check, calculating the related types and seeing -- if they are equal. isTcReflexiveCo :: TcCoercion -> Bool mkTcReflCo = mkReflCo mkTcSymCo = mkSymCo mkTcTransCo = mkTransCo mkTcNomReflCo = mkNomReflCo mkTcRepReflCo = mkRepReflCo mkTcTyConAppCo = mkTyConAppCo mkTcAppCo = mkAppCo mkTcFunCo = mkFunCo mkTcAxInstCo = mkAxInstCo mkTcUnbranchedAxInstCo = mkUnbranchedAxInstCo Representational mkTcForAllCo = mkForAllCo mkTcForAllCos = mkForAllCos mkTcNthCo = mkNthCo mkTcLRCo = mkLRCo mkTcSubCo = mkSubCo tcDowngradeRole = downgradeRole mkTcAxiomRuleCo = mkAxiomRuleCo mkTcGReflRightCo = mkGReflRightCo mkTcGReflLeftCo = mkGReflLeftCo mkTcCoherenceLeftCo = mkCoherenceLeftCo mkTcCoherenceRightCo = mkCoherenceRightCo mkTcPhantomCo = mkPhantomCo mkTcKindCo = mkKindCo mkTcCoVarCo = mkCoVarCo tcCoercionKind = coercionKind tcCoercionRole = coercionRole coVarsOfTcCo = coVarsOfCo isTcReflCo = isReflCo isTcGReflMCo = isGReflMCo isTcReflexiveCo = isReflexiveCo tcCoToMCo :: TcCoercion -> TcMCoercion tcCoToMCo = coToMCo | If the is , makes a SubCo ; otherwise , does nothing . -- Note that the input coercion should always be nominal. maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion maybeTcSubCo NomEq = id maybeTcSubCo ReprEq = mkTcSubCo % * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * % * * HsWrapper * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * %************************************************************************ %* * HsWrapper * * ************************************************************************ -} data HsWrapper = WpHole -- The identity coercion | WpCompose HsWrapper HsWrapper ( ` ` wrap2)[e ] = [ wrap2 [ e ] ] -- Hence ( \a . [ ] ) ` WpCompose ` ( \b . [ ] ) = ( \a b. [ ] ) But ( [ ] a ) ` ` ( [ ] b ) = ( [ ] b a ) | WpFun HsWrapper HsWrapper TcType SDoc ( WpFun wrap1 wrap2 t1)[e ] = \(x : t1 ) . wrap2 [ e wrap1[x ] ] So note that if : : exp_arg < = act_arg -- wrap2 :: act_res <= exp_res then WpFun wrap1 wrap2 : ( act_arg - > arg_res ) < = ( exp_arg - > exp_res ) -- This isn't the same as for mkFunCo, but it has to be this way because we ca n't use ' sym ' to flip around these HsWrappers The TcType is the " from " type of the first wrapper The SDoc explains the circumstances under which we have created this -- WpFun, in case we run afoul of levity polymorphism restrictions in the desugarer . See Note [ Levity polymorphism checking ] in DsMonad | WpCast TcCoercionR -- A cast: [] `cast` co -- Guaranteed not the identity coercion At role Representational -- Evidence abstraction and application -- (both dictionaries and coercions) \d . [ ] the 'd ' is an evidence variable | WpEvApp EvTerm -- [] d the 'd' is evidence for a constraint -- Kind and Type abstraction and application \a . [ ] the ' a ' is a type / kind variable ( not coercion var ) | WpTyApp KindOrType -- [] t the 't' is a type (not coercion) | WpLet TcEvBinds -- Non-empty (or possibly non-empty) evidence bindings, so that the identity coercion is always exactly WpHole Can not derive Data instance because SDoc is not Data ( it stores a function ) . -- So we do it manually: instance Data.Data HsWrapper where gfoldl _ z WpHole = z WpHole gfoldl k z (WpCompose a1 a2) = z WpCompose `k` a1 `k` a2 gfoldl k z (WpFun a1 a2 a3 _) = z wpFunEmpty `k` a1 `k` a2 `k` a3 gfoldl k z (WpCast a1) = z WpCast `k` a1 gfoldl k z (WpEvLam a1) = z WpEvLam `k` a1 gfoldl k z (WpEvApp a1) = z WpEvApp `k` a1 gfoldl k z (WpTyLam a1) = z WpTyLam `k` a1 gfoldl k z (WpTyApp a1) = z WpTyApp `k` a1 gfoldl k z (WpLet a1) = z WpLet `k` a1 gunfold k z c = case Data.constrIndex c of 1 -> z WpHole 2 -> k (k (z WpCompose)) 3 -> k (k (k (z wpFunEmpty))) 4 -> k (z WpCast) 5 -> k (z WpEvLam) 6 -> k (z WpEvApp) 7 -> k (z WpTyLam) 8 -> k (z WpTyApp) _ -> k (z WpLet) toConstr WpHole = wpHole_constr toConstr (WpCompose _ _) = wpCompose_constr toConstr (WpFun _ _ _ _) = wpFun_constr toConstr (WpCast _) = wpCast_constr toConstr (WpEvLam _) = wpEvLam_constr toConstr (WpEvApp _) = wpEvApp_constr toConstr (WpTyLam _) = wpTyLam_constr toConstr (WpTyApp _) = wpTyApp_constr toConstr (WpLet _) = wpLet_constr dataTypeOf _ = hsWrapper_dataType hsWrapper_dataType :: Data.DataType hsWrapper_dataType = Data.mkDataType "HsWrapper" [ wpHole_constr, wpCompose_constr, wpFun_constr, wpCast_constr , wpEvLam_constr, wpEvApp_constr, wpTyLam_constr, wpTyApp_constr , wpLet_constr] wpHole_constr, wpCompose_constr, wpFun_constr, wpCast_constr, wpEvLam_constr, wpEvApp_constr, wpTyLam_constr, wpTyApp_constr, wpLet_constr :: Data.Constr wpHole_constr = mkHsWrapperConstr "WpHole" wpCompose_constr = mkHsWrapperConstr "WpCompose" wpFun_constr = mkHsWrapperConstr "WpFun" wpCast_constr = mkHsWrapperConstr "WpCast" wpEvLam_constr = mkHsWrapperConstr "WpEvLam" wpEvApp_constr = mkHsWrapperConstr "WpEvApp" wpTyLam_constr = mkHsWrapperConstr "WpTyLam" wpTyApp_constr = mkHsWrapperConstr "WpTyApp" wpLet_constr = mkHsWrapperConstr "WpLet" mkHsWrapperConstr :: String -> Data.Constr mkHsWrapperConstr name = Data.mkConstr hsWrapper_dataType name [] Data.Prefix wpFunEmpty :: HsWrapper -> HsWrapper -> TcType -> HsWrapper wpFunEmpty c1 c2 t1 = WpFun c1 c2 t1 empty (<.>) :: HsWrapper -> HsWrapper -> HsWrapper WpHole <.> c = c c <.> WpHole = c c1 <.> c2 = c1 `WpCompose` c2 mkWpFun :: HsWrapper -> HsWrapper the " from " type of the first wrapper either type of the second wrapper ( used only when the second wrapper is the identity ) -> SDoc -- what caused you to want a WpFun? Something like "When converting ..." -> HsWrapper mkWpFun WpHole WpHole _ _ _ = WpHole mkWpFun WpHole (WpCast co2) t1 _ _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2) mkWpFun (WpCast co1) WpHole _ t2 _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2)) mkWpFun (WpCast co1) (WpCast co2) _ _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2) mkWpFun co1 co2 t1 _ d = WpFun co1 co2 t1 d mkWpCastR :: TcCoercionR -> HsWrapper mkWpCastR co | isTcReflCo co = WpHole | otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co) WpCast co mkWpCastN :: TcCoercionN -> HsWrapper mkWpCastN co | isTcReflCo co = WpHole | otherwise = ASSERT2(tcCoercionRole co == Nominal, ppr co) WpCast (mkTcSubCo co) The mkTcSubCo converts to Representational mkWpTyApps :: [Type] -> HsWrapper mkWpTyApps tys = mk_co_app_fn WpTyApp tys mkWpEvApps :: [EvTerm] -> HsWrapper mkWpEvApps args = mk_co_app_fn WpEvApp args mkWpEvVarApps :: [EvVar] -> HsWrapper mkWpEvVarApps vs = mk_co_app_fn WpEvApp (map (EvExpr . evId) vs) mkWpTyLams :: [TyVar] -> HsWrapper mkWpTyLams ids = mk_co_lam_fn WpTyLam ids mkWpLams :: [Var] -> HsWrapper mkWpLams ids = mk_co_lam_fn WpEvLam ids mkWpLet :: TcEvBinds -> HsWrapper -- This no-op is a quite a common case mkWpLet (EvBinds b) | isEmptyBag b = WpHole mkWpLet ev_binds = WpLet ev_binds mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper For applications , the * first * argument must -- come *last* in the composition sequence mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as idHsWrapper :: HsWrapper idHsWrapper = WpHole isIdHsWrapper :: HsWrapper -> Bool isIdHsWrapper WpHole = True isIdHsWrapper _ = False -- | Is the wrapper erasable, i.e., will not affect runtime semantics? isErasableHsWrapper :: HsWrapper -> Bool isErasableHsWrapper = go where go WpHole = True go (WpCompose wrap1 wrap2) = go wrap1 && go wrap2 -- not so sure about WpFun. But it eta-expands, so... go WpFun{} = False go WpCast{} = True go WpEvLam{} = False -- case in point go WpEvApp{} = False go WpTyLam{} = True go WpTyApp{} = True go WpLet{} = False collectHsWrapBinders :: HsWrapper -> ([Var], HsWrapper) Collect the outer lambda binders of a HsWrapper , -- stopping as soon as you get to a non-lambda binder collectHsWrapBinders wrap = go wrap [] where -- go w ws = collectHsWrapBinders (w <.> w1 <.> ... <.> wn) go :: HsWrapper -> [HsWrapper] -> ([Var], HsWrapper) go (WpEvLam v) wraps = add_lam v (gos wraps) go (WpTyLam v) wraps = add_lam v (gos wraps) go (WpCompose w1 w2) wraps = go w1 (w2:wraps) go wrap wraps = ([], foldl' (<.>) wrap wraps) gos [] = ([], WpHole) gos (w:ws) = go w ws add_lam v (vs,w) = (v:vs, w) {- ************************************************************************ * * Evidence bindings * * ************************************************************************ -} data TcEvBinds = TcEvBinds -- Mutable evidence bindings EvBindsVar -- Mutable because they are updated "later" -- when an implication constraint is solved | EvBinds -- Immutable after zonking (Bag EvBind) data EvBindsVar = EvBindsVar { ebv_uniq :: Unique, -- The Unique is for debug printing only ebv_binds :: IORef EvBindMap, -- The main payload: the value-level evidence bindings -- (dictionaries etc) -- Some Given, some Wanted ebv_tcvs :: IORef CoVarSet -- The free Given coercion vars needed by Wanted coercions that are solved by filling in their HoleDest in - place . Since they -- don't appear in ebv_binds, we keep track of their free -- variables so that we can report unused given constraints -- See Note [Tracking redundant constraints] in TcSimplify } | CoEvBindsVar { -- See Note [Coercion evidence only] -- See above for comments on ebv_uniq, ebv_tcvs ebv_uniq :: Unique, ebv_tcvs :: IORef CoVarSet } instance Data.Data TcEvBinds where Placeholder ; we ca n't travers into TcEvBinds toConstr _ = abstractConstr "TcEvBinds" gunfold _ _ = error "gunfold" dataTypeOf _ = Data.mkNoRepType "TcEvBinds" Note [ Coercion evidence only ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class constraints etc give rise to /term/ bindings for evidence , and we have nowhere to put term bindings in /types/. So in some places we use CoEvBindsVar ( see newCoTcEvBinds ) to signal that no term - level evidence bindings are allowed . ( ): - Places in types where we are solving kind constraints ( all of which are equalities ) ; see solveEqualities , solveLocalEqualities , checkTvConstraints - When unifying forall - types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class constraints etc give rise to /term/ bindings for evidence, and we have nowhere to put term bindings in /types/. So in some places we use CoEvBindsVar (see newCoTcEvBinds) to signal that no term-level evidence bindings are allowed. Notebly (): - Places in types where we are solving kind constraints (all of which are equalities); see solveEqualities, solveLocalEqualities, checkTvConstraints - When unifying forall-types -} isCoEvBindsVar :: EvBindsVar -> Bool isCoEvBindsVar (CoEvBindsVar {}) = True isCoEvBindsVar (EvBindsVar {}) = False ----------------- newtype EvBindMap = EvBindMap { ev_bind_varenv :: DVarEnv EvBind } -- Map from evidence variables to evidence terms We use here to get deterministic ordering when we -- turn it into a Bag. -- If we don't do that, when we generate let bindings for -- dictionaries in dsTcEvBinds they will be generated in random -- order. -- -- For example: -- -- let $dEq = GHC.Classes.$fEqInt in -- let $$dNum = GHC.Num.$fNumInt in ... -- -- vs -- let in -- let $dEq = GHC.Classes.$fEqInt in ... -- -- See Note [Deterministic UniqFM] in UniqDFM for explanation why -- @UniqFM@ can lead to nondeterministic order. emptyEvBindMap :: EvBindMap emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv } extendEvBinds :: EvBindMap -> EvBind -> EvBindMap extendEvBinds bs ev_bind = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs) (eb_lhs ev_bind) ev_bind } isEmptyEvBindMap :: EvBindMap -> Bool isEmptyEvBindMap (EvBindMap m) = isEmptyDVarEnv m lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs) evBindMapBinds :: EvBindMap -> Bag EvBind evBindMapBinds = foldEvBindMap consBag emptyBag foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs) filterEvBindMap :: (EvBind -> Bool) -> EvBindMap -> EvBindMap filterEvBindMap k (EvBindMap { ev_bind_varenv = env }) = EvBindMap { ev_bind_varenv = filterDVarEnv k env } instance Outputable EvBindMap where ppr (EvBindMap m) = ppr m ----------------- All evidence is bound by ; no side effects data EvBind = EvBind { eb_lhs :: EvVar , eb_rhs :: EvTerm , eb_is_given :: Bool -- True <=> given -- See Note [Tracking redundant constraints] in TcSimplify } evBindVar :: EvBind -> EvVar evBindVar = eb_lhs mkWantedEvBind :: EvVar -> EvTerm -> EvBind mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm } EvTypeable are never given , so we can work with EvExpr here instead of EvTerm mkGivenEvBind :: EvVar -> EvTerm -> EvBind mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm } An EvTerm is , conceptually , a CoreExpr that implements the constraint . -- Unfortunately, we cannot just do type EvTerm = CoreExpr Because of staging problems issues around data EvTerm = EvExpr EvExpr Dictionary for ( ) /\as \ds . let binds in v { et_tvs :: [TyVar] , et_given :: [EvVar] , et_binds :: TcEvBinds -- This field is why we need an EvFun constructor , and ca n't just use EvExpr , et_body :: EvVar } deriving Data.Data type EvExpr = CoreExpr An EvTerm is ( usually ) constructed by any of the constructors here -- and those more complicates ones who were moved to module TcEvTerm -- | Any sort of evidence Id, including coercions evId :: EvId -> EvExpr evId = Var -- coercion bindings -- See Note [Coercion evidence terms] evCoercion :: TcCoercion -> EvTerm evCoercion co = EvExpr (Coercion co) -- | d |> co evCast :: EvExpr -> TcCoercion -> EvTerm evCast et tc | isReflCo tc = EvExpr et | otherwise = EvExpr (Cast et tc) -- Dictionary instance application evDFunApp :: DFunId -> [Type] -> [EvExpr] -> EvTerm evDFunApp df tys ets = EvExpr $ Var df `mkTyApps` tys `mkApps` ets evDataConApp :: DataCon -> [Type] -> [EvExpr] -> EvTerm evDataConApp dc tys ets = evDFunApp (dataConWrapId dc) tys ets -- Selector id plus the types at which it should be instantiated , used for HasField -- dictionaries; see Note [HasField instances] in TcInterface evSelector :: Id -> [Type] -> [EvExpr] -> EvExpr evSelector sel_id tys tms = Var sel_id `mkTyApps` tys `mkApps` tms Dictionary for ( ) evTypeable :: Type -> EvTypeable -> EvTerm evTypeable = EvTypeable | Instructions on how to make a ' ' dictionary . See Note [ Typeable evidence terms ] data EvTypeable = EvTypeableTyCon TyCon [EvTerm] -- ^ Dictionary for @Typeable T@ where @T@ is a type constructor with all of its kind variables saturated . The @[EvTerm]@ is @Typeable@ evidence for -- the applied kinds.. | EvTypeableTyApp EvTerm EvTerm ^ Dictionary for ( s t)@ , given a dictionaries for @s@ and | EvTypeableTrFun EvTerm EvTerm ^ Dictionary for ( s - > t)@ , given a dictionaries for @s@ and | EvTypeableTyLit EvTerm -- ^ Dictionary for a type literal, -- e.g. @Typeable "foo"@ or @Typeable 3@ The ' EvTerm ' is evidence of , e.g. , @KnownNat 3@ ( see # 10348 ) deriving Data.Data -- | Evidence for @CallStack@ implicit parameters. data EvCallStack See Note [ Overview of implicit CallStacks ] = EvCsEmpty | EvCsPushCall Name RealSrcSpan EvExpr ^ @EvCsPushCall name represents a call to @name@ , occurring at @loc@ , in a calling context @stk@. deriving Data.Data Note [ Typeable evidence terms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The EvTypeable data type looks isomorphic to Type , but the EvTerms inside can be EvIds . Eg f : : forall a. Typeable a = > a - > TypeRep f x = typeRep ( undefined : : Proxy [ a ] ) Here for the ( Typeable [ a ] ) dictionary passed to typeRep we make evidence dl : : [ a ] = EvTypeable [ a ] ( EvTypeableTyApp ( EvTypeableTyCon [ ] ) ( EvId d ) ) where d : : Typable a is the lambda - bound dictionary passed into f. Note [ Coercion evidence terms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A " coercion evidence term " takes one of these forms co_tm : : = EvId v where v : : t1 ~ # t2 | EvCoercion co | EvCast co_tm co We do quite often need to get a TcCoercion from an EvTerm ; see ' evTermCoercion ' . INVARIANT : The evidence for any constraint with type ( t1 ~ # t2 ) is a coercion evidence term . Consider for example [ G ] d : : F Int a If we have ax7 a : : F Int a ~ ( a ~ Bool ) then we do NOT generate the constraint [ G ] ( d | > ax7 a ) : : a ~ Bool because that does not satisfy the invariant ( d is not a coercion variable ) . Instead we make a binding g1 : : a ~ Bool = g | > ax7 a and the constraint [ G ] g1 : : a ~ Bool See # 7238 and Note [ Bind new Givens immediately ] in Constraint Note [ EvBinds / EvTerm ] ~~~~~~~~~~~~~~~~~~~~~ How evidence is created and updated . Bindings for dictionaries , and coercions and implicit parameters are carried around in TcEvBinds which during constraint generation and simplification is always of the form ( TcEvBinds ref ) . After constraint simplification is finished it will be transformed to t an ( ) . Evidence for coercions * SHOULD * be filled in using the TcEvBinds However , all that correspond to * wanted * coercion terms in an EvBind must be mutable variables so that they can be readily inlined ( by zonking ) after constraint simplification is finished . Conclusion : a new wanted coercion variable should be made mutable . [ Notice though that evidence variables that bind coercion terms from super classes will be " given " and hence rigid ] Note [ Overview of implicit CallStacks ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( See -call-stack/implicit-locations ) The goal of CallStack evidence terms is to reify locations in the program source as runtime values , without any support from the RTS . We accomplish this by assigning a special meaning to constraints of type GHC.Stack . Types . HasCallStack , an alias type HasCallStack = ( ? : : ) Implicit parameters of type GHC.Stack . Types . ( the name is not important ) are solved in three steps : 1 . Occurrences of CallStack IPs are solved directly from the given IP , just like a regular IP . For example , the occurrence of ` ? in error : : ( ? : : ) = > String - > a error s = raise ( ErrorCall ( s + + prettyCallStack ? ) ) will be solved for the ` ? in ` error`s context as before . 2 . In a function call , instead of simply passing the given IP , we first append the current call - site to it . For example , consider a call to the - aware ` error ` above . undefined : : ( ? : : ) = > a undefined = error " undefined ! " Here we want to take the given ` ? ` and append the current call - site , before passing it to ` error ` . In essence , we want to rewrite ` error " undefined ! " ` to let ? stk = pushCallStack < error 's location > ? stk in error " undefined ! " We achieve this effect by emitting a NEW wanted [ W ] d : : IP " stk " CallStack from which we build the evidence term EvCsPushCall " error " < error 's location > ( EvId d ) that we use to solve the call to ` error ` . The new wanted ` d ` will then be solved per rule ( 1 ) , ie as a regular IP . ( see TcInteract.interactDict ) 3 . We default any insoluble CallStacks to the empty CallStack . Suppose ` undefined ` did not request a CallStack , ie undefinedNoStk : : a undefinedNoStk = error " undefined ! " Under the usual IP rules , the new wanted from rule ( 2 ) would be insoluble as there 's no given IP from which to solve it , so we would get an " unbound implicit parameter " error . We do n't ever want to emit an insoluble , so we add a defaulting pass to default any remaining wanted CallStacks to the empty CallStack with the evidence term EvCsEmpty ( see TcSimplify.simpl_top and TcSimplify.defaultCallStacks ) This provides a lightweight mechanism for building up call - stacks explicitly , but is notably limited by the fact that the stack will stop at the first function whose type does not include a CallStack IP . For example , using the above definition of ` undefined ` : head : : [ a ] - > a head [ ] = undefined head ( x : _ ) = x g = head [ ] the resulting CallStack will include the call to ` undefined ` in ` head ` and the call to ` error ` in ` undefined ` , but * not * the call to ` head ` in ` g ` , because ` head ` did not explicitly request a CallStack . Important Details : - GHC should NEVER report an insoluble CallStack constraint . - GHC should NEVER infer a CallStack constraint unless one was requested with a partial type signature ( See TcType.pickQuantifiablePreds ) . - A CallStack ( defined in GHC.Stack . Types ) is a [ ( String , SrcLoc ) ] , where the is the name of the binder that is used at the SrcLoc . is also defined in GHC.Stack . Types and contains the package / module / file name , as well as the full source - span . Both CallStack and SrcLoc are kept abstract so only GHC can construct new values . - We will automatically solve any wanted CallStack regardless of the name of the IP , i.e. f = show ( ? : : ) g = show ( ? : : ) are both valid . However , we will only push new SrcLocs onto existing CallStacks when the IP names match , e.g. in head : : ( ? : : ) = > [ a ] - > a head [ ] = error ( show ( ? : : ) ) the printed CallStack will NOT include head 's call - site . This reflects the standard scoping rules of implicit - parameters . - An EvCallStack term desugars to a CoreExpr of type ` IP " some str " CallStack ` . The desugarer will need to unwrap the IP newtype before pushing a new call - site onto a given stack ( See DsBinds.dsEvCallStack ) - When we emit a new wanted CallStack from rule ( 2 ) we set its origin to ` IPOccOrigin ip_name ` instead of the original ` OccurrenceOf func ` ( see TcInteract.interactDict ) . This is a bit shady , but is how we ensure that the new wanted is solved like a regular IP . Note [Typeable evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The EvTypeable data type looks isomorphic to Type, but the EvTerms inside can be EvIds. Eg f :: forall a. Typeable a => a -> TypeRep f x = typeRep (undefined :: Proxy [a]) Here for the (Typeable [a]) dictionary passed to typeRep we make evidence dl :: Typeable [a] = EvTypeable [a] (EvTypeableTyApp (EvTypeableTyCon []) (EvId d)) where d :: Typable a is the lambda-bound dictionary passed into f. Note [Coercion evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A "coercion evidence term" takes one of these forms co_tm ::= EvId v where v :: t1 ~# t2 | EvCoercion co | EvCast co_tm co We do quite often need to get a TcCoercion from an EvTerm; see 'evTermCoercion'. INVARIANT: The evidence for any constraint with type (t1 ~# t2) is a coercion evidence term. Consider for example [G] d :: F Int a If we have ax7 a :: F Int a ~ (a ~ Bool) then we do NOT generate the constraint [G] (d |> ax7 a) :: a ~ Bool because that does not satisfy the invariant (d is not a coercion variable). Instead we make a binding g1 :: a~Bool = g |> ax7 a and the constraint [G] g1 :: a~Bool See #7238 and Note [Bind new Givens immediately] in Constraint Note [EvBinds/EvTerm] ~~~~~~~~~~~~~~~~~~~~~ How evidence is created and updated. Bindings for dictionaries, and coercions and implicit parameters are carried around in TcEvBinds which during constraint generation and simplification is always of the form (TcEvBinds ref). After constraint simplification is finished it will be transformed to t an (EvBinds ev_bag). Evidence for coercions *SHOULD* be filled in using the TcEvBinds However, all EvVars that correspond to *wanted* coercion terms in an EvBind must be mutable variables so that they can be readily inlined (by zonking) after constraint simplification is finished. Conclusion: a new wanted coercion variable should be made mutable. [Notice though that evidence variables that bind coercion terms from super classes will be "given" and hence rigid] Note [Overview of implicit CallStacks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (See -call-stack/implicit-locations) The goal of CallStack evidence terms is to reify locations in the program source as runtime values, without any support from the RTS. We accomplish this by assigning a special meaning to constraints of type GHC.Stack.Types.HasCallStack, an alias type HasCallStack = (?callStack :: CallStack) Implicit parameters of type GHC.Stack.Types.CallStack (the name is not important) are solved in three steps: 1. Occurrences of CallStack IPs are solved directly from the given IP, just like a regular IP. For example, the occurrence of `?stk` in error :: (?stk :: CallStack) => String -> a error s = raise (ErrorCall (s ++ prettyCallStack ?stk)) will be solved for the `?stk` in `error`s context as before. 2. In a function call, instead of simply passing the given IP, we first append the current call-site to it. For example, consider a call to the callstack-aware `error` above. undefined :: (?stk :: CallStack) => a undefined = error "undefined!" Here we want to take the given `?stk` and append the current call-site, before passing it to `error`. In essence, we want to rewrite `error "undefined!"` to let ?stk = pushCallStack <error's location> ?stk in error "undefined!" We achieve this effect by emitting a NEW wanted [W] d :: IP "stk" CallStack from which we build the evidence term EvCsPushCall "error" <error's location> (EvId d) that we use to solve the call to `error`. The new wanted `d` will then be solved per rule (1), ie as a regular IP. (see TcInteract.interactDict) 3. We default any insoluble CallStacks to the empty CallStack. Suppose `undefined` did not request a CallStack, ie undefinedNoStk :: a undefinedNoStk = error "undefined!" Under the usual IP rules, the new wanted from rule (2) would be insoluble as there's no given IP from which to solve it, so we would get an "unbound implicit parameter" error. We don't ever want to emit an insoluble CallStack IP, so we add a defaulting pass to default any remaining wanted CallStacks to the empty CallStack with the evidence term EvCsEmpty (see TcSimplify.simpl_top and TcSimplify.defaultCallStacks) This provides a lightweight mechanism for building up call-stacks explicitly, but is notably limited by the fact that the stack will stop at the first function whose type does not include a CallStack IP. For example, using the above definition of `undefined`: head :: [a] -> a head [] = undefined head (x:_) = x g = head [] the resulting CallStack will include the call to `undefined` in `head` and the call to `error` in `undefined`, but *not* the call to `head` in `g`, because `head` did not explicitly request a CallStack. Important Details: - GHC should NEVER report an insoluble CallStack constraint. - GHC should NEVER infer a CallStack constraint unless one was requested with a partial type signature (See TcType.pickQuantifiablePreds). - A CallStack (defined in GHC.Stack.Types) is a [(String, SrcLoc)], where the String is the name of the binder that is used at the SrcLoc. SrcLoc is also defined in GHC.Stack.Types and contains the package/module/file name, as well as the full source-span. Both CallStack and SrcLoc are kept abstract so only GHC can construct new values. - We will automatically solve any wanted CallStack regardless of the name of the IP, i.e. f = show (?stk :: CallStack) g = show (?loc :: CallStack) are both valid. However, we will only push new SrcLocs onto existing CallStacks when the IP names match, e.g. in head :: (?loc :: CallStack) => [a] -> a head [] = error (show (?stk :: CallStack)) the printed CallStack will NOT include head's call-site. This reflects the standard scoping rules of implicit-parameters. - An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`. The desugarer will need to unwrap the IP newtype before pushing a new call-site onto a given stack (See DsBinds.dsEvCallStack) - When we emit a new wanted CallStack from rule (2) we set its origin to `IPOccOrigin ip_name` instead of the original `OccurrenceOf func` (see TcInteract.interactDict). This is a bit shady, but is how we ensure that the new wanted is solved like a regular IP. -} mkEvCast :: EvExpr -> TcCoercion -> EvTerm mkEvCast ev lco | ASSERT2( tcCoercionRole lco == Representational , (vcat [text "Coercion of wrong role passed to mkEvCast:", ppr ev, ppr lco])) isTcReflCo lco = EvExpr ev | otherwise = evCast ev lco mkEvScSelectors -- Assume class (..., D ty, ...) => C a b C -> [(TcPredType, -- D ty[ty1/a,ty2/b] : : C - > D ty[ty1 / a , ty2 / b ] ] mkEvScSelectors cls tys = zipWith mk_pr (immSuperClasses cls tys) [0..] where mk_pr pred i = (pred, Var sc_sel_id `mkTyApps` tys) where Zero - indexed emptyTcEvBinds :: TcEvBinds emptyTcEvBinds = EvBinds emptyBag isEmptyTcEvBinds :: TcEvBinds -> Bool isEmptyTcEvBinds (EvBinds b) = isEmptyBag b isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds" evTermCoercion_maybe :: EvTerm -> Maybe TcCoercion Applied only to EvTerms of type ( s ~ t ) -- See Note [Coercion evidence terms] evTermCoercion_maybe ev_term | EvExpr e <- ev_term = go e | otherwise = Nothing where go :: EvExpr -> Maybe TcCoercion go (Var v) = return (mkCoVarCo v) go (Coercion co) = return co go (Cast tm co) = do { co' <- go tm ; return (mkCoCast co' co) } go _ = Nothing evTermCoercion :: EvTerm -> TcCoercion evTermCoercion tm = case evTermCoercion_maybe tm of Just co -> co Nothing -> pprPanic "evTermCoercion" (ppr tm) {- ********************************************************************* * * Free variables * * ********************************************************************* -} findNeededEvVars :: EvBindMap -> VarSet -> VarSet -- Find all the Given evidence needed by seeds, -- looking transitively through binds findNeededEvVars ev_binds seeds = transCloVarSet also_needs seeds where also_needs :: VarSet -> VarSet also_needs needs = nonDetFoldUniqSet add emptyVarSet needs -- It's OK to use nonDetFoldUFM here because we immediately -- forget about the ordering by creating a set add :: Var -> VarSet -> VarSet add v needs | Just ev_bind <- lookupEvBind ev_binds v , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind , is_given = evVarsOfTerm rhs `unionVarSet` needs | otherwise = needs evVarsOfTerm :: EvTerm -> VarSet evVarsOfTerm (EvExpr e) = exprSomeFreeVars isEvVar e evVarsOfTerm (EvTypeable _ ev) = evVarsOfTypeable ev evVarsOfTerm (EvFun {}) = emptyVarSet -- See Note [Free vars of EvFun] evVarsOfTerms :: [EvTerm] -> VarSet evVarsOfTerms = mapUnionVarSet evVarsOfTerm evVarsOfTypeable :: EvTypeable -> VarSet evVarsOfTypeable ev = case ev of EvTypeableTyCon _ e -> mapUnionVarSet evVarsOfTerm e EvTypeableTyApp e1 e2 -> evVarsOfTerms [e1,e2] EvTypeableTrFun e1 e2 -> evVarsOfTerms [e1,e2] EvTypeableTyLit e -> evVarsOfTerm e Note [ Free vars of EvFun ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finding the free vars of an EvFun is made tricky by the fact the bindings et_binds may be a mutable variable . Fortunately , we can just squeeze by . Here 's how . * evVarsOfTerm is used only by TcSimplify.neededEvVars . * Each EvBindsVar in an et_binds field of an EvFun is /also/ in the ic_binds field of an Implication * So we can track usage via the processing for that implication , ( see Note [ Tracking redundant constraints ] in TcSimplify ) . We can ignore usage from the EvFun altogether . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Pretty printing * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finding the free vars of an EvFun is made tricky by the fact the bindings et_binds may be a mutable variable. Fortunately, we can just squeeze by. Here's how. * evVarsOfTerm is used only by TcSimplify.neededEvVars. * Each EvBindsVar in an et_binds field of an EvFun is /also/ in the ic_binds field of an Implication * So we can track usage via the processing for that implication, (see Note [Tracking redundant constraints] in TcSimplify). We can ignore usage from the EvFun altogether. ************************************************************************ * * Pretty printing * * ************************************************************************ -} instance Outputable HsWrapper where ppr co_fn = pprHsWrapper co_fn (no_parens (text "<>")) pprHsWrapper :: HsWrapper -> (Bool -> SDoc) -> SDoc -- With -fprint-typechecker-elaboration, print the wrapper -- otherwise just print what's inside The pp_thing_inside function takes to say whether -- it's in a position that needs parens for a non-atomic thing pprHsWrapper wrap pp_thing_inside = sdocWithDynFlags $ \ dflags -> if gopt Opt_PrintTypecheckerElaboration dflags then help pp_thing_inside wrap False else pp_thing_inside False where help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc -- True <=> appears in function application position -- False <=> appears as body of let or lambda help it WpHole = it help it (WpCompose f1 f2) = help (help it f2) f1 help it (WpFun f1 f2 t1 _) = add_parens $ text "\\(x" <> dcolon <> ppr t1 <> text ")." <+> help (\_ -> it True <+> help (\_ -> text "x") f1 True) f2 False help it (WpCast co) = add_parens $ sep [it False, nest 2 (text "|>" <+> pprParendCo co)] help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)] help it (WpTyApp ty) = no_parens $ sep [it True, text "@" <+> pprParendType ty] help it (WpEvLam id) = add_parens $ sep [ text "\\" <> pprLamBndr id <> dot, it False] help it (WpTyLam tv) = add_parens $ sep [text "/\\" <> pprLamBndr tv <> dot, it False] help it (WpLet binds) = add_parens $ sep [text "let" <+> braces (ppr binds), it False] pprLamBndr :: Id -> SDoc pprLamBndr v = pprBndr LambdaBind v add_parens, no_parens :: SDoc -> Bool -> SDoc add_parens d True = parens d add_parens d False = d no_parens d _ = d instance Outputable TcEvBinds where ppr (TcEvBinds v) = ppr v ppr (EvBinds bs) = text "EvBinds" <> braces (vcat (map ppr (bagToList bs))) instance Outputable EvBindsVar where ppr (EvBindsVar { ebv_uniq = u }) = text "EvBindsVar" <> angleBrackets (ppr u) ppr (CoEvBindsVar { ebv_uniq = u }) = text "CoEvBindsVar" <> angleBrackets (ppr u) instance Uniquable EvBindsVar where getUnique = ebv_uniq instance Outputable EvBind where ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given }) = sep [ pp_gw <+> ppr v , nest 2 $ equals <+> ppr e ] where pp_gw = brackets (if is_given then char 'G' else char 'W') -- We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing instance Outputable EvTerm where ppr (EvExpr e) = ppr e ppr (EvTypeable ty ev) = ppr ev <+> dcolon <+> text "Typeable" <+> ppr ty ppr (EvFun { et_tvs = tvs, et_given = gs, et_binds = bs, et_body = w }) = hang (text "\\" <+> sep (map pprLamBndr (tvs ++ gs)) <+> arrow) 2 (ppr bs $$ ppr w) -- Not very pretty instance Outputable EvCallStack where ppr EvCsEmpty = text "[]" ppr (EvCsPushCall name loc tm) = ppr (name,loc) <+> text ":" <+> ppr tm instance Outputable EvTypeable where ppr (EvTypeableTyCon ts _) = text "TyCon" <+> ppr ts ppr (EvTypeableTyApp t1 t2) = parens (ppr t1 <+> ppr t2) ppr (EvTypeableTrFun t1 t2) = parens (ppr t1 <+> arrow <+> ppr t2) ppr (EvTypeableTyLit t1) = text "TyLit" <> ppr t1 ---------------------------------------------------------------------- -- Helper functions for dealing with IP newtype-dictionaries ---------------------------------------------------------------------- -- | Create a 'Coercion' that unwraps an implicit-parameter or -- overloaded-label dictionary to expose the underlying value. We expect the ' Type ' to have the form ` IP sym ty ` or ` IsLabel , and return a ' Coercion ' ` co : : IP or ` co : : ~ Proxy # sym - > ty ` . See also Note [ Type - checking overloaded labels ] in TcExpr . unwrapIP :: Type -> CoercionR unwrapIP ty = case unwrapNewTyCon_maybe tc of Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys [] Nothing -> pprPanic "unwrapIP" $ text "The dictionary for" <+> quotes (ppr tc) <+> text "is not a newtype!" where (tc, tys) = splitTyConApp ty -- | Create a 'Coercion' that wraps a value in an implicit-parameter -- dictionary. See 'unwrapIP'. wrapIP :: Type -> CoercionR wrapIP ty = mkSymCo (unwrapIP ty)
null
https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/typecheck/TcEvidence.hs
haskell
Evidence bindings TcCoercion a phantom coercion | This version does a slow check, calculating the related types and seeing if they are equal. Note that the input coercion should always be nominal. The identity coercion wrap2 :: act_res <= exp_res This isn't the same as for mkFunCo, but it has to be this way WpFun, in case we run afoul of levity polymorphism restrictions in A cast: [] `cast` co Guaranteed not the identity coercion Evidence abstraction and application (both dictionaries and coercions) [] d the 'd' is evidence for a constraint Kind and Type abstraction and application [] t the 't' is a type (not coercion) Non-empty (or possibly non-empty) evidence bindings, So we do it manually: what caused you to want a WpFun? Something like "When converting ..." This no-op is a quite a common case come *last* in the composition sequence | Is the wrapper erasable, i.e., will not affect runtime semantics? not so sure about WpFun. But it eta-expands, so... case in point stopping as soon as you get to a non-lambda binder go w ws = collectHsWrapBinders (w <.> w1 <.> ... <.> wn) ************************************************************************ * * Evidence bindings * * ************************************************************************ Mutable evidence bindings Mutable because they are updated "later" when an implication constraint is solved Immutable after zonking The Unique is for debug printing only The main payload: the value-level evidence bindings (dictionaries etc) Some Given, some Wanted The free Given coercion vars needed by Wanted coercions that don't appear in ebv_binds, we keep track of their free variables so that we can report unused given constraints See Note [Tracking redundant constraints] in TcSimplify See Note [Coercion evidence only] See above for comments on ebv_uniq, ebv_tcvs --------------- Map from evidence variables to evidence terms turn it into a Bag. If we don't do that, when we generate let bindings for dictionaries in dsTcEvBinds they will be generated in random order. For example: let $dEq = GHC.Classes.$fEqInt in let $$dNum = GHC.Num.$fNumInt in ... vs let $dEq = GHC.Classes.$fEqInt in ... See Note [Deterministic UniqFM] in UniqDFM for explanation why @UniqFM@ can lead to nondeterministic order. --------------- True <=> given See Note [Tracking redundant constraints] in TcSimplify Unfortunately, we cannot just do This field is why we need an EvFun and those more complicates ones who were moved to module TcEvTerm | Any sort of evidence Id, including coercions coercion bindings See Note [Coercion evidence terms] | d |> co Dictionary instance application Selector id plus the types at which it dictionaries; see Note [HasField instances] ^ Dictionary for @Typeable T@ where @T@ is a type constructor with all of the applied kinds.. ^ Dictionary for a type literal, e.g. @Typeable "foo"@ or @Typeable 3@ | Evidence for @CallStack@ implicit parameters. Assume class (..., D ty, ...) => C a b D ty[ty1/a,ty2/b] See Note [Coercion evidence terms] ********************************************************************* * * Free variables * * ********************************************************************* Find all the Given evidence needed by seeds, looking transitively through binds It's OK to use nonDetFoldUFM here because we immediately forget about the ordering by creating a set See Note [Free vars of EvFun] With -fprint-typechecker-elaboration, print the wrapper otherwise just print what's inside it's in a position that needs parens for a non-atomic thing True <=> appears in function application position False <=> appears as body of let or lambda We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing Not very pretty -------------------------------------------------------------------- Helper functions for dealing with IP newtype-dictionaries -------------------------------------------------------------------- | Create a 'Coercion' that unwraps an implicit-parameter or overloaded-label dictionary to expose the underlying value. We | Create a 'Coercion' that wraps a value in an implicit-parameter dictionary. See 'unwrapIP'.
( c ) The University of Glasgow 2006 # LANGUAGE CPP , DeriveDataTypeable # module TcEvidence ( HsWrapper HsWrapper(..), (<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams, mkWpLams, mkWpLet, mkWpCastN, mkWpCastR, collectHsWrapBinders, mkWpFun, idHsWrapper, isIdHsWrapper, isErasableHsWrapper, pprHsWrapper, TcEvBinds(..), EvBindsVar(..), EvBindMap(..), emptyEvBindMap, extendEvBinds, lookupEvBind, evBindMapBinds, foldEvBindMap, filterEvBindMap, isEmptyEvBindMap, EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind, evBindVar, isCoEvBindsVar, EvTerm ( already a CoreExpr ) EvTerm(..), EvExpr, evId, evCoercion, evCast, evDFunApp, evDataConApp, evSelector, mkEvCast, evVarsOfTerm, mkEvScSelectors, evTypeable, findNeededEvVars, evTermCoercion, evTermCoercion_maybe, EvCallStack(..), EvTypeable(..), TcCoercion, TcCoercionR, TcCoercionN, TcCoercionP, CoercionHole, TcMCoercion, Role(..), LeftOrRight(..), pickLR, mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo, mkTcTyConAppCo, mkTcAppCo, mkTcFunCo, mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos, mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo, tcDowngradeRole, mkTcAxiomRuleCo, mkTcGReflRightCo, mkTcGReflLeftCo, mkTcPhantomCo, mkTcCoherenceLeftCo, mkTcCoherenceRightCo, mkTcKindCo, tcCoercionKind, coVarsOfTcCo, mkTcCoVarCo, isTcReflCo, isTcReflexiveCo, isTcGReflMCo, tcCoToMCo, tcCoercionRole, unwrapIP, wrapIP ) where #include "HsVersions2.h" import GhcPrelude import Var import CoAxiom import Coercion Instance OutputableBndr TyVar import TcType import Type import TyCon import DataCon( DataCon, dataConWrapId ) import Class( Class ) import PrelNames import DynFlags ( gopt, GeneralFlag(Opt_PrintTypecheckerElaboration) ) import VarEnv import VarSet import Predicate import Name import Pair import CoreSyn import Class ( classSCSelId ) import CoreFVs ( exprSomeFreeVars ) import Util import Bag import qualified Data.Data as Data import Outputable import SrcLoc import Data.IORef( IORef ) import UniqSet Note [ TcCoercions ] ~~~~~~~~~~~~~~~~~~ | TcCoercions are a hack used by the typechecker . Normally , Coercions have free variables of type ( a ~ # b ): we call these CoVars . However , the type checker passes around equality evidence ( boxed up ) at type ( a ~ b ) . An TcCoercion is simply a Coercion whose free variables have may be either boxed or unboxed . After we are done with typechecking the desugarer finds the boxed free variables , unboxes them , and creates a resulting real Coercion with kosher free variables . Note [TcCoercions] ~~~~~~~~~~~~~~~~~~ | TcCoercions are a hack used by the typechecker. Normally, Coercions have free variables of type (a ~# b): we call these CoVars. However, the type checker passes around equality evidence (boxed up) at type (a ~ b). An TcCoercion is simply a Coercion whose free variables have may be either boxed or unboxed. After we are done with typechecking the desugarer finds the boxed free variables, unboxes them, and creates a resulting real Coercion with kosher free variables. -} type TcCoercion = Coercion A Nominal coercion ~N A Representational coercion type TcMCoercion = MCoercion mkTcReflCo :: Role -> TcType -> TcCoercion mkTcSymCo :: TcCoercion -> TcCoercion mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion mkTcNomReflCo :: TcType -> TcCoercionN mkTcRepReflCo :: TcType -> TcCoercionR mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion mkTcAppCo :: TcCoercion -> TcCoercionN -> TcCoercion mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion mkTcAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [TcType] -> [TcCoercion] -> TcCoercion mkTcUnbranchedAxInstCo :: CoAxiom Unbranched -> [TcType] -> [TcCoercion] -> TcCoercionR mkTcForAllCo :: TyVar -> TcCoercionN -> TcCoercion -> TcCoercion mkTcForAllCos :: [(TyVar, TcCoercionN)] -> TcCoercion -> TcCoercion mkTcNthCo :: Role -> Int -> TcCoercion -> TcCoercion mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion mkTcSubCo :: TcCoercionN -> TcCoercionR tcDowngradeRole :: Role -> Role -> TcCoercion -> TcCoercion mkTcAxiomRuleCo :: CoAxiomRule -> [TcCoercion] -> TcCoercionR mkTcGReflRightCo :: Role -> TcType -> TcCoercionN -> TcCoercion mkTcGReflLeftCo :: Role -> TcType -> TcCoercionN -> TcCoercion mkTcCoherenceLeftCo :: Role -> TcType -> TcCoercionN -> TcCoercion -> TcCoercion mkTcCoherenceRightCo :: Role -> TcType -> TcCoercionN -> TcCoercion -> TcCoercion mkTcPhantomCo :: TcCoercionN -> TcType -> TcType -> TcCoercionP mkTcKindCo :: TcCoercion -> TcCoercionN mkTcCoVarCo :: CoVar -> TcCoercion tcCoercionKind :: TcCoercion -> Pair TcType tcCoercionRole :: TcCoercion -> Role coVarsOfTcCo :: TcCoercion -> TcTyCoVarSet isTcReflCo :: TcCoercion -> Bool isTcGReflMCo :: TcMCoercion -> Bool isTcReflexiveCo :: TcCoercion -> Bool mkTcReflCo = mkReflCo mkTcSymCo = mkSymCo mkTcTransCo = mkTransCo mkTcNomReflCo = mkNomReflCo mkTcRepReflCo = mkRepReflCo mkTcTyConAppCo = mkTyConAppCo mkTcAppCo = mkAppCo mkTcFunCo = mkFunCo mkTcAxInstCo = mkAxInstCo mkTcUnbranchedAxInstCo = mkUnbranchedAxInstCo Representational mkTcForAllCo = mkForAllCo mkTcForAllCos = mkForAllCos mkTcNthCo = mkNthCo mkTcLRCo = mkLRCo mkTcSubCo = mkSubCo tcDowngradeRole = downgradeRole mkTcAxiomRuleCo = mkAxiomRuleCo mkTcGReflRightCo = mkGReflRightCo mkTcGReflLeftCo = mkGReflLeftCo mkTcCoherenceLeftCo = mkCoherenceLeftCo mkTcCoherenceRightCo = mkCoherenceRightCo mkTcPhantomCo = mkPhantomCo mkTcKindCo = mkKindCo mkTcCoVarCo = mkCoVarCo tcCoercionKind = coercionKind tcCoercionRole = coercionRole coVarsOfTcCo = coVarsOfCo isTcReflCo = isReflCo isTcGReflMCo = isGReflMCo isTcReflexiveCo = isReflexiveCo tcCoToMCo :: TcCoercion -> TcMCoercion tcCoToMCo = coToMCo | If the is , makes a SubCo ; otherwise , does nothing . maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion maybeTcSubCo NomEq = id maybeTcSubCo ReprEq = mkTcSubCo % * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * % * * HsWrapper * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * %************************************************************************ %* * HsWrapper * * ************************************************************************ -} data HsWrapper | WpCompose HsWrapper HsWrapper ( ` ` wrap2)[e ] = [ wrap2 [ e ] ] Hence ( \a . [ ] ) ` WpCompose ` ( \b . [ ] ) = ( \a b. [ ] ) But ( [ ] a ) ` ` ( [ ] b ) = ( [ ] b a ) | WpFun HsWrapper HsWrapper TcType SDoc ( WpFun wrap1 wrap2 t1)[e ] = \(x : t1 ) . wrap2 [ e wrap1[x ] ] So note that if : : exp_arg < = act_arg then WpFun wrap1 wrap2 : ( act_arg - > arg_res ) < = ( exp_arg - > exp_res ) because we ca n't use ' sym ' to flip around these HsWrappers The TcType is the " from " type of the first wrapper The SDoc explains the circumstances under which we have created this the desugarer . See Note [ Levity polymorphism checking ] in DsMonad At role Representational \d . [ ] the 'd ' is an evidence variable \a . [ ] the ' a ' is a type / kind variable ( not coercion var ) so that the identity coercion is always exactly WpHole Can not derive Data instance because SDoc is not Data ( it stores a function ) . instance Data.Data HsWrapper where gfoldl _ z WpHole = z WpHole gfoldl k z (WpCompose a1 a2) = z WpCompose `k` a1 `k` a2 gfoldl k z (WpFun a1 a2 a3 _) = z wpFunEmpty `k` a1 `k` a2 `k` a3 gfoldl k z (WpCast a1) = z WpCast `k` a1 gfoldl k z (WpEvLam a1) = z WpEvLam `k` a1 gfoldl k z (WpEvApp a1) = z WpEvApp `k` a1 gfoldl k z (WpTyLam a1) = z WpTyLam `k` a1 gfoldl k z (WpTyApp a1) = z WpTyApp `k` a1 gfoldl k z (WpLet a1) = z WpLet `k` a1 gunfold k z c = case Data.constrIndex c of 1 -> z WpHole 2 -> k (k (z WpCompose)) 3 -> k (k (k (z wpFunEmpty))) 4 -> k (z WpCast) 5 -> k (z WpEvLam) 6 -> k (z WpEvApp) 7 -> k (z WpTyLam) 8 -> k (z WpTyApp) _ -> k (z WpLet) toConstr WpHole = wpHole_constr toConstr (WpCompose _ _) = wpCompose_constr toConstr (WpFun _ _ _ _) = wpFun_constr toConstr (WpCast _) = wpCast_constr toConstr (WpEvLam _) = wpEvLam_constr toConstr (WpEvApp _) = wpEvApp_constr toConstr (WpTyLam _) = wpTyLam_constr toConstr (WpTyApp _) = wpTyApp_constr toConstr (WpLet _) = wpLet_constr dataTypeOf _ = hsWrapper_dataType hsWrapper_dataType :: Data.DataType hsWrapper_dataType = Data.mkDataType "HsWrapper" [ wpHole_constr, wpCompose_constr, wpFun_constr, wpCast_constr , wpEvLam_constr, wpEvApp_constr, wpTyLam_constr, wpTyApp_constr , wpLet_constr] wpHole_constr, wpCompose_constr, wpFun_constr, wpCast_constr, wpEvLam_constr, wpEvApp_constr, wpTyLam_constr, wpTyApp_constr, wpLet_constr :: Data.Constr wpHole_constr = mkHsWrapperConstr "WpHole" wpCompose_constr = mkHsWrapperConstr "WpCompose" wpFun_constr = mkHsWrapperConstr "WpFun" wpCast_constr = mkHsWrapperConstr "WpCast" wpEvLam_constr = mkHsWrapperConstr "WpEvLam" wpEvApp_constr = mkHsWrapperConstr "WpEvApp" wpTyLam_constr = mkHsWrapperConstr "WpTyLam" wpTyApp_constr = mkHsWrapperConstr "WpTyApp" wpLet_constr = mkHsWrapperConstr "WpLet" mkHsWrapperConstr :: String -> Data.Constr mkHsWrapperConstr name = Data.mkConstr hsWrapper_dataType name [] Data.Prefix wpFunEmpty :: HsWrapper -> HsWrapper -> TcType -> HsWrapper wpFunEmpty c1 c2 t1 = WpFun c1 c2 t1 empty (<.>) :: HsWrapper -> HsWrapper -> HsWrapper WpHole <.> c = c c <.> WpHole = c c1 <.> c2 = c1 `WpCompose` c2 mkWpFun :: HsWrapper -> HsWrapper the " from " type of the first wrapper either type of the second wrapper ( used only when the second wrapper is the identity ) -> HsWrapper mkWpFun WpHole WpHole _ _ _ = WpHole mkWpFun WpHole (WpCast co2) t1 _ _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2) mkWpFun (WpCast co1) WpHole _ t2 _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2)) mkWpFun (WpCast co1) (WpCast co2) _ _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2) mkWpFun co1 co2 t1 _ d = WpFun co1 co2 t1 d mkWpCastR :: TcCoercionR -> HsWrapper mkWpCastR co | isTcReflCo co = WpHole | otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co) WpCast co mkWpCastN :: TcCoercionN -> HsWrapper mkWpCastN co | isTcReflCo co = WpHole | otherwise = ASSERT2(tcCoercionRole co == Nominal, ppr co) WpCast (mkTcSubCo co) The mkTcSubCo converts to Representational mkWpTyApps :: [Type] -> HsWrapper mkWpTyApps tys = mk_co_app_fn WpTyApp tys mkWpEvApps :: [EvTerm] -> HsWrapper mkWpEvApps args = mk_co_app_fn WpEvApp args mkWpEvVarApps :: [EvVar] -> HsWrapper mkWpEvVarApps vs = mk_co_app_fn WpEvApp (map (EvExpr . evId) vs) mkWpTyLams :: [TyVar] -> HsWrapper mkWpTyLams ids = mk_co_lam_fn WpTyLam ids mkWpLams :: [Var] -> HsWrapper mkWpLams ids = mk_co_lam_fn WpEvLam ids mkWpLet :: TcEvBinds -> HsWrapper mkWpLet (EvBinds b) | isEmptyBag b = WpHole mkWpLet ev_binds = WpLet ev_binds mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper For applications , the * first * argument must mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as idHsWrapper :: HsWrapper idHsWrapper = WpHole isIdHsWrapper :: HsWrapper -> Bool isIdHsWrapper WpHole = True isIdHsWrapper _ = False isErasableHsWrapper :: HsWrapper -> Bool isErasableHsWrapper = go where go WpHole = True go (WpCompose wrap1 wrap2) = go wrap1 && go wrap2 go WpFun{} = False go WpCast{} = True go WpEvApp{} = False go WpTyLam{} = True go WpTyApp{} = True go WpLet{} = False collectHsWrapBinders :: HsWrapper -> ([Var], HsWrapper) Collect the outer lambda binders of a HsWrapper , collectHsWrapBinders wrap = go wrap [] where go :: HsWrapper -> [HsWrapper] -> ([Var], HsWrapper) go (WpEvLam v) wraps = add_lam v (gos wraps) go (WpTyLam v) wraps = add_lam v (gos wraps) go (WpCompose w1 w2) wraps = go w1 (w2:wraps) go wrap wraps = ([], foldl' (<.>) wrap wraps) gos [] = ([], WpHole) gos (w:ws) = go w ws add_lam v (vs,w) = (v:vs, w) data TcEvBinds (Bag EvBind) data EvBindsVar = EvBindsVar { ebv_uniq :: Unique, ebv_binds :: IORef EvBindMap, ebv_tcvs :: IORef CoVarSet are solved by filling in their HoleDest in - place . Since they } ebv_uniq :: Unique, ebv_tcvs :: IORef CoVarSet } instance Data.Data TcEvBinds where Placeholder ; we ca n't travers into TcEvBinds toConstr _ = abstractConstr "TcEvBinds" gunfold _ _ = error "gunfold" dataTypeOf _ = Data.mkNoRepType "TcEvBinds" Note [ Coercion evidence only ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class constraints etc give rise to /term/ bindings for evidence , and we have nowhere to put term bindings in /types/. So in some places we use CoEvBindsVar ( see newCoTcEvBinds ) to signal that no term - level evidence bindings are allowed . ( ): - Places in types where we are solving kind constraints ( all of which are equalities ) ; see solveEqualities , solveLocalEqualities , checkTvConstraints - When unifying forall - types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class constraints etc give rise to /term/ bindings for evidence, and we have nowhere to put term bindings in /types/. So in some places we use CoEvBindsVar (see newCoTcEvBinds) to signal that no term-level evidence bindings are allowed. Notebly (): - Places in types where we are solving kind constraints (all of which are equalities); see solveEqualities, solveLocalEqualities, checkTvConstraints - When unifying forall-types -} isCoEvBindsVar :: EvBindsVar -> Bool isCoEvBindsVar (CoEvBindsVar {}) = True isCoEvBindsVar (EvBindsVar {}) = False newtype EvBindMap = EvBindMap { ev_bind_varenv :: DVarEnv EvBind We use here to get deterministic ordering when we let in emptyEvBindMap :: EvBindMap emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyDVarEnv } extendEvBinds :: EvBindMap -> EvBind -> EvBindMap extendEvBinds bs ev_bind = EvBindMap { ev_bind_varenv = extendDVarEnv (ev_bind_varenv bs) (eb_lhs ev_bind) ev_bind } isEmptyEvBindMap :: EvBindMap -> Bool isEmptyEvBindMap (EvBindMap m) = isEmptyDVarEnv m lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind lookupEvBind bs = lookupDVarEnv (ev_bind_varenv bs) evBindMapBinds :: EvBindMap -> Bag EvBind evBindMapBinds = foldEvBindMap consBag emptyBag foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a foldEvBindMap k z bs = foldDVarEnv k z (ev_bind_varenv bs) filterEvBindMap :: (EvBind -> Bool) -> EvBindMap -> EvBindMap filterEvBindMap k (EvBindMap { ev_bind_varenv = env }) = EvBindMap { ev_bind_varenv = filterDVarEnv k env } instance Outputable EvBindMap where ppr (EvBindMap m) = ppr m All evidence is bound by ; no side effects data EvBind = EvBind { eb_lhs :: EvVar , eb_rhs :: EvTerm } evBindVar :: EvBind -> EvVar evBindVar = eb_lhs mkWantedEvBind :: EvVar -> EvTerm -> EvBind mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm } EvTypeable are never given , so we can work with EvExpr here instead of EvTerm mkGivenEvBind :: EvVar -> EvTerm -> EvBind mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm } An EvTerm is , conceptually , a CoreExpr that implements the constraint . type EvTerm = CoreExpr Because of staging problems issues around data EvTerm = EvExpr EvExpr Dictionary for ( ) /\as \ds . let binds in v { et_tvs :: [TyVar] , et_given :: [EvVar] constructor , and ca n't just use EvExpr , et_body :: EvVar } deriving Data.Data type EvExpr = CoreExpr An EvTerm is ( usually ) constructed by any of the constructors here evId :: EvId -> EvExpr evId = Var evCoercion :: TcCoercion -> EvTerm evCoercion co = EvExpr (Coercion co) evCast :: EvExpr -> TcCoercion -> EvTerm evCast et tc | isReflCo tc = EvExpr et | otherwise = EvExpr (Cast et tc) evDFunApp :: DFunId -> [Type] -> [EvExpr] -> EvTerm evDFunApp df tys ets = EvExpr $ Var df `mkTyApps` tys `mkApps` ets evDataConApp :: DataCon -> [Type] -> [EvExpr] -> EvTerm evDataConApp dc tys ets = evDFunApp (dataConWrapId dc) tys ets should be instantiated , used for HasField in TcInterface evSelector :: Id -> [Type] -> [EvExpr] -> EvExpr evSelector sel_id tys tms = Var sel_id `mkTyApps` tys `mkApps` tms Dictionary for ( ) evTypeable :: Type -> EvTypeable -> EvTerm evTypeable = EvTypeable | Instructions on how to make a ' ' dictionary . See Note [ Typeable evidence terms ] data EvTypeable = EvTypeableTyCon TyCon [EvTerm] its kind variables saturated . The @[EvTerm]@ is @Typeable@ evidence for | EvTypeableTyApp EvTerm EvTerm ^ Dictionary for ( s t)@ , given a dictionaries for @s@ and | EvTypeableTrFun EvTerm EvTerm ^ Dictionary for ( s - > t)@ , given a dictionaries for @s@ and | EvTypeableTyLit EvTerm The ' EvTerm ' is evidence of , e.g. , @KnownNat 3@ ( see # 10348 ) deriving Data.Data data EvCallStack See Note [ Overview of implicit CallStacks ] = EvCsEmpty | EvCsPushCall Name RealSrcSpan EvExpr ^ @EvCsPushCall name represents a call to @name@ , occurring at @loc@ , in a calling context @stk@. deriving Data.Data Note [ Typeable evidence terms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The EvTypeable data type looks isomorphic to Type , but the EvTerms inside can be EvIds . Eg f : : forall a. Typeable a = > a - > TypeRep f x = typeRep ( undefined : : Proxy [ a ] ) Here for the ( Typeable [ a ] ) dictionary passed to typeRep we make evidence dl : : [ a ] = EvTypeable [ a ] ( EvTypeableTyApp ( EvTypeableTyCon [ ] ) ( EvId d ) ) where d : : Typable a is the lambda - bound dictionary passed into f. Note [ Coercion evidence terms ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A " coercion evidence term " takes one of these forms co_tm : : = EvId v where v : : t1 ~ # t2 | EvCoercion co | EvCast co_tm co We do quite often need to get a TcCoercion from an EvTerm ; see ' evTermCoercion ' . INVARIANT : The evidence for any constraint with type ( t1 ~ # t2 ) is a coercion evidence term . Consider for example [ G ] d : : F Int a If we have ax7 a : : F Int a ~ ( a ~ Bool ) then we do NOT generate the constraint [ G ] ( d | > ax7 a ) : : a ~ Bool because that does not satisfy the invariant ( d is not a coercion variable ) . Instead we make a binding g1 : : a ~ Bool = g | > ax7 a and the constraint [ G ] g1 : : a ~ Bool See # 7238 and Note [ Bind new Givens immediately ] in Constraint Note [ EvBinds / EvTerm ] ~~~~~~~~~~~~~~~~~~~~~ How evidence is created and updated . Bindings for dictionaries , and coercions and implicit parameters are carried around in TcEvBinds which during constraint generation and simplification is always of the form ( TcEvBinds ref ) . After constraint simplification is finished it will be transformed to t an ( ) . Evidence for coercions * SHOULD * be filled in using the TcEvBinds However , all that correspond to * wanted * coercion terms in an EvBind must be mutable variables so that they can be readily inlined ( by zonking ) after constraint simplification is finished . Conclusion : a new wanted coercion variable should be made mutable . [ Notice though that evidence variables that bind coercion terms from super classes will be " given " and hence rigid ] Note [ Overview of implicit CallStacks ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( See -call-stack/implicit-locations ) The goal of CallStack evidence terms is to reify locations in the program source as runtime values , without any support from the RTS . We accomplish this by assigning a special meaning to constraints of type GHC.Stack . Types . HasCallStack , an alias type HasCallStack = ( ? : : ) Implicit parameters of type GHC.Stack . Types . ( the name is not important ) are solved in three steps : 1 . Occurrences of CallStack IPs are solved directly from the given IP , just like a regular IP . For example , the occurrence of ` ? in error : : ( ? : : ) = > String - > a error s = raise ( ErrorCall ( s + + prettyCallStack ? ) ) will be solved for the ` ? in ` error`s context as before . 2 . In a function call , instead of simply passing the given IP , we first append the current call - site to it . For example , consider a call to the - aware ` error ` above . undefined : : ( ? : : ) = > a undefined = error " undefined ! " Here we want to take the given ` ? ` and append the current call - site , before passing it to ` error ` . In essence , we want to rewrite ` error " undefined ! " ` to let ? stk = pushCallStack < error 's location > ? stk in error " undefined ! " We achieve this effect by emitting a NEW wanted [ W ] d : : IP " stk " CallStack from which we build the evidence term EvCsPushCall " error " < error 's location > ( EvId d ) that we use to solve the call to ` error ` . The new wanted ` d ` will then be solved per rule ( 1 ) , ie as a regular IP . ( see TcInteract.interactDict ) 3 . We default any insoluble CallStacks to the empty CallStack . Suppose ` undefined ` did not request a CallStack , ie undefinedNoStk : : a undefinedNoStk = error " undefined ! " Under the usual IP rules , the new wanted from rule ( 2 ) would be insoluble as there 's no given IP from which to solve it , so we would get an " unbound implicit parameter " error . We do n't ever want to emit an insoluble , so we add a defaulting pass to default any remaining wanted CallStacks to the empty CallStack with the evidence term EvCsEmpty ( see TcSimplify.simpl_top and TcSimplify.defaultCallStacks ) This provides a lightweight mechanism for building up call - stacks explicitly , but is notably limited by the fact that the stack will stop at the first function whose type does not include a CallStack IP . For example , using the above definition of ` undefined ` : head : : [ a ] - > a head [ ] = undefined head ( x : _ ) = x g = head [ ] the resulting CallStack will include the call to ` undefined ` in ` head ` and the call to ` error ` in ` undefined ` , but * not * the call to ` head ` in ` g ` , because ` head ` did not explicitly request a CallStack . Important Details : - GHC should NEVER report an insoluble CallStack constraint . - GHC should NEVER infer a CallStack constraint unless one was requested with a partial type signature ( See TcType.pickQuantifiablePreds ) . - A CallStack ( defined in GHC.Stack . Types ) is a [ ( String , SrcLoc ) ] , where the is the name of the binder that is used at the SrcLoc . is also defined in GHC.Stack . Types and contains the package / module / file name , as well as the full source - span . Both CallStack and SrcLoc are kept abstract so only GHC can construct new values . - We will automatically solve any wanted CallStack regardless of the name of the IP , i.e. f = show ( ? : : ) g = show ( ? : : ) are both valid . However , we will only push new SrcLocs onto existing CallStacks when the IP names match , e.g. in head : : ( ? : : ) = > [ a ] - > a head [ ] = error ( show ( ? : : ) ) the printed CallStack will NOT include head 's call - site . This reflects the standard scoping rules of implicit - parameters . - An EvCallStack term desugars to a CoreExpr of type ` IP " some str " CallStack ` . The desugarer will need to unwrap the IP newtype before pushing a new call - site onto a given stack ( See DsBinds.dsEvCallStack ) - When we emit a new wanted CallStack from rule ( 2 ) we set its origin to ` IPOccOrigin ip_name ` instead of the original ` OccurrenceOf func ` ( see TcInteract.interactDict ) . This is a bit shady , but is how we ensure that the new wanted is solved like a regular IP . Note [Typeable evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The EvTypeable data type looks isomorphic to Type, but the EvTerms inside can be EvIds. Eg f :: forall a. Typeable a => a -> TypeRep f x = typeRep (undefined :: Proxy [a]) Here for the (Typeable [a]) dictionary passed to typeRep we make evidence dl :: Typeable [a] = EvTypeable [a] (EvTypeableTyApp (EvTypeableTyCon []) (EvId d)) where d :: Typable a is the lambda-bound dictionary passed into f. Note [Coercion evidence terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A "coercion evidence term" takes one of these forms co_tm ::= EvId v where v :: t1 ~# t2 | EvCoercion co | EvCast co_tm co We do quite often need to get a TcCoercion from an EvTerm; see 'evTermCoercion'. INVARIANT: The evidence for any constraint with type (t1 ~# t2) is a coercion evidence term. Consider for example [G] d :: F Int a If we have ax7 a :: F Int a ~ (a ~ Bool) then we do NOT generate the constraint [G] (d |> ax7 a) :: a ~ Bool because that does not satisfy the invariant (d is not a coercion variable). Instead we make a binding g1 :: a~Bool = g |> ax7 a and the constraint [G] g1 :: a~Bool See #7238 and Note [Bind new Givens immediately] in Constraint Note [EvBinds/EvTerm] ~~~~~~~~~~~~~~~~~~~~~ How evidence is created and updated. Bindings for dictionaries, and coercions and implicit parameters are carried around in TcEvBinds which during constraint generation and simplification is always of the form (TcEvBinds ref). After constraint simplification is finished it will be transformed to t an (EvBinds ev_bag). Evidence for coercions *SHOULD* be filled in using the TcEvBinds However, all EvVars that correspond to *wanted* coercion terms in an EvBind must be mutable variables so that they can be readily inlined (by zonking) after constraint simplification is finished. Conclusion: a new wanted coercion variable should be made mutable. [Notice though that evidence variables that bind coercion terms from super classes will be "given" and hence rigid] Note [Overview of implicit CallStacks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (See -call-stack/implicit-locations) The goal of CallStack evidence terms is to reify locations in the program source as runtime values, without any support from the RTS. We accomplish this by assigning a special meaning to constraints of type GHC.Stack.Types.HasCallStack, an alias type HasCallStack = (?callStack :: CallStack) Implicit parameters of type GHC.Stack.Types.CallStack (the name is not important) are solved in three steps: 1. Occurrences of CallStack IPs are solved directly from the given IP, just like a regular IP. For example, the occurrence of `?stk` in error :: (?stk :: CallStack) => String -> a error s = raise (ErrorCall (s ++ prettyCallStack ?stk)) will be solved for the `?stk` in `error`s context as before. 2. In a function call, instead of simply passing the given IP, we first append the current call-site to it. For example, consider a call to the callstack-aware `error` above. undefined :: (?stk :: CallStack) => a undefined = error "undefined!" Here we want to take the given `?stk` and append the current call-site, before passing it to `error`. In essence, we want to rewrite `error "undefined!"` to let ?stk = pushCallStack <error's location> ?stk in error "undefined!" We achieve this effect by emitting a NEW wanted [W] d :: IP "stk" CallStack from which we build the evidence term EvCsPushCall "error" <error's location> (EvId d) that we use to solve the call to `error`. The new wanted `d` will then be solved per rule (1), ie as a regular IP. (see TcInteract.interactDict) 3. We default any insoluble CallStacks to the empty CallStack. Suppose `undefined` did not request a CallStack, ie undefinedNoStk :: a undefinedNoStk = error "undefined!" Under the usual IP rules, the new wanted from rule (2) would be insoluble as there's no given IP from which to solve it, so we would get an "unbound implicit parameter" error. We don't ever want to emit an insoluble CallStack IP, so we add a defaulting pass to default any remaining wanted CallStacks to the empty CallStack with the evidence term EvCsEmpty (see TcSimplify.simpl_top and TcSimplify.defaultCallStacks) This provides a lightweight mechanism for building up call-stacks explicitly, but is notably limited by the fact that the stack will stop at the first function whose type does not include a CallStack IP. For example, using the above definition of `undefined`: head :: [a] -> a head [] = undefined head (x:_) = x g = head [] the resulting CallStack will include the call to `undefined` in `head` and the call to `error` in `undefined`, but *not* the call to `head` in `g`, because `head` did not explicitly request a CallStack. Important Details: - GHC should NEVER report an insoluble CallStack constraint. - GHC should NEVER infer a CallStack constraint unless one was requested with a partial type signature (See TcType.pickQuantifiablePreds). - A CallStack (defined in GHC.Stack.Types) is a [(String, SrcLoc)], where the String is the name of the binder that is used at the SrcLoc. SrcLoc is also defined in GHC.Stack.Types and contains the package/module/file name, as well as the full source-span. Both CallStack and SrcLoc are kept abstract so only GHC can construct new values. - We will automatically solve any wanted CallStack regardless of the name of the IP, i.e. f = show (?stk :: CallStack) g = show (?loc :: CallStack) are both valid. However, we will only push new SrcLocs onto existing CallStacks when the IP names match, e.g. in head :: (?loc :: CallStack) => [a] -> a head [] = error (show (?stk :: CallStack)) the printed CallStack will NOT include head's call-site. This reflects the standard scoping rules of implicit-parameters. - An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`. The desugarer will need to unwrap the IP newtype before pushing a new call-site onto a given stack (See DsBinds.dsEvCallStack) - When we emit a new wanted CallStack from rule (2) we set its origin to `IPOccOrigin ip_name` instead of the original `OccurrenceOf func` (see TcInteract.interactDict). This is a bit shady, but is how we ensure that the new wanted is solved like a regular IP. -} mkEvCast :: EvExpr -> TcCoercion -> EvTerm mkEvCast ev lco | ASSERT2( tcCoercionRole lco == Representational , (vcat [text "Coercion of wrong role passed to mkEvCast:", ppr ev, ppr lco])) isTcReflCo lco = EvExpr ev | otherwise = evCast ev lco C : : C - > D ty[ty1 / a , ty2 / b ] ] mkEvScSelectors cls tys = zipWith mk_pr (immSuperClasses cls tys) [0..] where mk_pr pred i = (pred, Var sc_sel_id `mkTyApps` tys) where Zero - indexed emptyTcEvBinds :: TcEvBinds emptyTcEvBinds = EvBinds emptyBag isEmptyTcEvBinds :: TcEvBinds -> Bool isEmptyTcEvBinds (EvBinds b) = isEmptyBag b isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds" evTermCoercion_maybe :: EvTerm -> Maybe TcCoercion Applied only to EvTerms of type ( s ~ t ) evTermCoercion_maybe ev_term | EvExpr e <- ev_term = go e | otherwise = Nothing where go :: EvExpr -> Maybe TcCoercion go (Var v) = return (mkCoVarCo v) go (Coercion co) = return co go (Cast tm co) = do { co' <- go tm ; return (mkCoCast co' co) } go _ = Nothing evTermCoercion :: EvTerm -> TcCoercion evTermCoercion tm = case evTermCoercion_maybe tm of Just co -> co Nothing -> pprPanic "evTermCoercion" (ppr tm) findNeededEvVars :: EvBindMap -> VarSet -> VarSet findNeededEvVars ev_binds seeds = transCloVarSet also_needs seeds where also_needs :: VarSet -> VarSet also_needs needs = nonDetFoldUniqSet add emptyVarSet needs add :: Var -> VarSet -> VarSet add v needs | Just ev_bind <- lookupEvBind ev_binds v , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind , is_given = evVarsOfTerm rhs `unionVarSet` needs | otherwise = needs evVarsOfTerm :: EvTerm -> VarSet evVarsOfTerm (EvExpr e) = exprSomeFreeVars isEvVar e evVarsOfTerm (EvTypeable _ ev) = evVarsOfTypeable ev evVarsOfTerms :: [EvTerm] -> VarSet evVarsOfTerms = mapUnionVarSet evVarsOfTerm evVarsOfTypeable :: EvTypeable -> VarSet evVarsOfTypeable ev = case ev of EvTypeableTyCon _ e -> mapUnionVarSet evVarsOfTerm e EvTypeableTyApp e1 e2 -> evVarsOfTerms [e1,e2] EvTypeableTrFun e1 e2 -> evVarsOfTerms [e1,e2] EvTypeableTyLit e -> evVarsOfTerm e Note [ Free vars of EvFun ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finding the free vars of an EvFun is made tricky by the fact the bindings et_binds may be a mutable variable . Fortunately , we can just squeeze by . Here 's how . * evVarsOfTerm is used only by TcSimplify.neededEvVars . * Each EvBindsVar in an et_binds field of an EvFun is /also/ in the ic_binds field of an Implication * So we can track usage via the processing for that implication , ( see Note [ Tracking redundant constraints ] in TcSimplify ) . We can ignore usage from the EvFun altogether . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Pretty printing * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finding the free vars of an EvFun is made tricky by the fact the bindings et_binds may be a mutable variable. Fortunately, we can just squeeze by. Here's how. * evVarsOfTerm is used only by TcSimplify.neededEvVars. * Each EvBindsVar in an et_binds field of an EvFun is /also/ in the ic_binds field of an Implication * So we can track usage via the processing for that implication, (see Note [Tracking redundant constraints] in TcSimplify). We can ignore usage from the EvFun altogether. ************************************************************************ * * Pretty printing * * ************************************************************************ -} instance Outputable HsWrapper where ppr co_fn = pprHsWrapper co_fn (no_parens (text "<>")) pprHsWrapper :: HsWrapper -> (Bool -> SDoc) -> SDoc The pp_thing_inside function takes to say whether pprHsWrapper wrap pp_thing_inside = sdocWithDynFlags $ \ dflags -> if gopt Opt_PrintTypecheckerElaboration dflags then help pp_thing_inside wrap False else pp_thing_inside False where help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc help it WpHole = it help it (WpCompose f1 f2) = help (help it f2) f1 help it (WpFun f1 f2 t1 _) = add_parens $ text "\\(x" <> dcolon <> ppr t1 <> text ")." <+> help (\_ -> it True <+> help (\_ -> text "x") f1 True) f2 False help it (WpCast co) = add_parens $ sep [it False, nest 2 (text "|>" <+> pprParendCo co)] help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)] help it (WpTyApp ty) = no_parens $ sep [it True, text "@" <+> pprParendType ty] help it (WpEvLam id) = add_parens $ sep [ text "\\" <> pprLamBndr id <> dot, it False] help it (WpTyLam tv) = add_parens $ sep [text "/\\" <> pprLamBndr tv <> dot, it False] help it (WpLet binds) = add_parens $ sep [text "let" <+> braces (ppr binds), it False] pprLamBndr :: Id -> SDoc pprLamBndr v = pprBndr LambdaBind v add_parens, no_parens :: SDoc -> Bool -> SDoc add_parens d True = parens d add_parens d False = d no_parens d _ = d instance Outputable TcEvBinds where ppr (TcEvBinds v) = ppr v ppr (EvBinds bs) = text "EvBinds" <> braces (vcat (map ppr (bagToList bs))) instance Outputable EvBindsVar where ppr (EvBindsVar { ebv_uniq = u }) = text "EvBindsVar" <> angleBrackets (ppr u) ppr (CoEvBindsVar { ebv_uniq = u }) = text "CoEvBindsVar" <> angleBrackets (ppr u) instance Uniquable EvBindsVar where getUnique = ebv_uniq instance Outputable EvBind where ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given }) = sep [ pp_gw <+> ppr v , nest 2 $ equals <+> ppr e ] where pp_gw = brackets (if is_given then char 'G' else char 'W') instance Outputable EvTerm where ppr (EvExpr e) = ppr e ppr (EvTypeable ty ev) = ppr ev <+> dcolon <+> text "Typeable" <+> ppr ty ppr (EvFun { et_tvs = tvs, et_given = gs, et_binds = bs, et_body = w }) = hang (text "\\" <+> sep (map pprLamBndr (tvs ++ gs)) <+> arrow) instance Outputable EvCallStack where ppr EvCsEmpty = text "[]" ppr (EvCsPushCall name loc tm) = ppr (name,loc) <+> text ":" <+> ppr tm instance Outputable EvTypeable where ppr (EvTypeableTyCon ts _) = text "TyCon" <+> ppr ts ppr (EvTypeableTyApp t1 t2) = parens (ppr t1 <+> ppr t2) ppr (EvTypeableTrFun t1 t2) = parens (ppr t1 <+> arrow <+> ppr t2) ppr (EvTypeableTyLit t1) = text "TyLit" <> ppr t1 expect the ' Type ' to have the form ` IP sym ty ` or ` IsLabel , and return a ' Coercion ' ` co : : IP or ` co : : ~ Proxy # sym - > ty ` . See also Note [ Type - checking overloaded labels ] in TcExpr . unwrapIP :: Type -> CoercionR unwrapIP ty = case unwrapNewTyCon_maybe tc of Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys [] Nothing -> pprPanic "unwrapIP" $ text "The dictionary for" <+> quotes (ppr tc) <+> text "is not a newtype!" where (tc, tys) = splitTyConApp ty wrapIP :: Type -> CoercionR wrapIP ty = mkSymCo (unwrapIP ty)
5d5892e179ecf280f170d4085f232cf6e7b3cf58a2144f20d7d4075b009d4e55
rubenbarroso/EOPL
5-4-2.scm
This is 5-4-2.scm : flat fields (let ((time-stamp "Time-stamp: <2000-12-13 16:22:39 wand>")) (eopl:printf "5-4-2.scm - flat fields ~a~%" (substring time-stamp 13 29))) ;;;;;;;;;;;;;;;; classes ;;;;;;;;;;;;;;;; ;;; classes are represented by their class-decls. (define class? class-decl?) ; not used ;;;;;;;;;;;;;;;; objects ;;;;;;;;;;;;;;;; ;; an object is now just a single part, with a vector representing the ;; managed storage for the all the fields. (define-datatype object object? (an-object (class-name symbol?) (fields vector?))) (define new-object (lambda (class-name) (an-object class-name (make-vector (roll-up-field-length class-name))))) (define roll-up-field-length (lambda (class-name) (if (eqv? class-name 'object) 0 (+ (roll-up-field-length (class-name->super-name class-name)) (length (class-name->field-ids class-name)))))) ;;;;;;;;;;;;;;;; methods ;;;;;;;;;;;;;;;; (define find-method-and-apply (lambda (m-name host-name self args) (if (eqv? host-name 'object) (eopl:error 'find-method-and-apply "No method for name ~s" m-name) (let ((m-decl (lookup-method-decl m-name (class-name->method-decls host-name)))) (if (method-decl? m-decl) (apply-method m-decl host-name self args) (find-method-and-apply m-name (class-name->super-name host-name) self args)))))) ^ 5 - 4 - 2 (define apply-method (lambda (m-decl host-name self args) (let ((ids (method-decl->ids m-decl)) (body (method-decl->body m-decl)) (super-name (class-name->super-name host-name)) (field-ids (roll-up-field-ids host-name)) ;\new2 (fields (object->fields self))) (eval-expression body (extend-env (cons '%super (cons 'self ids)) (cons super-name (cons self args)) \new1 ^ 5 - 4 - 2 (define roll-up-field-ids (lambda (class-name) (if (eqv? class-name 'object) '() (append (roll-up-field-ids (class-name->super-name class-name)) (class-name->field-ids class-name))))) ^ 5 - 4 - 2 (define rib-find-position (lambda (name symbols) (list-find-last-position name symbols))) ;^;;;;;;;;;;;;;;; method environments ;;;;;;;;;;;;;;;; (define lookup-method-decl (lambda (m-name m-decls) (cond ((null? m-decls) #f) ((eqv? m-name (method-decl->method-name (car m-decls))) (car m-decls)) (else (lookup-method-decl m-name (cdr m-decls)))))) ;^;;;;;;;;;;;;;;; class environments ;;;;;;;;;;;;;;;; ;^;; we'll just use the list of class-decls. (define the-class-env '()) (define elaborate-class-decls! (lambda (c-decls) (set! the-class-env c-decls))) (define lookup-class (lambda (name) (let loop ((env the-class-env)) (cond ((null? env) (eopl:error 'lookup-class "Unknown class ~s" name)) ((eqv? (class-decl->class-name (car env)) name) (car env)) (else (loop (cdr env))))))) ;^;;;;;;;;;;;;;;; selectors ;;;;;;;;;;;;;;;; (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->fields (lambda (obj) (cases object obj (an-object (class-decl fields) fields)))) (define object->class-decl (lambda (obj) (lookup-class (object->class-name obj)))) (define object->field-ids (lambda (object) (class-decl->field-ids (object->class-decl object)))) (define class-name->super-name (lambda (class-name) (class-decl->super-name (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (class-decl->field-ids (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (class-decl->field-ids (lookup-class class-name)))) (define class-name->method-decls (lambda (class-name) (class-decl->method-decls (lookup-class class-name))))
null
https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/interps/5-4-2.scm
scheme
classes ;;;;;;;;;;;;;;;; classes are represented by their class-decls. not used objects ;;;;;;;;;;;;;;;; an object is now just a single part, with a vector representing the managed storage for the all the fields. methods ;;;;;;;;;;;;;;;; \new2 ^;;;;;;;;;;;;;;; method environments ;;;;;;;;;;;;;;;; ^;;;;;;;;;;;;;;; class environments ;;;;;;;;;;;;;;;; ^;; we'll just use the list of class-decls. ^;;;;;;;;;;;;;;; selectors ;;;;;;;;;;;;;;;;
This is 5-4-2.scm : flat fields (let ((time-stamp "Time-stamp: <2000-12-13 16:22:39 wand>")) (eopl:printf "5-4-2.scm - flat fields ~a~%" (substring time-stamp 13 29))) (define-datatype object object? (an-object (class-name symbol?) (fields vector?))) (define new-object (lambda (class-name) (an-object class-name (make-vector (roll-up-field-length class-name))))) (define roll-up-field-length (lambda (class-name) (if (eqv? class-name 'object) 0 (+ (roll-up-field-length (class-name->super-name class-name)) (length (class-name->field-ids class-name)))))) (define find-method-and-apply (lambda (m-name host-name self args) (if (eqv? host-name 'object) (eopl:error 'find-method-and-apply "No method for name ~s" m-name) (let ((m-decl (lookup-method-decl m-name (class-name->method-decls host-name)))) (if (method-decl? m-decl) (apply-method m-decl host-name self args) (find-method-and-apply m-name (class-name->super-name host-name) self args)))))) ^ 5 - 4 - 2 (define apply-method (lambda (m-decl host-name self args) (let ((ids (method-decl->ids m-decl)) (body (method-decl->body m-decl)) (super-name (class-name->super-name host-name)) (fields (object->fields self))) (eval-expression body (extend-env (cons '%super (cons 'self ids)) (cons super-name (cons self args)) \new1 ^ 5 - 4 - 2 (define roll-up-field-ids (lambda (class-name) (if (eqv? class-name 'object) '() (append (roll-up-field-ids (class-name->super-name class-name)) (class-name->field-ids class-name))))) ^ 5 - 4 - 2 (define rib-find-position (lambda (name symbols) (list-find-last-position name symbols))) (define lookup-method-decl (lambda (m-name m-decls) (cond ((null? m-decls) #f) ((eqv? m-name (method-decl->method-name (car m-decls))) (car m-decls)) (else (lookup-method-decl m-name (cdr m-decls)))))) (define the-class-env '()) (define elaborate-class-decls! (lambda (c-decls) (set! the-class-env c-decls))) (define lookup-class (lambda (name) (let loop ((env the-class-env)) (cond ((null? env) (eopl:error 'lookup-class "Unknown class ~s" name)) ((eqv? (class-decl->class-name (car env)) name) (car env)) (else (loop (cdr env))))))) (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->fields (lambda (obj) (cases object obj (an-object (class-decl fields) fields)))) (define object->class-decl (lambda (obj) (lookup-class (object->class-name obj)))) (define object->field-ids (lambda (object) (class-decl->field-ids (object->class-decl object)))) (define class-name->super-name (lambda (class-name) (class-decl->super-name (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (class-decl->field-ids (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (class-decl->field-ids (lookup-class class-name)))) (define class-name->method-decls (lambda (class-name) (class-decl->method-decls (lookup-class class-name))))
8e7c9ccf37207169db32713cd56f22aaa5fc8d211d19833ba338b0927528f0d9
rescript-lang/rescript-compiler
lam_compat.mli
Copyright ( C ) 2018 - Hongbo Zhang , Authors of ReScript * * 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 . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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. *) type boxed_integer = Lambda.boxed_integer = Pnativeint | Pint32 | Pint64 type comparison = Lambda.comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge type compile_time_constant = | Big_endian | Ostype_unix | Ostype_win32 | Ostype | Backend_type type let_kind = Lambda.let_kind = Strict | Alias | StrictOpt | Variable type field_dbg_info = Lambda.field_dbg_info = | Fld_record of { name : string; mutable_flag : Asttypes.mutable_flag } | Fld_module of { name : string } | Fld_record_inline of { name : string } | Fld_record_extension of { name : string } | Fld_tuple | Fld_poly_var_tag | Fld_poly_var_content | Fld_extension | Fld_variant | Fld_cons | Fld_array val str_of_field_info : field_dbg_info -> string option type set_field_dbg_info = Lambda.set_field_dbg_info = | Fld_record_set of string | Fld_record_inline_set of string | Fld_record_extension_set of string val cmp_int32 : comparison -> int32 -> int32 -> bool val cmp_int64 : comparison -> int64 -> int64 -> bool val cmp_nativeint : comparison -> nativeint -> nativeint -> bool val cmp_float : comparison -> float -> float -> bool val cmp_int : comparison -> int -> int -> bool val eq_comparison : comparison -> comparison -> bool val eq_boxed_integer : boxed_integer -> boxed_integer -> bool val eq_compile_time_constant : compile_time_constant -> compile_time_constant -> bool
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/e60482c6f6a69994907b9bd56e58ce87052e3659/jscomp/core/lam_compat.mli
ocaml
Copyright ( C ) 2018 - Hongbo Zhang , Authors of ReScript * * 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 . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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. *) type boxed_integer = Lambda.boxed_integer = Pnativeint | Pint32 | Pint64 type comparison = Lambda.comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge type compile_time_constant = | Big_endian | Ostype_unix | Ostype_win32 | Ostype | Backend_type type let_kind = Lambda.let_kind = Strict | Alias | StrictOpt | Variable type field_dbg_info = Lambda.field_dbg_info = | Fld_record of { name : string; mutable_flag : Asttypes.mutable_flag } | Fld_module of { name : string } | Fld_record_inline of { name : string } | Fld_record_extension of { name : string } | Fld_tuple | Fld_poly_var_tag | Fld_poly_var_content | Fld_extension | Fld_variant | Fld_cons | Fld_array val str_of_field_info : field_dbg_info -> string option type set_field_dbg_info = Lambda.set_field_dbg_info = | Fld_record_set of string | Fld_record_inline_set of string | Fld_record_extension_set of string val cmp_int32 : comparison -> int32 -> int32 -> bool val cmp_int64 : comparison -> int64 -> int64 -> bool val cmp_nativeint : comparison -> nativeint -> nativeint -> bool val cmp_float : comparison -> float -> float -> bool val cmp_int : comparison -> int -> int -> bool val eq_comparison : comparison -> comparison -> bool val eq_boxed_integer : boxed_integer -> boxed_integer -> bool val eq_compile_time_constant : compile_time_constant -> compile_time_constant -> bool
31901c7f44bbc809af52541193e18ba5410c6caf23150f104b006aa45df361f6
gregcman/sucle
sucle.lisp
(in-package :sucle) ;;;;************************************************************************;;;; ;;;;<BOXES?> (defun create-aabb (&optional (maxx 1.0) (maxy maxx) (maxz maxx) (minx (- maxx)) (miny (- maxy)) (minz (- maxz))) (floatf maxx maxy maxz minx miny minz) (aabbcc:make-aabb :minx minx :maxx maxx :miny miny :maxy maxy :minz minz :maxz maxz)) (defparameter *block-aabb* 1x1x1 cube (create-aabb 1.0 1.0 1.0 0.0 0.0 0.0)) [ FIXME]The point of this is to reduce the amount of bits to store the hitbox . ;;;;Why? because when there is an inexact number, like 0.3, there are bits at the end which ;;;;get chopped off or something, thus leading to strange clipping. ;;;;This effectively reduces the precision, giving leeway for math operations. ;;;;My prediction could be wrong though. (defun round-to-nearest (x &optional (n (load-time-value (/ 1.0 128.0)))) (* n (round (/ x n)))) (defparameter *player-aabb* (apply #'create-aabb (mapcar 'round-to-nearest '(0.3 0.12 0.3 -0.3 -1.5 -0.3)))) ;;;a very small cubic fist (defparameter *fist-aabb* (create-aabb 0.00005)) (defparameter *chunk-aabb* (apply 'create-aabb (mapcar 'floatify (list vocs:+size+ vocs:+size+ vocs:+size+ 0.0 0.0 0.0)))) (defparameter *start-menu* `(;;keys bound to functions (((:key :pressed #\f) . ,(lambda () (print "Paying Respects"))) ((:key :pressed #\q) . ,(lambda () (app:quit))) ((:key :pressed #\Escape) . ,(lambda () (app:quit))) ((:key :pressed #\p) . ,(lambda () (app:pop-mode))) ((:key :pressed #\o) . ,(lambda () (app:push-mode 'menu:tick))) ((:key :pressed #\s) . ,(lambda () (app:push-mode 'sucle-per-frame))) ((:key :pressed #\c) . ,(lambda () (print "Clearing...") (let ((clear (assoc :clear menu:*data*))) (setf (second clear) (with-output-to-string (str) (let ((clearstr (make-string menu:*w* :initial-element #\space))) (dotimes (y menu:*h*) (terpri str) (write-string clearstr str)))))))) ((:key :released #\c) . ,(lambda () (print "Clearing Done!") (let ((clear (assoc :clear menu:*data*))) (setf (second clear) ""))))) ;;data to render ((:hello " Press s to start the game Press c to clear Press h for help Press F to pay respects [not really] Press q/escape to quit " 4 4 :bold t) (: hello " world " 8 16 : fg " green " : bg " red " : reverse t : bold t ) (:clear "" 0 0 :bold t)) ())) ;;;;</BOXES?> (defparameter *some-saves* nil) (defparameter *world-directory* nil) (defun world-path (&optional (world ;;"first/" # + nil ;;"test/" "other/" ;;"third/" ;;"terrarium2/" ;;"ridikulisp/" ) (working-dir (sucle-temp:path "save/") #+nil (cdr (assoc (machine-instance) '(("gm3-iMac" . #P"/media/imac/share/space/lispysaves/saves/sandbox-saves/") ("nootboke" . #P"/home/terminal256/Documents/saves/")) :test 'equal)))) (utility:rebase-path world working-dir)) (defun start () (app:enter 'sucle-app)) (defun sucle-app () #+nil (setf (entity-fly? *ent*) nil (entity-gravity? *ent*) t) ;;(our-load) (window:set-vsync t) (fps:set-fps 60) (ncurses-clone-for-lem:init) (app:push-mode 'menu:tick) (menu:use *start-menu*) (crud:use-crud-from-path ;;(sucle-temp:path "data.db") ;;(world-path) (sucle-temp:path "new.db") ) (sucle-mp:with-initialize-multiprocessing (unwind-protect (app:default-loop) (when vocs::*persist* (vocs::save-all))))) ;;;; #+nil (defun start () (application:main (lambda () (call-with-world-meshing-lparallel (lambda () (loop (application:poll-app) (per-frame))))) :width 720 :height 480 :title "conceptually simple block game")) ;;;;************************************************************************;;;; ;;;;This code basically has not changed in forever. (defparameter *raw-mouse-x* 0.0d0) (defparameter *raw-mouse-y* 0.0d0) (defun cursor-motion-difference (&optional (x window:*mouse-x*) (y window:*mouse-y*)) ;;Return the difference in position of the last time the ;;cursor was observed. ;;*raw-mouse-x* and *raw-mouse-y* hold the last value ;;of the cursor. (multiple-value-prog1 (values (- x *raw-mouse-x*) (- y *raw-mouse-y*)) (setf *raw-mouse-x* x *raw-mouse-y* y))) (defparameter *mouse-x* 0.0d0) (defparameter *mouse-y* 0.0d0) (defparameter *lerp-mouse-x* 0.0d0) (defparameter *lerp-mouse-y* 0.0d0) (defun update-moused (clamp &optional (smoothing-factor 1.0)) (multiple-value-bind (dx dy) (cursor-motion-difference) (let ((x (+ *mouse-x* dx)) (y (+ *mouse-y* dy))) ;;So looking straight up stops. (when (> y clamp) (setf y clamp)) ;;So looking straight down stops (let ((negative (- clamp))) (when (< y negative) (setf y negative))) (setf *mouse-x* x) (setf *mouse-y* y))) * * and * * are used ;;for camera smoothing with the framerate. (setf *lerp-mouse-x* (alexandria:lerp smoothing-factor *lerp-mouse-x* *mouse-x*)) (setf *lerp-mouse-y* (alexandria:lerp smoothing-factor *lerp-mouse-y* *mouse-y*))) (defparameter *mouse-multiplier* 0.002617) (defparameter *mouse-multiplier-aux* (/ (* 0.5 pi 0.9999) *mouse-multiplier*)) (defun neck-values () (values (floatify (* *lerp-mouse-x* *mouse-multiplier*)) (floatify (* *lerp-mouse-y* *mouse-multiplier*)))) (defun unit-pitch-yaw (pitch yaw &optional (result (sb-cga:vec 0.0 0.0 0.0))) (setf yaw (- yaw)) (let ((cos-pitch (cos pitch))) (with-vec (x y z) (result symbol-macrolet) (setf x (* cos-pitch (sin yaw)) y (- (sin pitch)) z (* cos-pitch (cos yaw))))) result) ;;;;************************************************************************;;;; ;;emacs-like modes (defparameter *active-modes* ()) (defun reset-all-modes () (setf *active-modes* nil)) (defun enable-mode (mode) (pushnew mode *active-modes* :test 'equal)) (defun disable-mode (mode) (setf *active-modes* (delete mode *active-modes*))) (defun mode-enabled-p (mode) (member mode *active-modes* :test 'equal)) (defun set-mode-if (mode p) (if p (enable-mode mode) (disable-mode mode))) ;;;;************************************************************************;;;; (defparameter *session* nil) (defparameter *ticks* 0) (defparameter *game-ticks-per-iteration* 0) (defparameter *fraction-for-fps* 0.0) (defparameter *fist* nil) (defparameter *entities* nil) (defparameter *ent* nil) (defparameter *reach* 50.0) (defparameter *fov* (floatify (* pi (/ 85 180)))) (defparameter *camera* (camera-matrix:make-camera :frustum-far (* 256.0) :frustum-near (/ 1.0 8.0))) (defparameter *fog-ratio* 0.75) (defparameter *time-of-day* 1.0) (defparameter *sky-color* (mapcar 'utility:byte/255 ;;'(0 0 0) '(173 204 255))) (defun atmosphere () (let ((sky (mapcar (lambda (x) (alexandria:clamp (* x *time-of-day*) 0.0 1.0)) *sky-color*)) (fog *fog-ratio*)) (values (mapcar (lambda (a b) (alexandria:lerp *fade* a b)) *fade-color* sky) (alexandria:lerp *fade* 1.0 *fog-ratio*)))) (defparameter *fade-color* '(0.0 0.0 0.0)) (defparameter *fade* 1.0) (defun update-world-vao2 () (update-world-vao (lambda (key) (world:unsquared-chunk-distance key (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*))))) ;;*frame-time* is for graphical frames, as in framerate. (defparameter *frame-time* 0) (defun sucle-per-frame () (incf *frame-time*) [ FIXME]where is the best place to flush the job - tasks ? (sucle-mp:flush-job-tasks) ;;set the chunk center aroun the player (livesupport:update-repl-link) (application:on-session-change *session* (voxel-chunks:clearworld) (setf *entities* (loop :repeat 10 :collect (create-entity))) (setf *ent* (elt *entities* 0)) (sync_entity->chunk-array *ent* *chunk-cursor-center*) (load-world *chunk-cursor-center*;; t ) ;;Controller? (reset-all-modes) (enable-mode :normal-mode) (enable-mode :god-mode) ;;Model ;;FIXME::this depends on the position of entity. ;;Rendering/view? (reset-chunk-display-list) ( update-world-vao2)) (sync_entity->chunk-array *ent* *chunk-cursor-center*) ;;load or unload chunks around the player who may have moved (load-world *chunk-cursor-center*) ;;Polling ;;Physics ;;Rendering Chunks ;;Rendering Other stuff ;;Meshing Waiting on vsync ;;Back to polling ;;Physics and Polling should be close together to prevent lag ;;physics Calculate what bocks are selected etc .. # + nil (setf *fist* (mvc 'standard-fist (spread (entity-position *ent*)) (spread (sb-cga:vec* (camera-matrix:camera-vec-forward *camera*) *reach*)))) (when (mode-enabled-p :fist-mode) (run-buttons *fist-keys*)) (when (mode-enabled-p :god-mode) (run-buttons *god-keys*)) (when (mode-enabled-p :movement-mode) ;;Set the sneaking state (setf (entity-sneak? *ent*) (cond ((window:button :key :down :left-shift) 0) ((window:button :key :down :left-control) 1))) ;;Jump if space pressed (setf (entity-jump? *ent*) (window:button :key :down #\Space)) (when (window:button :key :pressed #\Space) (set-doublejump *ent*)) Set the direction with WASD (setf (entity-hips *ent*) (let ((x 0) (y 0)) (when (window:button :key :down #\w) (incf x)) (when (window:button :key :down #\s) (decf x)) (when (window:button :key :down #\a) (decf y)) (when (window:button :key :down #\d) (incf y)) ;;[FIXME] ;;This used to be cached and had its own function in ;;the control.asd (if (and (zerop x) (zerop y)) nil (floatify (atan y x))))) ;;update the internal mouse state ;;taking into consideration fractions (update-moused *mouse-multiplier-aux* 1.0)) (when (mode-enabled-p :normal-mode) ;;[FIXME] because this runs after update-moused, the camera swivels ;;unecessarily. (run-buttons *normal-keys*)) (let ((number-key (control:num-key-jp :pressed))) (when number-key (setf *ent* (elt *entities* number-key)))) ;;Set the pitch and yaw of the player based on the ;;mouse position (mvc 'set-neck-values (entity-neck *ent*) (neck-values)) ;;Run the game ticks ;;FIXME:: run fps:tick if resuming from being paused. (setf (values *fraction-for-fps* *game-ticks-per-iteration*) (fps:tick (incf *ticks*) (setf *time-of-day* 1.0) ;;run the physics (run-physics-for-entity *ent*))) ;;render chunks and such ;;handle chunk meshing (sync_entity->camera *ent* *camera*) (draw-to-default-area) ;;this also clears the depth and color buffer. (multiple-value-bind (color fog) (atmosphere) (apply #'render-sky color) (use-chunk-shader :camera *camera* :sky-color color :time-of-day (* *fade* *time-of-day*) :fog-ratio fog :chunk-radius (vocs::cursor-radius *chunk-cursor-center*))) #+nil (map nil (lambda (ent) (unless (eq ent *ent*) (render-entity ent))) *entities*) (get-chunks-to-draw (let ((ent (elt *entities* 0)) (camera (camera-matrix:make-camera))) (sync_entity->camera ent camera) camera) (vocs::cursor-radius *chunk-cursor-center*) (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*)) (render-chunks) (use-occlusion-shader *camera*) (render-chunk-occlusion-queries) ;;selected block and crosshairs (use-solidshader *camera*) (render-fist *fist*) #+nil (progn (gl:line-width 10.0) (map nil (lambda (ent) (when (eq ent (elt *entities* 0)) (let ((*camera* (camera-matrix:make-camera))) (sync_entity->camera ent *camera*) (render-camera *camera*)))) *entities*)) #+nil (progn (gl:line-width 10.0) (render-chunk-outlines)) #+nil (progn (gl:line-width 10.0) (render-units)) ( mvc ' render - line 0 0 0 ( spread ' ( 200 200 200 ) ) ) (render-crosshairs) (complete-render-tasks) (dispatch-mesher-to-dirty-chunks (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*))) [ FIXME]architecture : one center , the player , and the chunk array centers around it (defparameter *chunk-cursor-center* (vocs::make-cursor)) (defun sync_entity->chunk-array (ent cursor) (mvc 'vocs::set-cursor-position (spread (entity-position ent)) cursor)) (defun load-world (chunk-cursor-center) (let ((maybe-moved (vocs::cursor-dirty chunk-cursor-center))) (when maybe-moved (mapc 'world::dirty-push-around (vocs::load-chunks-around *chunk-cursor-center*))) (vocs::call-fresh-chunks-and-end (lambda (chunk) FIXME : this does not load the nearest chunks to render first ? ;;fresh-chunks are not necessarily fresh. reposition-chunk array gets rid of ;;everything when moving, how to only update those that exist? (world::dirty-push (vocs::chunk-key chunk)))) (when maybe-moved (setf (vocs::cursor-dirty chunk-cursor-center) nil)))) (defun render-chunk-outlines () (dohash (k chunk) *g/chunk-call-list* (declare (ignorable v)) (render-aabb-at (chunk-gl-representation-aabb chunk) 0.0 0.0 0.0))) (defun render-camera (camera) (mapc (lambda (arg) (mvc 'render-line-dx (spread (camera-matrix:camera-vec-position camera)) (spread (map 'list (lambda (x) (* x 100)) arg)))) (camera-matrix::camera-edges camera)) (mapc (lambda (arg) (mvc 'render-line-dx (spread (camera-matrix:camera-vec-position camera)) (spread (map 'list (lambda (x) (* x 100)) arg)) 0.99 0.8 0.0)) (camera-matrix::camera-planes camera))) (defun render-units (&optional (foo 100)) ;;X is red (mvc 'render-line 0 0 0 foo 0 0 (spread #(1.0 0.0 0.0))) ;;Y is green (mvc 'render-line 0 0 0 0 foo 0 (spread #(0.0 1.0 0.0))) ;;Z is blue (mvc 'render-line 0 0 0 0 0 foo (spread #(0.0 0.0 1.0)))) (defun sync_entity->camera (entity camera) ;;FIXME:this lumps in generating the other cached camera values, ;;and the generic used configuration, such as aspect ratio and fov. ;;Set the direction of the camera based on the ;;pitch and yaw of the player (sync_neck->camera (entity-neck entity) camera) ;;Calculate the camera position from ;;the past, current position of the player and the frame fraction (sync_particle->camera ;;modify the camera for sneaking (let ((particle (entity-particle entity))) (if (and (not (entity-fly? entity)) (eql 0 (entity-sneak? entity))) (translate-pointmass particle 0.0 -0.125 0.0) particle)) camera *fraction-for-fps*) ;;update the camera ;;FIXME::these values are (set-camera-values camera (/ (floatify window:*height*) (floatify window:*width*) ) *fov* (* 1024.0 256.0) ) (camera-matrix:update-matrices camera) ;;return the camera, in case it was created. (values camera)) (defun set-camera-values (camera aspect-ratio fov frustum-far) (setf (camera-matrix:camera-aspect-ratio camera) aspect-ratio) (setf (camera-matrix:camera-fov camera) fov) (setf (camera-matrix:camera-frustum-far camera) frustum-far)) (defun sync_particle->camera (particle camera fraction) (let* ((prev (pointmass-position-old particle)) (curr (pointmass-position particle))) (let ((vec (camera-matrix:camera-vec-position camera))) (nsb-cga:%vec-lerp vec prev curr fraction)))) (defun sync_neck->camera (neck camera) #+nil (print (list (necking-pitch neck) (necking-yaw neck))) ;;(print) (unit-pitch-yaw (necking-pitch neck) (necking-yaw neck) (camera-matrix:camera-vec-forward camera))) ;;;;************************************************************************;;;; (defparameter *blockid* (block-data:lookup :planks)) (defparameter *x* 0) (defparameter *y* 0) (defparameter *z* 0) ;;;detect more entities ;;;detect block types ;;;;Default punching and placing blocks (defparameter *left-fist* 'destroy-block-at) (defun destroy-block-at (&optional (x *x*) (y *y*) (z *z*)) ( blocksound x y z ) (world:plain-setblock x y z (block-data:lookup :air) 15)) (defparameter *right-fist* 'place-block-at) (defun place-block-at (&optional (x *x*) (y *y*) (z *z*) (blockval *blockid*)) (when (not-occupied x y z) ( blocksound x y z ) (world:plain-setblock x y z blockval (block-data:data blockval :light)))) (defparameter *5-fist* (constantly nil)) (defparameter *4-fist* (constantly nil)) (defparameter *middle-fist* (constantly nil)) (defparameter *fist-keys* `(((:mouse :pressed :left) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *left-fist*))))) ((:mouse :pressed :right) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-normal-block *fist*)) (funcall *right-fist*))))) ((:mouse :pressed :5) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *5-fist*))))) ((:mouse :pressed :4) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *4-fist*))))) ((:mouse :pressed :middle) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *middle-fist*))))))) (defparameter *normal-keys* `(((:key :pressed #\p) . ,(lambda () (update-world-vao2))) ((:key :pressed :escape) . ,(lambda () (window:get-mouse-out) (app:pop-mode))) ((:key :pressed #\e) . ,(lambda () (window:toggle-mouse-capture) (set-mode-if :movement-mode (not (window:mouse-free?))) (set-mode-if :fist-mode (not (window:mouse-free?))) ;;Flush changes to the mouse so ;;moving the mouse while not captured does not ;;affect the camera ;;FIXME::not implemented. ;;(moused) )))) (defparameter *god-keys* `(;;Toggle noclip with 'v' ((:key :pressed #\v) . ,(lambda () (toggle (entity-clip? *ent*)))) ;;Toggle flying with 'f' ((:key :pressed #\f) . ,(lambda () (toggle (entity-fly? *ent*)) (toggle (entity-gravity? *ent*))))))
null
https://raw.githubusercontent.com/gregcman/sucle/258be4ac4daaceea06a55f893227584d3772bb47/src/sucle/sucle.lisp
lisp
************************************************************************;;;; <BOXES?> Why? because when there is an inexact number, like 0.3, there are bits at the end which get chopped off or something, thus leading to strange clipping. This effectively reduces the precision, giving leeway for math operations. My prediction could be wrong though. a very small cubic fist keys bound to functions data to render </BOXES?> "first/" "test/" "third/" "terrarium2/" "ridikulisp/" (our-load) (sucle-temp:path "data.db") (world-path) ************************************************************************;;;; This code basically has not changed in forever. Return the difference in position of the last time the cursor was observed. *raw-mouse-x* and *raw-mouse-y* hold the last value of the cursor. So looking straight up stops. So looking straight down stops for camera smoothing with the framerate. ************************************************************************;;;; emacs-like modes ************************************************************************;;;; '(0 0 0) *frame-time* is for graphical frames, as in framerate. set the chunk center aroun the player t Controller? Model FIXME::this depends on the position of entity. Rendering/view? load or unload chunks around the player who may have moved Polling Physics Rendering Chunks Rendering Other stuff Meshing Back to polling Physics and Polling should be close together to prevent lag physics Set the sneaking state Jump if space pressed [FIXME] This used to be cached and had its own function in the control.asd update the internal mouse state taking into consideration fractions [FIXME] because this runs after update-moused, the camera swivels unecessarily. Set the pitch and yaw of the player based on the mouse position Run the game ticks FIXME:: run fps:tick if resuming from being paused. run the physics render chunks and such handle chunk meshing this also clears the depth and color buffer. selected block and crosshairs fresh-chunks are not necessarily fresh. reposition-chunk array gets rid of everything when moving, how to only update those that exist? X is red Y is green Z is blue FIXME:this lumps in generating the other cached camera values, and the generic used configuration, such as aspect ratio and fov. Set the direction of the camera based on the pitch and yaw of the player Calculate the camera position from the past, current position of the player and the frame fraction modify the camera for sneaking update the camera FIXME::these values are return the camera, in case it was created. (print) ************************************************************************;;;; detect more entities detect block types Default punching and placing blocks Flush changes to the mouse so moving the mouse while not captured does not affect the camera FIXME::not implemented. (moused) Toggle noclip with 'v' Toggle flying with 'f'
(in-package :sucle) (defun create-aabb (&optional (maxx 1.0) (maxy maxx) (maxz maxx) (minx (- maxx)) (miny (- maxy)) (minz (- maxz))) (floatf maxx maxy maxz minx miny minz) (aabbcc:make-aabb :minx minx :maxx maxx :miny miny :maxy maxy :minz minz :maxz maxz)) (defparameter *block-aabb* 1x1x1 cube (create-aabb 1.0 1.0 1.0 0.0 0.0 0.0)) [ FIXME]The point of this is to reduce the amount of bits to store the hitbox . (defun round-to-nearest (x &optional (n (load-time-value (/ 1.0 128.0)))) (* n (round (/ x n)))) (defparameter *player-aabb* (apply #'create-aabb (mapcar 'round-to-nearest '(0.3 0.12 0.3 -0.3 -1.5 -0.3)))) (defparameter *fist-aabb* (create-aabb 0.00005)) (defparameter *chunk-aabb* (apply 'create-aabb (mapcar 'floatify (list vocs:+size+ vocs:+size+ vocs:+size+ 0.0 0.0 0.0)))) (defparameter *start-menu* (((:key :pressed #\f) . ,(lambda () (print "Paying Respects"))) ((:key :pressed #\q) . ,(lambda () (app:quit))) ((:key :pressed #\Escape) . ,(lambda () (app:quit))) ((:key :pressed #\p) . ,(lambda () (app:pop-mode))) ((:key :pressed #\o) . ,(lambda () (app:push-mode 'menu:tick))) ((:key :pressed #\s) . ,(lambda () (app:push-mode 'sucle-per-frame))) ((:key :pressed #\c) . ,(lambda () (print "Clearing...") (let ((clear (assoc :clear menu:*data*))) (setf (second clear) (with-output-to-string (str) (let ((clearstr (make-string menu:*w* :initial-element #\space))) (dotimes (y menu:*h*) (terpri str) (write-string clearstr str)))))))) ((:key :released #\c) . ,(lambda () (print "Clearing Done!") (let ((clear (assoc :clear menu:*data*))) (setf (second clear) ""))))) ((:hello " Press s to start the game Press c to clear Press h for help Press F to pay respects [not really] Press q/escape to quit " 4 4 :bold t) (: hello " world " 8 16 : fg " green " : bg " red " : reverse t : bold t ) (:clear "" 0 0 :bold t)) ())) (defparameter *some-saves* nil) (defparameter *world-directory* nil) (defun world-path (&optional (world # + nil "other/" ) (working-dir (sucle-temp:path "save/") #+nil (cdr (assoc (machine-instance) '(("gm3-iMac" . #P"/media/imac/share/space/lispysaves/saves/sandbox-saves/") ("nootboke" . #P"/home/terminal256/Documents/saves/")) :test 'equal)))) (utility:rebase-path world working-dir)) (defun start () (app:enter 'sucle-app)) (defun sucle-app () #+nil (setf (entity-fly? *ent*) nil (entity-gravity? *ent*) t) (window:set-vsync t) (fps:set-fps 60) (ncurses-clone-for-lem:init) (app:push-mode 'menu:tick) (menu:use *start-menu*) (crud:use-crud-from-path (sucle-temp:path "new.db") ) (sucle-mp:with-initialize-multiprocessing (unwind-protect (app:default-loop) (when vocs::*persist* (vocs::save-all))))) #+nil (defun start () (application:main (lambda () (call-with-world-meshing-lparallel (lambda () (loop (application:poll-app) (per-frame))))) :width 720 :height 480 :title "conceptually simple block game")) (defparameter *raw-mouse-x* 0.0d0) (defparameter *raw-mouse-y* 0.0d0) (defun cursor-motion-difference (&optional (x window:*mouse-x*) (y window:*mouse-y*)) (multiple-value-prog1 (values (- x *raw-mouse-x*) (- y *raw-mouse-y*)) (setf *raw-mouse-x* x *raw-mouse-y* y))) (defparameter *mouse-x* 0.0d0) (defparameter *mouse-y* 0.0d0) (defparameter *lerp-mouse-x* 0.0d0) (defparameter *lerp-mouse-y* 0.0d0) (defun update-moused (clamp &optional (smoothing-factor 1.0)) (multiple-value-bind (dx dy) (cursor-motion-difference) (let ((x (+ *mouse-x* dx)) (y (+ *mouse-y* dy))) (when (> y clamp) (setf y clamp)) (let ((negative (- clamp))) (when (< y negative) (setf y negative))) (setf *mouse-x* x) (setf *mouse-y* y))) * * and * * are used (setf *lerp-mouse-x* (alexandria:lerp smoothing-factor *lerp-mouse-x* *mouse-x*)) (setf *lerp-mouse-y* (alexandria:lerp smoothing-factor *lerp-mouse-y* *mouse-y*))) (defparameter *mouse-multiplier* 0.002617) (defparameter *mouse-multiplier-aux* (/ (* 0.5 pi 0.9999) *mouse-multiplier*)) (defun neck-values () (values (floatify (* *lerp-mouse-x* *mouse-multiplier*)) (floatify (* *lerp-mouse-y* *mouse-multiplier*)))) (defun unit-pitch-yaw (pitch yaw &optional (result (sb-cga:vec 0.0 0.0 0.0))) (setf yaw (- yaw)) (let ((cos-pitch (cos pitch))) (with-vec (x y z) (result symbol-macrolet) (setf x (* cos-pitch (sin yaw)) y (- (sin pitch)) z (* cos-pitch (cos yaw))))) result) (defparameter *active-modes* ()) (defun reset-all-modes () (setf *active-modes* nil)) (defun enable-mode (mode) (pushnew mode *active-modes* :test 'equal)) (defun disable-mode (mode) (setf *active-modes* (delete mode *active-modes*))) (defun mode-enabled-p (mode) (member mode *active-modes* :test 'equal)) (defun set-mode-if (mode p) (if p (enable-mode mode) (disable-mode mode))) (defparameter *session* nil) (defparameter *ticks* 0) (defparameter *game-ticks-per-iteration* 0) (defparameter *fraction-for-fps* 0.0) (defparameter *fist* nil) (defparameter *entities* nil) (defparameter *ent* nil) (defparameter *reach* 50.0) (defparameter *fov* (floatify (* pi (/ 85 180)))) (defparameter *camera* (camera-matrix:make-camera :frustum-far (* 256.0) :frustum-near (/ 1.0 8.0))) (defparameter *fog-ratio* 0.75) (defparameter *time-of-day* 1.0) (defparameter *sky-color* (mapcar 'utility:byte/255 '(173 204 255))) (defun atmosphere () (let ((sky (mapcar (lambda (x) (alexandria:clamp (* x *time-of-day*) 0.0 1.0)) *sky-color*)) (fog *fog-ratio*)) (values (mapcar (lambda (a b) (alexandria:lerp *fade* a b)) *fade-color* sky) (alexandria:lerp *fade* 1.0 *fog-ratio*)))) (defparameter *fade-color* '(0.0 0.0 0.0)) (defparameter *fade* 1.0) (defun update-world-vao2 () (update-world-vao (lambda (key) (world:unsquared-chunk-distance key (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*))))) (defparameter *frame-time* 0) (defun sucle-per-frame () (incf *frame-time*) [ FIXME]where is the best place to flush the job - tasks ? (sucle-mp:flush-job-tasks) (livesupport:update-repl-link) (application:on-session-change *session* (voxel-chunks:clearworld) (setf *entities* (loop :repeat 10 :collect (create-entity))) (setf *ent* (elt *entities* 0)) (sync_entity->chunk-array *ent* *chunk-cursor-center*) ) (reset-all-modes) (enable-mode :normal-mode) (enable-mode :god-mode) (reset-chunk-display-list) ( update-world-vao2)) (sync_entity->chunk-array *ent* *chunk-cursor-center*) (load-world *chunk-cursor-center*) Waiting on vsync Calculate what bocks are selected etc .. # + nil (setf *fist* (mvc 'standard-fist (spread (entity-position *ent*)) (spread (sb-cga:vec* (camera-matrix:camera-vec-forward *camera*) *reach*)))) (when (mode-enabled-p :fist-mode) (run-buttons *fist-keys*)) (when (mode-enabled-p :god-mode) (run-buttons *god-keys*)) (when (mode-enabled-p :movement-mode) (setf (entity-sneak? *ent*) (cond ((window:button :key :down :left-shift) 0) ((window:button :key :down :left-control) 1))) (setf (entity-jump? *ent*) (window:button :key :down #\Space)) (when (window:button :key :pressed #\Space) (set-doublejump *ent*)) Set the direction with WASD (setf (entity-hips *ent*) (let ((x 0) (y 0)) (when (window:button :key :down #\w) (incf x)) (when (window:button :key :down #\s) (decf x)) (when (window:button :key :down #\a) (decf y)) (when (window:button :key :down #\d) (incf y)) (if (and (zerop x) (zerop y)) nil (floatify (atan y x))))) (update-moused *mouse-multiplier-aux* 1.0)) (when (mode-enabled-p :normal-mode) (run-buttons *normal-keys*)) (let ((number-key (control:num-key-jp :pressed))) (when number-key (setf *ent* (elt *entities* number-key)))) (mvc 'set-neck-values (entity-neck *ent*) (neck-values)) (setf (values *fraction-for-fps* *game-ticks-per-iteration*) (fps:tick (incf *ticks*) (setf *time-of-day* 1.0) (run-physics-for-entity *ent*))) (sync_entity->camera *ent* *camera*) (draw-to-default-area) (multiple-value-bind (color fog) (atmosphere) (apply #'render-sky color) (use-chunk-shader :camera *camera* :sky-color color :time-of-day (* *fade* *time-of-day*) :fog-ratio fog :chunk-radius (vocs::cursor-radius *chunk-cursor-center*))) #+nil (map nil (lambda (ent) (unless (eq ent *ent*) (render-entity ent))) *entities*) (get-chunks-to-draw (let ((ent (elt *entities* 0)) (camera (camera-matrix:make-camera))) (sync_entity->camera ent camera) camera) (vocs::cursor-radius *chunk-cursor-center*) (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*)) (render-chunks) (use-occlusion-shader *camera*) (render-chunk-occlusion-queries) (use-solidshader *camera*) (render-fist *fist*) #+nil (progn (gl:line-width 10.0) (map nil (lambda (ent) (when (eq ent (elt *entities* 0)) (let ((*camera* (camera-matrix:make-camera))) (sync_entity->camera ent *camera*) (render-camera *camera*)))) *entities*)) #+nil (progn (gl:line-width 10.0) (render-chunk-outlines)) #+nil (progn (gl:line-width 10.0) (render-units)) ( mvc ' render - line 0 0 0 ( spread ' ( 200 200 200 ) ) ) (render-crosshairs) (complete-render-tasks) (dispatch-mesher-to-dirty-chunks (vocs::cursor-x *chunk-cursor-center*) (vocs::cursor-y *chunk-cursor-center*) (vocs::cursor-z *chunk-cursor-center*))) [ FIXME]architecture : one center , the player , and the chunk array centers around it (defparameter *chunk-cursor-center* (vocs::make-cursor)) (defun sync_entity->chunk-array (ent cursor) (mvc 'vocs::set-cursor-position (spread (entity-position ent)) cursor)) (defun load-world (chunk-cursor-center) (let ((maybe-moved (vocs::cursor-dirty chunk-cursor-center))) (when maybe-moved (mapc 'world::dirty-push-around (vocs::load-chunks-around *chunk-cursor-center*))) (vocs::call-fresh-chunks-and-end (lambda (chunk) FIXME : this does not load the nearest chunks to render first ? (world::dirty-push (vocs::chunk-key chunk)))) (when maybe-moved (setf (vocs::cursor-dirty chunk-cursor-center) nil)))) (defun render-chunk-outlines () (dohash (k chunk) *g/chunk-call-list* (declare (ignorable v)) (render-aabb-at (chunk-gl-representation-aabb chunk) 0.0 0.0 0.0))) (defun render-camera (camera) (mapc (lambda (arg) (mvc 'render-line-dx (spread (camera-matrix:camera-vec-position camera)) (spread (map 'list (lambda (x) (* x 100)) arg)))) (camera-matrix::camera-edges camera)) (mapc (lambda (arg) (mvc 'render-line-dx (spread (camera-matrix:camera-vec-position camera)) (spread (map 'list (lambda (x) (* x 100)) arg)) 0.99 0.8 0.0)) (camera-matrix::camera-planes camera))) (defun render-units (&optional (foo 100)) (mvc 'render-line 0 0 0 foo 0 0 (spread #(1.0 0.0 0.0))) (mvc 'render-line 0 0 0 0 foo 0 (spread #(0.0 1.0 0.0))) (mvc 'render-line 0 0 0 0 0 foo (spread #(0.0 0.0 1.0)))) (defun sync_entity->camera (entity camera) (sync_neck->camera (entity-neck entity) camera) (sync_particle->camera (let ((particle (entity-particle entity))) (if (and (not (entity-fly? entity)) (eql 0 (entity-sneak? entity))) (translate-pointmass particle 0.0 -0.125 0.0) particle)) camera *fraction-for-fps*) (set-camera-values camera (/ (floatify window:*height*) (floatify window:*width*) ) *fov* (* 1024.0 256.0) ) (camera-matrix:update-matrices camera) (values camera)) (defun set-camera-values (camera aspect-ratio fov frustum-far) (setf (camera-matrix:camera-aspect-ratio camera) aspect-ratio) (setf (camera-matrix:camera-fov camera) fov) (setf (camera-matrix:camera-frustum-far camera) frustum-far)) (defun sync_particle->camera (particle camera fraction) (let* ((prev (pointmass-position-old particle)) (curr (pointmass-position particle))) (let ((vec (camera-matrix:camera-vec-position camera))) (nsb-cga:%vec-lerp vec prev curr fraction)))) (defun sync_neck->camera (neck camera) #+nil (print (list (necking-pitch neck) (necking-yaw neck))) (unit-pitch-yaw (necking-pitch neck) (necking-yaw neck) (camera-matrix:camera-vec-forward camera))) (defparameter *blockid* (block-data:lookup :planks)) (defparameter *x* 0) (defparameter *y* 0) (defparameter *z* 0) (defparameter *left-fist* 'destroy-block-at) (defun destroy-block-at (&optional (x *x*) (y *y*) (z *z*)) ( blocksound x y z ) (world:plain-setblock x y z (block-data:lookup :air) 15)) (defparameter *right-fist* 'place-block-at) (defun place-block-at (&optional (x *x*) (y *y*) (z *z*) (blockval *blockid*)) (when (not-occupied x y z) ( blocksound x y z ) (world:plain-setblock x y z blockval (block-data:data blockval :light)))) (defparameter *5-fist* (constantly nil)) (defparameter *4-fist* (constantly nil)) (defparameter *middle-fist* (constantly nil)) (defparameter *fist-keys* `(((:mouse :pressed :left) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *left-fist*))))) ((:mouse :pressed :right) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-normal-block *fist*)) (funcall *right-fist*))))) ((:mouse :pressed :5) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *5-fist*))))) ((:mouse :pressed :4) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *4-fist*))))) ((:mouse :pressed :middle) . ,(lambda () (when (fist-exists *fist*) (multiple-value-bind (*x* *y* *z*) (spread (fist-selected-block *fist*)) (funcall *middle-fist*))))))) (defparameter *normal-keys* `(((:key :pressed #\p) . ,(lambda () (update-world-vao2))) ((:key :pressed :escape) . ,(lambda () (window:get-mouse-out) (app:pop-mode))) ((:key :pressed #\e) . ,(lambda () (window:toggle-mouse-capture) (set-mode-if :movement-mode (not (window:mouse-free?))) (set-mode-if :fist-mode (not (window:mouse-free?))) )))) (defparameter *god-keys* ((:key :pressed #\v) . ,(lambda () (toggle (entity-clip? *ent*)))) ((:key :pressed #\f) . ,(lambda () (toggle (entity-fly? *ent*)) (toggle (entity-gravity? *ent*))))))
07c9e86ce7d37bfead5c254899cec3b375ee5a7b6843413d299f4c9eb9951e8f
conscell/hugs-android
BSD.hs
module BSD # DEPRECATED " This module has moved to Network . BSD " # (module Network.BSD) where import Network.BSD
null
https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/oldlib/BSD.hs
haskell
module BSD # DEPRECATED " This module has moved to Network . BSD " # (module Network.BSD) where import Network.BSD
a13cbd246d1446f9dae3d4c0c84a15b28b3d48fc8516e9af4701e14fd3fd11c2
serperu/secer
etorrent_dht_net.erl
-module(etorrent_dht_net). -include("types.hrl"). -export([prova/1]). % -ifdef(TEST). % -include_lib("eqc/include/eqc.hrl"). -include_lib("eunit/include/eunit.hrl"). % -endif. -ifdef(EQC). -export([prop_query_inv/0, prop_inv_compact/0]). -endif. -behaviour(gen_server). -import(etorrent_bcoding, [get_value/2, get_value/3]). -import(etorrent_dht, [distance/2, closest_to/3]). % % Implementation notes % RPC calls to remote nodes in the DHT are exposed to % clients using the gen_server call mechanism. In order % to make this work the client reference passed to the % handle_call/3 callback is stored in the server state. % % When a response is received from the remote node, the % source IP and port combined with the message id is used % to map the response to the correct client reference. % % A timer is used to notify the server of requests that % time out, if a request times out {error, timeout} is % returned to the client. If a response is received after % the timer has fired, the response is dropped. % % The expected behavior is that the high-level timeout fires % before the gen_server call times out, therefore this interval % should be shorter then the interval used by gen_server calls. % The find_node_search/1 and get_peers_search/1 functions % are almost identical, they both recursively search for the % nodes closest to an id. The difference is that get_peers should % return as soon as it finds a node that acts as a tracker for % the infohash. % Public interface -export([start_link/1, node_port/0, ping/2, find_node/3, find_node_search/1, find_node_search/2, get_peers/3, get_peers_search/1, get_peers_search/2, announce/5, return/4]). -spec node_port() -> portnum(). -spec ping(ipaddr(), portnum()) -> pang | nodeid(). -spec find_node(ipaddr(), portnum(), nodeid()) -> {'error', 'timeout'} | {nodeid(), list(nodeinfo())}. -spec find_node_search(nodeid()) -> list(nodeinfo()). -spec find_node_search(nodeid(), list(nodeinfo())) -> list(nodeinfo()). -spec get_peers(ipaddr(), portnum(), infohash()) -> {nodeid(), token(), list(peerinfo()), list(nodeinfo())}. -spec get_peers_search(infohash()) -> {list(trackerinfo()), list(peerinfo()), list(nodeinfo())}. -spec get_peers_search(infohash(), list(nodeinfo())) -> {list(trackerinfo()), list(peerinfo()), list(nodeinfo())}. -spec announce(ipaddr(), portnum(), infohash(), token(), portnum()) -> {'error', 'timeout'} | nodeid(). -spec return(ipaddr(), portnum(), transaction(), list()) -> 'ok'. % gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). % internal exports -export([handle_query/7, decode_msg/1]). -record(state, { socket, sent, tokens }). % % Type definitions and function specifications % % Contansts and settings % srv_name() -> dht_socket_server. query_timeout() -> 2000. search_width() -> 32. search_retries() -> 4. socket_options() -> [list, inet, {active, true}]. token_lifetime() -> 5*60*1000. % % Public interface % start_link(DHTPort) -> gen_server:start({local, srv_name()}, ?MODULE, [DHTPort], []). node_port() -> gen_server:call(srv_name(), {get_node_port}). % % % ping(IP, Port) -> case gen_server:call(srv_name(), {ping, IP, Port}) of timeout -> pang; Values -> ID = decode_response(ping, Values) end. % % % find_node(IP, Port, Target) -> case gen_server:call(srv_name(), {find_node, IP, Port, Target}) of timeout -> {error, timeout}; Values -> {ID, Nodes} = decode_response(find_node, Values), etorrent_dht_state:log_request_success(ID, IP, Port), {ID, Nodes} end. % % % get_peers(IP, Port, InfoHash) -> Call = {get_peers, IP, Port, InfoHash}, case gen_server:call(srv_name(), Call) of timeout -> {error, timeout}; Values -> decode_response(get_peers, Values) end. % Recursively search for the 100 nodes that are the closest to % the local DHT node. % % Keep tabs on: % - Which nodes has been queried? % - Which nodes has responded? % - Which nodes has not been queried? find_node_search(NodeID) -> Width = search_width(), Retry = search_retries(), Nodes = etorrent_dht_state:closest_to(NodeID, Width), dht_iter_search(find_node, NodeID, Width, Retry, Nodes). find_node_search(NodeID, Nodes) -> Width = search_width(), Retry = search_retries(), dht_iter_search(find_node, NodeID, Width, Retry, Nodes). get_peers_search(InfoHash) -> Width = search_width(), Retry = search_retries(), Nodes = etorrent_dht_state:closest_to(InfoHash, Width), dht_iter_search(get_peers, InfoHash, Width, Retry, Nodes). get_peers_search(InfoHash, Nodes) -> Width = search_width(), Retry = search_retries(), dht_iter_search(get_peers, InfoHash, Width, Retry, Nodes). dht_iter_search(SearchType, Target, Width, Retry, Nodes) -> WithDist = [{distance(ID, Target), ID, IP, Port} || {ID, IP, Port} <- Nodes], dht_iter_search(SearchType, Target, Width, Retry, 0, WithDist, gb_sets:empty(), gb_sets:empty(), []). dht_iter_search(SearchType, _, _, Retry, Retry, _, _, Alive, WithPeers) -> TmpAlive = gb_sets:to_list(Alive), AliveList = [{ID, IP, Port} || {_, ID, IP, Port} <- TmpAlive], case SearchType of find_node -> AliveList; get_peers -> Trackers = [{ID, IP, Port, Token} ||{ID, IP, Port, Token, _} <- WithPeers], Peers = [Peers || {_, _, _, _, Peers} <- WithPeers], {Trackers, Peers, AliveList} end; dht_iter_search(SearchType, Target, Width, Retry, Retries, Next, Queried, Alive, WithPeers) -> % Mark all nodes in the queue as queried AddQueried = [{ID, IP, Port} || {_, ID, IP, Port} <- Next], NewQueried = gb_sets:union(Queried, gb_sets:from_list(AddQueried)), % Query all nodes in the queue and generate a list of { Dist , ID , IP , Port , Nodes } elements SearchCalls = [case SearchType of find_node -> {?MODULE, find_node, [IP, Port, Target]}; get_peers -> {?MODULE, get_peers, [IP, Port, Target]} end || {_, _, IP, Port} <- Next], ReturnValues = rpc:parallel_eval(SearchCalls), WithArgs = lists:zip(Next, ReturnValues), FailedCall = make_ref(), TmpSuccessful = [case {repack, SearchType, RetVal} of {repack, _, {error, timeout}} -> FailedCall; {repack, _, {error, response}} -> FailedCall; {repack, find_node, {NID, Nodes}} -> {{Dist, NID, IP, Port}, Nodes}; {repack, get_peers, {NID, Token, Peers, Nodes}} -> {{Dist, NID, IP, Port}, {Token, Peers, Nodes}} end || {{Dist, _ID, IP, Port}, RetVal} <- WithArgs], Successful = [E || E <- TmpSuccessful, E =/= FailedCall], % Mark all nodes that responded as alive AddAlive = [N ||{{_, _, _, _}=N, _} <- Successful], NewAlive = gb_sets:union(Alive, gb_sets:from_list(AddAlive)), % Accumulate all nodes from the successful responses. % Calculate the relative distance to all of these nodes % and keep the closest nodes which has not already been % queried in a previous iteration NodeLists = [case {acc_nodes, {SearchType, Res}} of {acc_nodes, {find_node, Nodes}} -> Nodes; {acc_nodes, {get_peers, {_, _, Nodes}}} -> Nodes end || {_, Res} <- Successful], AllNodes = lists:flatten(NodeLists), NewNodes = [Node || Node <- AllNodes, not gb_sets:is_member(Node, NewQueried)], NewNext = [{distance(ID, Target), ID, IP, Port} ||{ID, IP, Port} <- closest_to(Target, NewNodes, Width)], % Check if the closest node in the work queue is closer % to the target than the closest responsive node that was % found in this iteration. MinAliveDist = case gb_sets:size(NewAlive) of 0 -> infinity; _ -> {IMinAliveDist, _, _, _} = gb_sets:smallest(NewAlive), IMinAliveDist end, MinQueueDist = case NewNext of [] -> infinity; Other -> {MinDist, _, _, _} = lists:min(Other), MinDist end, % Check if the closest node in the work queue is closer % to the infohash than the closest responsive node. NewRetries = if (MinQueueDist < MinAliveDist) -> 0; (MinQueueDist >= MinAliveDist) -> Retries + 1 end, % Accumulate the trackers and peers found if this is a get_peers search. NewWithPeers = case SearchType of find_node -> []=WithPeers; get_peers -> Tmp=[{ID, IP, Port, Token, Peers} || {{_, ID, IP, Port}, {Token, Peers, _}} <- Successful, Peers > []], WithPeers ++ Tmp end, dht_iter_search(SearchType, Target, Width, Retry, NewRetries, NewNext, NewQueried, NewAlive, NewWithPeers). % % % announce(IP, Port, InfoHash, Token, BTPort) -> Announce = {announce, IP, Port, InfoHash, Token, BTPort}, case gen_server:call(srv_name(), Announce) of timeout -> {error, timeout}; Values -> decode_response(announce, Values) end. % % % return(IP, Port, ID, Response) -> ok = gen_server:call(srv_name(), {return, IP, Port, ID, Response}). init([DHTPort]) -> {ok, Socket} = gen_udp:open(DHTPort, socket_options()), State = #state{socket=Socket, sent=gb_trees:empty(), tokens=init_tokens(3)}, erlang:send_after(token_lifetime(), self(), renew_token), {ok, State}. timeout_reference(IP, Port, ID) -> Msg = {timeout, self(), IP, Port, ID}, erlang:send_after(query_timeout(), self(), Msg). cancel_timeout(TimeoutRef) -> erlang:cancel_timer(TimeoutRef). handle_call({ping, IP, Port}, From, State) -> Args = common_values(), do_send_query('ping', Args, IP, Port, From, State); handle_call({find_node, IP, Port, Target}, From, State) -> LTarget = etorrent_dht:list_id(Target), Args = [{<<"target">>, list_to_binary(LTarget)} | common_values()], do_send_query('find_node', Args, IP, Port, From, State); handle_call({get_peers, IP, Port, InfoHash}, From, State) -> LHash = list_to_binary(etorrent_dht:list_id(InfoHash)), Args = [{<<"info_hash">>, LHash}| common_values()], do_send_query('get_peers', Args, IP, Port, From, State); handle_call({announce, IP, Port, InfoHash, Token, BTPort}, From, State) -> LHash = list_to_binary(etorrent_dht:list_id(InfoHash)), Args = [ {<<"info_hash">>, LHash}, {<<"port">>, BTPort}, {<<"token">>, Token} | common_values()], do_send_query('announce', Args, IP, Port, From, State); handle_call({return, IP, Port, ID, Values}, _From, State) -> Socket = State#state.socket, Response = encode_response(ID, Values), ok = case gen_udp:send(Socket, IP, Port, Response) of ok -> ok; {error, einval} -> error_logger:error_msg("Error (einval) when returning to ~w:~w", [IP, Port]), ok; {error, eagain} -> error_logger:error_msg("Error (eagain) when returning to ~w:~w", [IP, Port]), ok end, {reply, ok, State}; handle_call({get_node_port}, _From, State) -> #state{ socket=Socket} = State, {ok, {_, Port}} = inet:sockname(Socket), {reply, Port, State}; handle_call({get_num_open}, _From, State) -> Sent = State#state.sent, NumSent = gb_trees:size(Sent), {reply, NumSent, State}. do_send_query(Method, Args, IP, Port, From, State) -> #state{sent=Sent, socket=Socket} = State, MsgID = unique_message_id(IP, Port, Sent), Query = encode_query(Method, MsgID, Args), case gen_udp:send(Socket, IP, Port, Query) of ok -> TRef = timeout_reference(IP, Port, MsgID), error_logger:info_msg("Sent ~w to ~w:~w", [Method, IP, Port]), NewSent = store_sent_query(IP, Port, MsgID, From, TRef, Sent), NewState = State#state{sent=NewSent}, {noreply, NewState}; {error, einval} -> error_logger:error_msg("Error (einval) when sending ~w to ~w:~w", [Method, IP, Port]), {reply, timeout, State}; {error, eagain} -> error_logger:error_msg("Error (eagain) when sending ~w to ~w:~w", [Method, IP, Port]), {reply, timeout, State} end. handle_cast(not_implemented, State) -> {noreply, State}. handle_info({timeout, _, IP, Port, ID}, State) -> #state{sent=Sent} = State, NewState = case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, _Timeout}} -> _ = gen_server:reply(Client, timeout), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end, {noreply, NewState}; handle_info(renew_token, State) -> #state{tokens=PrevTokens} = State, NewTokens = renew_token(PrevTokens), NewState = State#state{tokens=NewTokens}, erlang:send_after(token_lifetime(), self(), renew_token), {noreply, NewState}; handle_info({udp, _Socket, IP, Port, Packet}, State) -> #state{ sent=Sent, tokens=Tokens} = State, Self = etorrent_dht_state:node_id(), NewState = case (catch decode_msg(Packet)) of {'EXIT', _} -> error_logger:error_msg("Invalid packet from ~w:~w: ~w", [IP, Port, Packet]), State; {error, ID, Code, ErrorMsg} -> error_logger:error_msg("Received error from ~w:~w (~w) ~w", [IP, Port, Code, ErrorMsg]), case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, timeout), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end; {response, ID, Values} -> case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, Values), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end; {Method, ID, Params} -> error_logger:info_msg("Received ~w from ~w:~w", [Method, IP, Port]), case find_sent_query(IP, Port, ID, Sent) of {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, timeout), error_logger:error_msg("Bad node, don't send queries to yourself!"), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent}; error -> SNID = get_string("id", Params), NID = etorrent_dht:integer_id(SNID), spawn_link(etorrent_dht_state, safe_insert_node, [NID, IP, Port]), HandlerArgs = [Method, Params, IP, Port, ID, Self, Tokens], spawn_link(?MODULE, handle_query, HandlerArgs), State end end, {noreply, NewState}; handle_info(_Msg, State) -> {noreply, State}. terminate(_, State) -> ok. code_change(_, _, State) -> {ok, State}. %% Default args. Returns a proplist of default args common_values() -> Self = etorrent_dht_state:node_id(), common_values(Self). common_values(Self) -> LSelf = etorrent_dht:list_id(Self), [{<<"id">>, list_to_binary(LSelf)}]. -spec handle_query(dht_qtype(), bdict(), ipaddr(), portnum(), transaction(), nodeid(), _) -> 'ok'. handle_query('ping', _, IP, Port, MsgID, Self, _Tokens) -> return(IP, Port, MsgID, common_values(Self)); handle_query('find_node', Params, IP, Port, MsgID, Self, _Tokens) -> Target = etorrent_dht:integer_id(get_value(<<"target">>, Params)), CloseNodes = etorrent_dht_state:closest_to(Target), BinCompact = node_infos_to_compact(CloseNodes), Values = [{<<"nodes">>, BinCompact}], return(IP, Port, MsgID, common_values(Self) ++ Values); handle_query('get_peers', Params, IP, Port, MsgID, Self, Tokens) -> InfoHash = etorrent_dht:integer_id(get_value(<<"info_hash">>, Params)), Values = case etorrent_dht_tracker:get_peers(InfoHash) of [] -> Nodes = etorrent_dht_state:closest_to(InfoHash), BinCompact = node_infos_to_compact(Nodes), [{<<"nodes">>, BinCompact}]; Peers -> PeerList = [peers_to_compact([P]) || P <- Peers], [{<<"values">>, PeerList}] end, Token = [{<<"token">>, token_value(IP, Port, Tokens)}], return(IP, Port, MsgID, common_values(Self) ++ Token ++ Values); handle_query('announce', Params, IP, Port, MsgID, Self, Tokens) -> InfoHash = etorrent_dht:integer_id(get_value(<<"info_hash">>, Params)), BTPort = get_value(<<"port">>, Params), Token = get_value(<<"token">>, Params), _ = case is_valid_token(Token, IP, Port, Tokens) of true -> etorrent_dht_tracker:announce(InfoHash, IP, BTPort); false -> FmtArgs = [IP, Port, Token], error_logger:error_msg("Invalid token from ~w:~w ~w", FmtArgs) end, return(IP, Port, MsgID, common_values(Self)). unique_message_id(IP, Port, Open) -> IntID = random:uniform(16#FFFF), MsgID = <<IntID:16>>, IsLocal = gb_trees:is_defined(tkey(IP, Port, MsgID), Open), if IsLocal -> unique_message_id(IP, Port, Open); true -> MsgID end. store_sent_query(IP, Port, ID, Client, Timeout, Open) -> K = tkey(IP, Port, ID), V = tval(Client, Timeout), gb_trees:insert(K, V, Open). find_sent_query(IP, Port, ID, Open) -> case gb_trees:lookup(tkey(IP, Port, ID), Open) of none -> error; {value, Value} -> {ok, Value} end. clear_sent_query(IP, Port, ID, Open) -> gb_trees:delete(tkey(IP, Port, ID), Open). tkey(IP, Port, ID) -> {IP, Port, ID}. tval(Client, TimeoutRef) -> {Client, TimeoutRef}. get_string(What, PL) -> etorrent_bcoding:get_string_value(What, PL). % % Generate a random token value. A token value is used to filter out bogus announce % requests, or at least announce requests from nodes that never sends get_peers requests. % random_token() -> ID0 = random:uniform(16#FFFF), ID1 = random:uniform(16#FFFF), <<ID0:16, ID1:16>>. % Initialize the socket server 's token queue , the size of this queue % will be kept constant during the running-time of the server. The % size of this queue specifies how old tokens the server will accept. % init_tokens(NumTokens) -> queue:from_list([random_token() || _ <- lists:seq(1, NumTokens)]). % % Calculate the token value for a client based on the % client's IP address and Port number combined with a secret token value held by the socket server . % This avoids the need to store unique token values in the socket server. % token_value(IP, Port, Token) when is_binary(Token) -> Hash = erlang:phash2({IP, Port, Token}), <<Hash:32>>; token_value(IP, Port, Tokens) -> MostRecent = queue:last(Tokens), token_value(IP, Port, MostRecent). % % Check if a token value included by a node in an announce message is bogus % of based on a token that is not recent enough. % is_valid_token(TokenValue, IP, Port, Tokens) -> ValidValues = [token_value(IP, Port, Token) || Token <- queue:to_list(Tokens)], lists:member(TokenValue, ValidValues). % % Discard the oldest token and create a new one to replace it. % renew_token(Tokens) -> {_, WithoutOldest} = queue:out(Tokens), queue:in(random_token(), WithoutOldest). -spec decode_msg(string()) -> any(). decode_msg(InMsg) -> io:format("0: ~p\n", [InMsg]), Msg = etorrent_bcoding:decode(InMsg), io:format("0: ~p\n", [Msg]), MsgID = get_value(<<"t">>, Msg), case get_value(<<"y">>, Msg) of <<"q">> -> MString = get_value(<<"q">>, Msg), Method = string_to_method(MString), Params = get_value(<<"a">>, Msg), {Method, MsgID, Params}; <<"r">> -> Values = get_value(<<"r">>, Msg), {response, MsgID, Values}; <<"e">> -> [ECode, EMsg] = get_value(<<"e">>, Msg), {error, MsgID, ECode, EMsg} end. decode_response(ping, Values) -> etorrent_dht:integer_id(get_value(<<"id">>, Values)); decode_response(find_node, Values) -> ID = etorrent_dht:integer_id(get_value(<<"id">>, Values)), BinNodes = get_value(<<"nodes">>, Values), Nodes = compact_to_node_infos(BinNodes), {ID, Nodes}; decode_response(get_peers, Values) -> ID = etorrent_dht:integer_id(get_value(<<"id">>, Values)), Token = get_value(<<"token">>, Values), NoPeers = make_ref(), MaybePeers = get_value(<<"values">>, Values, NoPeers), {Peers, Nodes} = case MaybePeers of NoPeers when is_reference(NoPeers) -> BinCompact = get_value(<<"nodes">>, Values), INodes = compact_to_node_infos(BinCompact), {[], INodes}; BinPeers when is_list(BinPeers) -> PeerLists = [compact_to_peers(N) || N <- BinPeers], IPeers = lists:flatten(PeerLists), {IPeers, []} end, {ID, Token, Peers, Nodes}; decode_response(announce, Values) -> etorrent_dht:integer_id(get_value(<<"id">>, Values)). encode_query(Method, MsgID, Params) -> Msg = [ {<<"y">>, <<"q">>}, {<<"q">>, method_to_string(Method)}, {<<"t">>, MsgID}, {<<"a">>, Params}], etorrent_bcoding:encode(Msg). encode_response(MsgID, Values) -> Msg = [ {<<"y">>, <<"r">>}, {<<"t">>, MsgID}, {<<"r">>, Values}], etorrent_bcoding:encode(Msg). method_to_string(ping) -> <<"ping">>; method_to_string(find_node) -> <<"find_node">>; method_to_string(get_peers) -> <<"get_peers">>; method_to_string(announce) -> <<"announce_peer">>. string_to_method(<<"ping">>) -> ping; string_to_method(<<"find_node">>) -> find_node; string_to_method(<<"get_peers">>) -> get_peers; string_to_method(<<"announce_peer">>) -> announce. compact_to_peers(<<>>) -> []; compact_to_peers(<<A0, A1, A2, A3, Port:16, Rest/binary>>) -> Addr = {A0, A1, A2, A3}, [{Addr, Port}|compact_to_peers(Rest)]. peers_to_compact(PeerList) -> peers_to_compact(PeerList, <<>>). peers_to_compact([], Acc) -> Acc; peers_to_compact([{{A0, A1, A2, A3}, Port}|T], Acc) -> CPeer = <<A0, A1, A2, A3, Port:16>>, peers_to_compact(T, <<Acc/binary, CPeer/binary>>). compact_to_node_infos(<<>>) -> []; compact_to_node_infos(<<ID:160, A0, A1, A2, A3, Port:16, Rest/binary>>) -> IP = {A0, A1, A2, A3}, NodeInfo = {ID, IP, Port}, [NodeInfo|compact_to_node_infos(Rest)]. node_infos_to_compact(NodeList) -> node_infos_to_compact(NodeList, <<>>). node_infos_to_compact([], Acc) -> Acc; node_infos_to_compact([{ID, {A0, A1, A2, A3}, Port}|T], Acc) -> CNode = <<ID:160, A0, A1, A2, A3, Port:16>>, node_infos_to_compact(T, <<Acc/binary, CNode/binary>>). prova(X) -> % Enc = iolist_to_binary(etorrent_bcoding:encode(X)), Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", decode_msg(Enc). query_ping_1_test() -> Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", {ping, ID, Params} = decode_msg(Enc), ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)). -ifdef(EUNIT). fetch_id(Params) -> get_value(<<"id">>, Params). query_ping_0_test() -> Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", {ping, ID, Params} = decode_msg(Enc), ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)). query_find_node_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567896:" ++"target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe", Res = decode_msg(Enc), {find_node, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"target">>, Params)). query_get_peers_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567899:info_hash" ++"20:mnopqrstuvwxyz123456e1:q9:get_peers1:t2:aa1:y1:qe", Res = decode_msg(Enc), {get_peers, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"info_hash">>,Params)). query_announce_peer_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567899:info_hash20:" ++"mnopqrstuvwxyz1234564:porti6881e5:token8:aoeusnthe1:" ++"q13:announce_peer1:t2:aa1:y1:qe", Res = decode_msg(Enc), {announce, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"info_hash">>,Params)), ?assertEqual(<<"aoeusnth">>, get_value(<<"token">>, Params)), ?assertEqual(6881, get_value(<<"port">>, Params)). resp_ping_0_test() -> Enc = "d1:rd2:id20:mnopqrstuvwxyz123456e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, MsgID, Values} = Res, ID = decode_response(ping, Values), ?assertEqual(<<"aa">>, MsgID), ?assertEqual(etorrent_dht:integer_id(<<"mnopqrstuvwxyz123456">>), ID). resp_find_node_0_test() -> Enc = "d1:rd2:id20:0123456789abcdefghij5:nodes0:e1:t2:aa1:y1:re", {response, _, Values} = decode_msg(Enc), {ID, Nodes} = decode_response(find_node, Values), ?assertEqual(etorrent_dht:integer_id(<<"0123456789abcdefghij">>), ID), ?assertEqual([], Nodes). resp_find_node_1_test() -> Enc = "d1:rd2:id20:0123456789abcdefghij5:nodes26:" ++ "0123456789abcdefghij" ++ [0,0,0,0,0,0] ++ "e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {_, Nodes} = decode_response(find_node, Values), ?assertEqual([{etorrent_dht:integer_id("0123456789abcdefghij"), {0,0,0,0}, 0}], Nodes). resp_get_peers_0_test() -> Enc = "d1:rd2:id20:abcdefghij01234567895:token8:aoeusnth6:values" ++ "l6:axje.u6:idhtnmee1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {ID, Token, Peers, Nodes} = decode_response(get_peers, Values), ?assertEqual(etorrent_dht:integer_id(<<"abcdefghij0123456789">>), ID), ?assertEqual(<<"aoeusnth">>, Token), ?assertEqual([{{97,120,106,101},11893}, {{105,100,104,116}, 28269}], Peers). resp_get_peers_1_test() -> Enc = "d1:rd2:id20:abcdefghij01234567895:nodes26:" ++ "0123456789abcdefghijdef4565:token8:aoeusnthe" ++ "1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {ID, Token, Peers, Nodes} = decode_response(get_peers, Values), ?assertEqual(etorrent_dht:integer_id(<<"abcdefghij0123456789">>), ID), ?assertEqual(<<"aoeusnth">>, Token), ?assertEqual([{etorrent_dht:integer_id(<<"0123456789abcdefghij">>), {100,101,102,52},13622}], Nodes). resp_announce_peer_0_test() -> Enc = "d1:rd2:id20:mnopqrstuvwxyz123456e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, ID = decode_response(announce, Values), ?assertEqual(etorrent_dht:integer_id(<<"mnopqrstuvwxyz123456">>), ID). -ifdef(EQC). octet() -> choose(0, 255). portnum() -> choose(0, 16#FFFF). dht_node() -> {{octet(), octet(), octet(), octet()}, portnum()}. integer_id() -> ?LET(ID, binary(20), etorrent_dht:integer_id(ID)). node_id() -> integer_id(). info_hash() -> integer_id(). token() -> binary(20). transaction() -> binary(2). ping_query() -> {ping, [{<<"id">>, node_id()}]}. find_node_query() -> {find_node, [{<<"id">>, node_id()}, {<<"target">>, node_id()}]}. get_peers_query() -> {get_peers, [{<<"id">>, node_id()}, {<<"info_hash">>, info_hash()}]}. announce_query() -> {announce, [{<<"id">>, node_id()}, {<<"info_hash">>, info_hash()}, {<<"token">>, token()}, {<<"port">>, portnum()}]}. dht_query() -> All = [ping_query(), find_node_query(), get_peers_query(), announce_query()], oneof([{Method, transaction(), lists:sort(Params)} || {Method, Params} <- All]). prop_inv_compact() -> ?FORALL(Input, list(dht_node()), begin Compact = peers_to_compact(Input), Output = compact_to_peers(iolist_to_binary(Compact)), Input =:= Output end). prop_inv_compact_test() -> ?assert(eqc:quickcheck(prop_inv_compact())). prop_query_inv() -> ?FORALL(InQ, dht_query(), begin {Method, MsgId, Params} = InQ, EncQ = iolist_to_binary(encode_query(Method, MsgId, Params)), OutQ = decode_msg(EncQ), OutQ =:= InQ end). prop_query_inv_test() -> ?assert(eqc:quickcheck(prop_query_inv())). EQC -endif.
null
https://raw.githubusercontent.com/serperu/secer/ffe2f9602356c34c9465c44534c82cc758b809b5/examples/etorrent/etorrent_dht_net.erl
erlang
-ifdef(TEST). -include_lib("eqc/include/eqc.hrl"). -endif. Implementation notes RPC calls to remote nodes in the DHT are exposed to clients using the gen_server call mechanism. In order to make this work the client reference passed to the handle_call/3 callback is stored in the server state. When a response is received from the remote node, the source IP and port combined with the message id is used to map the response to the correct client reference. A timer is used to notify the server of requests that time out, if a request times out {error, timeout} is returned to the client. If a response is received after the timer has fired, the response is dropped. The expected behavior is that the high-level timeout fires before the gen_server call times out, therefore this interval should be shorter then the interval used by gen_server calls. are almost identical, they both recursively search for the nodes closest to an id. The difference is that get_peers should return as soon as it finds a node that acts as a tracker for the infohash. Public interface gen_server callbacks internal exports Type definitions and function specifications Public interface the local DHT node. Keep tabs on: - Which nodes has been queried? - Which nodes has responded? - Which nodes has not been queried? Mark all nodes in the queue as queried Query all nodes in the queue and generate a list of Mark all nodes that responded as alive Accumulate all nodes from the successful responses. Calculate the relative distance to all of these nodes and keep the closest nodes which has not already been queried in a previous iteration Check if the closest node in the work queue is closer to the target than the closest responsive node that was found in this iteration. Check if the closest node in the work queue is closer to the infohash than the closest responsive node. Accumulate the trackers and peers found if this is a get_peers search. Default args. Returns a proplist of default args Generate a random token value. A token value is used to filter out bogus announce requests, or at least announce requests from nodes that never sends get_peers requests. will be kept constant during the running-time of the server. The size of this queue specifies how old tokens the server will accept. Calculate the token value for a client based on the % client's IP address This avoids the need to store unique token values in the socket server. Check if a token value included by a node in an announce message is bogus of based on a token that is not recent enough. Discard the oldest token and create a new one to replace it. Enc = iolist_to_binary(etorrent_bcoding:encode(X)),
-module(etorrent_dht_net). -include("types.hrl"). -export([prova/1]). -include_lib("eunit/include/eunit.hrl"). -ifdef(EQC). -export([prop_query_inv/0, prop_inv_compact/0]). -endif. -behaviour(gen_server). -import(etorrent_bcoding, [get_value/2, get_value/3]). -import(etorrent_dht, [distance/2, closest_to/3]). The find_node_search/1 and get_peers_search/1 functions -export([start_link/1, node_port/0, ping/2, find_node/3, find_node_search/1, find_node_search/2, get_peers/3, get_peers_search/1, get_peers_search/2, announce/5, return/4]). -spec node_port() -> portnum(). -spec ping(ipaddr(), portnum()) -> pang | nodeid(). -spec find_node(ipaddr(), portnum(), nodeid()) -> {'error', 'timeout'} | {nodeid(), list(nodeinfo())}. -spec find_node_search(nodeid()) -> list(nodeinfo()). -spec find_node_search(nodeid(), list(nodeinfo())) -> list(nodeinfo()). -spec get_peers(ipaddr(), portnum(), infohash()) -> {nodeid(), token(), list(peerinfo()), list(nodeinfo())}. -spec get_peers_search(infohash()) -> {list(trackerinfo()), list(peerinfo()), list(nodeinfo())}. -spec get_peers_search(infohash(), list(nodeinfo())) -> {list(trackerinfo()), list(peerinfo()), list(nodeinfo())}. -spec announce(ipaddr(), portnum(), infohash(), token(), portnum()) -> {'error', 'timeout'} | nodeid(). -spec return(ipaddr(), portnum(), transaction(), list()) -> 'ok'. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([handle_query/7, decode_msg/1]). -record(state, { socket, sent, tokens }). Contansts and settings srv_name() -> dht_socket_server. query_timeout() -> 2000. search_width() -> 32. search_retries() -> 4. socket_options() -> [list, inet, {active, true}]. token_lifetime() -> 5*60*1000. start_link(DHTPort) -> gen_server:start({local, srv_name()}, ?MODULE, [DHTPort], []). node_port() -> gen_server:call(srv_name(), {get_node_port}). ping(IP, Port) -> case gen_server:call(srv_name(), {ping, IP, Port}) of timeout -> pang; Values -> ID = decode_response(ping, Values) end. find_node(IP, Port, Target) -> case gen_server:call(srv_name(), {find_node, IP, Port, Target}) of timeout -> {error, timeout}; Values -> {ID, Nodes} = decode_response(find_node, Values), etorrent_dht_state:log_request_success(ID, IP, Port), {ID, Nodes} end. get_peers(IP, Port, InfoHash) -> Call = {get_peers, IP, Port, InfoHash}, case gen_server:call(srv_name(), Call) of timeout -> {error, timeout}; Values -> decode_response(get_peers, Values) end. Recursively search for the 100 nodes that are the closest to find_node_search(NodeID) -> Width = search_width(), Retry = search_retries(), Nodes = etorrent_dht_state:closest_to(NodeID, Width), dht_iter_search(find_node, NodeID, Width, Retry, Nodes). find_node_search(NodeID, Nodes) -> Width = search_width(), Retry = search_retries(), dht_iter_search(find_node, NodeID, Width, Retry, Nodes). get_peers_search(InfoHash) -> Width = search_width(), Retry = search_retries(), Nodes = etorrent_dht_state:closest_to(InfoHash, Width), dht_iter_search(get_peers, InfoHash, Width, Retry, Nodes). get_peers_search(InfoHash, Nodes) -> Width = search_width(), Retry = search_retries(), dht_iter_search(get_peers, InfoHash, Width, Retry, Nodes). dht_iter_search(SearchType, Target, Width, Retry, Nodes) -> WithDist = [{distance(ID, Target), ID, IP, Port} || {ID, IP, Port} <- Nodes], dht_iter_search(SearchType, Target, Width, Retry, 0, WithDist, gb_sets:empty(), gb_sets:empty(), []). dht_iter_search(SearchType, _, _, Retry, Retry, _, _, Alive, WithPeers) -> TmpAlive = gb_sets:to_list(Alive), AliveList = [{ID, IP, Port} || {_, ID, IP, Port} <- TmpAlive], case SearchType of find_node -> AliveList; get_peers -> Trackers = [{ID, IP, Port, Token} ||{ID, IP, Port, Token, _} <- WithPeers], Peers = [Peers || {_, _, _, _, Peers} <- WithPeers], {Trackers, Peers, AliveList} end; dht_iter_search(SearchType, Target, Width, Retry, Retries, Next, Queried, Alive, WithPeers) -> AddQueried = [{ID, IP, Port} || {_, ID, IP, Port} <- Next], NewQueried = gb_sets:union(Queried, gb_sets:from_list(AddQueried)), { Dist , ID , IP , Port , Nodes } elements SearchCalls = [case SearchType of find_node -> {?MODULE, find_node, [IP, Port, Target]}; get_peers -> {?MODULE, get_peers, [IP, Port, Target]} end || {_, _, IP, Port} <- Next], ReturnValues = rpc:parallel_eval(SearchCalls), WithArgs = lists:zip(Next, ReturnValues), FailedCall = make_ref(), TmpSuccessful = [case {repack, SearchType, RetVal} of {repack, _, {error, timeout}} -> FailedCall; {repack, _, {error, response}} -> FailedCall; {repack, find_node, {NID, Nodes}} -> {{Dist, NID, IP, Port}, Nodes}; {repack, get_peers, {NID, Token, Peers, Nodes}} -> {{Dist, NID, IP, Port}, {Token, Peers, Nodes}} end || {{Dist, _ID, IP, Port}, RetVal} <- WithArgs], Successful = [E || E <- TmpSuccessful, E =/= FailedCall], AddAlive = [N ||{{_, _, _, _}=N, _} <- Successful], NewAlive = gb_sets:union(Alive, gb_sets:from_list(AddAlive)), NodeLists = [case {acc_nodes, {SearchType, Res}} of {acc_nodes, {find_node, Nodes}} -> Nodes; {acc_nodes, {get_peers, {_, _, Nodes}}} -> Nodes end || {_, Res} <- Successful], AllNodes = lists:flatten(NodeLists), NewNodes = [Node || Node <- AllNodes, not gb_sets:is_member(Node, NewQueried)], NewNext = [{distance(ID, Target), ID, IP, Port} ||{ID, IP, Port} <- closest_to(Target, NewNodes, Width)], MinAliveDist = case gb_sets:size(NewAlive) of 0 -> infinity; _ -> {IMinAliveDist, _, _, _} = gb_sets:smallest(NewAlive), IMinAliveDist end, MinQueueDist = case NewNext of [] -> infinity; Other -> {MinDist, _, _, _} = lists:min(Other), MinDist end, NewRetries = if (MinQueueDist < MinAliveDist) -> 0; (MinQueueDist >= MinAliveDist) -> Retries + 1 end, NewWithPeers = case SearchType of find_node -> []=WithPeers; get_peers -> Tmp=[{ID, IP, Port, Token, Peers} || {{_, ID, IP, Port}, {Token, Peers, _}} <- Successful, Peers > []], WithPeers ++ Tmp end, dht_iter_search(SearchType, Target, Width, Retry, NewRetries, NewNext, NewQueried, NewAlive, NewWithPeers). announce(IP, Port, InfoHash, Token, BTPort) -> Announce = {announce, IP, Port, InfoHash, Token, BTPort}, case gen_server:call(srv_name(), Announce) of timeout -> {error, timeout}; Values -> decode_response(announce, Values) end. return(IP, Port, ID, Response) -> ok = gen_server:call(srv_name(), {return, IP, Port, ID, Response}). init([DHTPort]) -> {ok, Socket} = gen_udp:open(DHTPort, socket_options()), State = #state{socket=Socket, sent=gb_trees:empty(), tokens=init_tokens(3)}, erlang:send_after(token_lifetime(), self(), renew_token), {ok, State}. timeout_reference(IP, Port, ID) -> Msg = {timeout, self(), IP, Port, ID}, erlang:send_after(query_timeout(), self(), Msg). cancel_timeout(TimeoutRef) -> erlang:cancel_timer(TimeoutRef). handle_call({ping, IP, Port}, From, State) -> Args = common_values(), do_send_query('ping', Args, IP, Port, From, State); handle_call({find_node, IP, Port, Target}, From, State) -> LTarget = etorrent_dht:list_id(Target), Args = [{<<"target">>, list_to_binary(LTarget)} | common_values()], do_send_query('find_node', Args, IP, Port, From, State); handle_call({get_peers, IP, Port, InfoHash}, From, State) -> LHash = list_to_binary(etorrent_dht:list_id(InfoHash)), Args = [{<<"info_hash">>, LHash}| common_values()], do_send_query('get_peers', Args, IP, Port, From, State); handle_call({announce, IP, Port, InfoHash, Token, BTPort}, From, State) -> LHash = list_to_binary(etorrent_dht:list_id(InfoHash)), Args = [ {<<"info_hash">>, LHash}, {<<"port">>, BTPort}, {<<"token">>, Token} | common_values()], do_send_query('announce', Args, IP, Port, From, State); handle_call({return, IP, Port, ID, Values}, _From, State) -> Socket = State#state.socket, Response = encode_response(ID, Values), ok = case gen_udp:send(Socket, IP, Port, Response) of ok -> ok; {error, einval} -> error_logger:error_msg("Error (einval) when returning to ~w:~w", [IP, Port]), ok; {error, eagain} -> error_logger:error_msg("Error (eagain) when returning to ~w:~w", [IP, Port]), ok end, {reply, ok, State}; handle_call({get_node_port}, _From, State) -> #state{ socket=Socket} = State, {ok, {_, Port}} = inet:sockname(Socket), {reply, Port, State}; handle_call({get_num_open}, _From, State) -> Sent = State#state.sent, NumSent = gb_trees:size(Sent), {reply, NumSent, State}. do_send_query(Method, Args, IP, Port, From, State) -> #state{sent=Sent, socket=Socket} = State, MsgID = unique_message_id(IP, Port, Sent), Query = encode_query(Method, MsgID, Args), case gen_udp:send(Socket, IP, Port, Query) of ok -> TRef = timeout_reference(IP, Port, MsgID), error_logger:info_msg("Sent ~w to ~w:~w", [Method, IP, Port]), NewSent = store_sent_query(IP, Port, MsgID, From, TRef, Sent), NewState = State#state{sent=NewSent}, {noreply, NewState}; {error, einval} -> error_logger:error_msg("Error (einval) when sending ~w to ~w:~w", [Method, IP, Port]), {reply, timeout, State}; {error, eagain} -> error_logger:error_msg("Error (eagain) when sending ~w to ~w:~w", [Method, IP, Port]), {reply, timeout, State} end. handle_cast(not_implemented, State) -> {noreply, State}. handle_info({timeout, _, IP, Port, ID}, State) -> #state{sent=Sent} = State, NewState = case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, _Timeout}} -> _ = gen_server:reply(Client, timeout), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end, {noreply, NewState}; handle_info(renew_token, State) -> #state{tokens=PrevTokens} = State, NewTokens = renew_token(PrevTokens), NewState = State#state{tokens=NewTokens}, erlang:send_after(token_lifetime(), self(), renew_token), {noreply, NewState}; handle_info({udp, _Socket, IP, Port, Packet}, State) -> #state{ sent=Sent, tokens=Tokens} = State, Self = etorrent_dht_state:node_id(), NewState = case (catch decode_msg(Packet)) of {'EXIT', _} -> error_logger:error_msg("Invalid packet from ~w:~w: ~w", [IP, Port, Packet]), State; {error, ID, Code, ErrorMsg} -> error_logger:error_msg("Received error from ~w:~w (~w) ~w", [IP, Port, Code, ErrorMsg]), case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, timeout), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end; {response, ID, Values} -> case find_sent_query(IP, Port, ID, Sent) of error -> State; {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, Values), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent} end; {Method, ID, Params} -> error_logger:info_msg("Received ~w from ~w:~w", [Method, IP, Port]), case find_sent_query(IP, Port, ID, Sent) of {ok, {Client, Timeout}} -> _ = cancel_timeout(Timeout), _ = gen_server:reply(Client, timeout), error_logger:error_msg("Bad node, don't send queries to yourself!"), NewSent = clear_sent_query(IP, Port, ID, Sent), State#state{sent=NewSent}; error -> SNID = get_string("id", Params), NID = etorrent_dht:integer_id(SNID), spawn_link(etorrent_dht_state, safe_insert_node, [NID, IP, Port]), HandlerArgs = [Method, Params, IP, Port, ID, Self, Tokens], spawn_link(?MODULE, handle_query, HandlerArgs), State end end, {noreply, NewState}; handle_info(_Msg, State) -> {noreply, State}. terminate(_, State) -> ok. code_change(_, _, State) -> {ok, State}. common_values() -> Self = etorrent_dht_state:node_id(), common_values(Self). common_values(Self) -> LSelf = etorrent_dht:list_id(Self), [{<<"id">>, list_to_binary(LSelf)}]. -spec handle_query(dht_qtype(), bdict(), ipaddr(), portnum(), transaction(), nodeid(), _) -> 'ok'. handle_query('ping', _, IP, Port, MsgID, Self, _Tokens) -> return(IP, Port, MsgID, common_values(Self)); handle_query('find_node', Params, IP, Port, MsgID, Self, _Tokens) -> Target = etorrent_dht:integer_id(get_value(<<"target">>, Params)), CloseNodes = etorrent_dht_state:closest_to(Target), BinCompact = node_infos_to_compact(CloseNodes), Values = [{<<"nodes">>, BinCompact}], return(IP, Port, MsgID, common_values(Self) ++ Values); handle_query('get_peers', Params, IP, Port, MsgID, Self, Tokens) -> InfoHash = etorrent_dht:integer_id(get_value(<<"info_hash">>, Params)), Values = case etorrent_dht_tracker:get_peers(InfoHash) of [] -> Nodes = etorrent_dht_state:closest_to(InfoHash), BinCompact = node_infos_to_compact(Nodes), [{<<"nodes">>, BinCompact}]; Peers -> PeerList = [peers_to_compact([P]) || P <- Peers], [{<<"values">>, PeerList}] end, Token = [{<<"token">>, token_value(IP, Port, Tokens)}], return(IP, Port, MsgID, common_values(Self) ++ Token ++ Values); handle_query('announce', Params, IP, Port, MsgID, Self, Tokens) -> InfoHash = etorrent_dht:integer_id(get_value(<<"info_hash">>, Params)), BTPort = get_value(<<"port">>, Params), Token = get_value(<<"token">>, Params), _ = case is_valid_token(Token, IP, Port, Tokens) of true -> etorrent_dht_tracker:announce(InfoHash, IP, BTPort); false -> FmtArgs = [IP, Port, Token], error_logger:error_msg("Invalid token from ~w:~w ~w", FmtArgs) end, return(IP, Port, MsgID, common_values(Self)). unique_message_id(IP, Port, Open) -> IntID = random:uniform(16#FFFF), MsgID = <<IntID:16>>, IsLocal = gb_trees:is_defined(tkey(IP, Port, MsgID), Open), if IsLocal -> unique_message_id(IP, Port, Open); true -> MsgID end. store_sent_query(IP, Port, ID, Client, Timeout, Open) -> K = tkey(IP, Port, ID), V = tval(Client, Timeout), gb_trees:insert(K, V, Open). find_sent_query(IP, Port, ID, Open) -> case gb_trees:lookup(tkey(IP, Port, ID), Open) of none -> error; {value, Value} -> {ok, Value} end. clear_sent_query(IP, Port, ID, Open) -> gb_trees:delete(tkey(IP, Port, ID), Open). tkey(IP, Port, ID) -> {IP, Port, ID}. tval(Client, TimeoutRef) -> {Client, TimeoutRef}. get_string(What, PL) -> etorrent_bcoding:get_string_value(What, PL). random_token() -> ID0 = random:uniform(16#FFFF), ID1 = random:uniform(16#FFFF), <<ID0:16, ID1:16>>. Initialize the socket server 's token queue , the size of this queue init_tokens(NumTokens) -> queue:from_list([random_token() || _ <- lists:seq(1, NumTokens)]). and Port number combined with a secret token value held by the socket server . token_value(IP, Port, Token) when is_binary(Token) -> Hash = erlang:phash2({IP, Port, Token}), <<Hash:32>>; token_value(IP, Port, Tokens) -> MostRecent = queue:last(Tokens), token_value(IP, Port, MostRecent). is_valid_token(TokenValue, IP, Port, Tokens) -> ValidValues = [token_value(IP, Port, Token) || Token <- queue:to_list(Tokens)], lists:member(TokenValue, ValidValues). renew_token(Tokens) -> {_, WithoutOldest} = queue:out(Tokens), queue:in(random_token(), WithoutOldest). -spec decode_msg(string()) -> any(). decode_msg(InMsg) -> io:format("0: ~p\n", [InMsg]), Msg = etorrent_bcoding:decode(InMsg), io:format("0: ~p\n", [Msg]), MsgID = get_value(<<"t">>, Msg), case get_value(<<"y">>, Msg) of <<"q">> -> MString = get_value(<<"q">>, Msg), Method = string_to_method(MString), Params = get_value(<<"a">>, Msg), {Method, MsgID, Params}; <<"r">> -> Values = get_value(<<"r">>, Msg), {response, MsgID, Values}; <<"e">> -> [ECode, EMsg] = get_value(<<"e">>, Msg), {error, MsgID, ECode, EMsg} end. decode_response(ping, Values) -> etorrent_dht:integer_id(get_value(<<"id">>, Values)); decode_response(find_node, Values) -> ID = etorrent_dht:integer_id(get_value(<<"id">>, Values)), BinNodes = get_value(<<"nodes">>, Values), Nodes = compact_to_node_infos(BinNodes), {ID, Nodes}; decode_response(get_peers, Values) -> ID = etorrent_dht:integer_id(get_value(<<"id">>, Values)), Token = get_value(<<"token">>, Values), NoPeers = make_ref(), MaybePeers = get_value(<<"values">>, Values, NoPeers), {Peers, Nodes} = case MaybePeers of NoPeers when is_reference(NoPeers) -> BinCompact = get_value(<<"nodes">>, Values), INodes = compact_to_node_infos(BinCompact), {[], INodes}; BinPeers when is_list(BinPeers) -> PeerLists = [compact_to_peers(N) || N <- BinPeers], IPeers = lists:flatten(PeerLists), {IPeers, []} end, {ID, Token, Peers, Nodes}; decode_response(announce, Values) -> etorrent_dht:integer_id(get_value(<<"id">>, Values)). encode_query(Method, MsgID, Params) -> Msg = [ {<<"y">>, <<"q">>}, {<<"q">>, method_to_string(Method)}, {<<"t">>, MsgID}, {<<"a">>, Params}], etorrent_bcoding:encode(Msg). encode_response(MsgID, Values) -> Msg = [ {<<"y">>, <<"r">>}, {<<"t">>, MsgID}, {<<"r">>, Values}], etorrent_bcoding:encode(Msg). method_to_string(ping) -> <<"ping">>; method_to_string(find_node) -> <<"find_node">>; method_to_string(get_peers) -> <<"get_peers">>; method_to_string(announce) -> <<"announce_peer">>. string_to_method(<<"ping">>) -> ping; string_to_method(<<"find_node">>) -> find_node; string_to_method(<<"get_peers">>) -> get_peers; string_to_method(<<"announce_peer">>) -> announce. compact_to_peers(<<>>) -> []; compact_to_peers(<<A0, A1, A2, A3, Port:16, Rest/binary>>) -> Addr = {A0, A1, A2, A3}, [{Addr, Port}|compact_to_peers(Rest)]. peers_to_compact(PeerList) -> peers_to_compact(PeerList, <<>>). peers_to_compact([], Acc) -> Acc; peers_to_compact([{{A0, A1, A2, A3}, Port}|T], Acc) -> CPeer = <<A0, A1, A2, A3, Port:16>>, peers_to_compact(T, <<Acc/binary, CPeer/binary>>). compact_to_node_infos(<<>>) -> []; compact_to_node_infos(<<ID:160, A0, A1, A2, A3, Port:16, Rest/binary>>) -> IP = {A0, A1, A2, A3}, NodeInfo = {ID, IP, Port}, [NodeInfo|compact_to_node_infos(Rest)]. node_infos_to_compact(NodeList) -> node_infos_to_compact(NodeList, <<>>). node_infos_to_compact([], Acc) -> Acc; node_infos_to_compact([{ID, {A0, A1, A2, A3}, Port}|T], Acc) -> CNode = <<ID:160, A0, A1, A2, A3, Port:16>>, node_infos_to_compact(T, <<Acc/binary, CNode/binary>>). prova(X) -> Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", decode_msg(Enc). query_ping_1_test() -> Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", {ping, ID, Params} = decode_msg(Enc), ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)). -ifdef(EUNIT). fetch_id(Params) -> get_value(<<"id">>, Params). query_ping_0_test() -> Enc = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", {ping, ID, Params} = decode_msg(Enc), ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)). query_find_node_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567896:" ++"target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe", Res = decode_msg(Enc), {find_node, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"target">>, Params)). query_get_peers_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567899:info_hash" ++"20:mnopqrstuvwxyz123456e1:q9:get_peers1:t2:aa1:y1:qe", Res = decode_msg(Enc), {get_peers, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"info_hash">>,Params)). query_announce_peer_0_test() -> Enc = "d1:ad2:id20:abcdefghij01234567899:info_hash20:" ++"mnopqrstuvwxyz1234564:porti6881e5:token8:aoeusnthe1:" ++"q13:announce_peer1:t2:aa1:y1:qe", Res = decode_msg(Enc), {announce, ID, Params} = Res, ?assertEqual(<<"aa">>, ID), ?assertEqual(<<"abcdefghij0123456789">>, fetch_id(Params)), ?assertEqual(<<"mnopqrstuvwxyz123456">>, get_value(<<"info_hash">>,Params)), ?assertEqual(<<"aoeusnth">>, get_value(<<"token">>, Params)), ?assertEqual(6881, get_value(<<"port">>, Params)). resp_ping_0_test() -> Enc = "d1:rd2:id20:mnopqrstuvwxyz123456e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, MsgID, Values} = Res, ID = decode_response(ping, Values), ?assertEqual(<<"aa">>, MsgID), ?assertEqual(etorrent_dht:integer_id(<<"mnopqrstuvwxyz123456">>), ID). resp_find_node_0_test() -> Enc = "d1:rd2:id20:0123456789abcdefghij5:nodes0:e1:t2:aa1:y1:re", {response, _, Values} = decode_msg(Enc), {ID, Nodes} = decode_response(find_node, Values), ?assertEqual(etorrent_dht:integer_id(<<"0123456789abcdefghij">>), ID), ?assertEqual([], Nodes). resp_find_node_1_test() -> Enc = "d1:rd2:id20:0123456789abcdefghij5:nodes26:" ++ "0123456789abcdefghij" ++ [0,0,0,0,0,0] ++ "e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {_, Nodes} = decode_response(find_node, Values), ?assertEqual([{etorrent_dht:integer_id("0123456789abcdefghij"), {0,0,0,0}, 0}], Nodes). resp_get_peers_0_test() -> Enc = "d1:rd2:id20:abcdefghij01234567895:token8:aoeusnth6:values" ++ "l6:axje.u6:idhtnmee1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {ID, Token, Peers, Nodes} = decode_response(get_peers, Values), ?assertEqual(etorrent_dht:integer_id(<<"abcdefghij0123456789">>), ID), ?assertEqual(<<"aoeusnth">>, Token), ?assertEqual([{{97,120,106,101},11893}, {{105,100,104,116}, 28269}], Peers). resp_get_peers_1_test() -> Enc = "d1:rd2:id20:abcdefghij01234567895:nodes26:" ++ "0123456789abcdefghijdef4565:token8:aoeusnthe" ++ "1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, {ID, Token, Peers, Nodes} = decode_response(get_peers, Values), ?assertEqual(etorrent_dht:integer_id(<<"abcdefghij0123456789">>), ID), ?assertEqual(<<"aoeusnth">>, Token), ?assertEqual([{etorrent_dht:integer_id(<<"0123456789abcdefghij">>), {100,101,102,52},13622}], Nodes). resp_announce_peer_0_test() -> Enc = "d1:rd2:id20:mnopqrstuvwxyz123456e1:t2:aa1:y1:re", Res = decode_msg(Enc), {response, _, Values} = Res, ID = decode_response(announce, Values), ?assertEqual(etorrent_dht:integer_id(<<"mnopqrstuvwxyz123456">>), ID). -ifdef(EQC). octet() -> choose(0, 255). portnum() -> choose(0, 16#FFFF). dht_node() -> {{octet(), octet(), octet(), octet()}, portnum()}. integer_id() -> ?LET(ID, binary(20), etorrent_dht:integer_id(ID)). node_id() -> integer_id(). info_hash() -> integer_id(). token() -> binary(20). transaction() -> binary(2). ping_query() -> {ping, [{<<"id">>, node_id()}]}. find_node_query() -> {find_node, [{<<"id">>, node_id()}, {<<"target">>, node_id()}]}. get_peers_query() -> {get_peers, [{<<"id">>, node_id()}, {<<"info_hash">>, info_hash()}]}. announce_query() -> {announce, [{<<"id">>, node_id()}, {<<"info_hash">>, info_hash()}, {<<"token">>, token()}, {<<"port">>, portnum()}]}. dht_query() -> All = [ping_query(), find_node_query(), get_peers_query(), announce_query()], oneof([{Method, transaction(), lists:sort(Params)} || {Method, Params} <- All]). prop_inv_compact() -> ?FORALL(Input, list(dht_node()), begin Compact = peers_to_compact(Input), Output = compact_to_peers(iolist_to_binary(Compact)), Input =:= Output end). prop_inv_compact_test() -> ?assert(eqc:quickcheck(prop_inv_compact())). prop_query_inv() -> ?FORALL(InQ, dht_query(), begin {Method, MsgId, Params} = InQ, EncQ = iolist_to_binary(encode_query(Method, MsgId, Params)), OutQ = decode_msg(EncQ), OutQ =:= InQ end). prop_query_inv_test() -> ?assert(eqc:quickcheck(prop_query_inv())). EQC -endif.
c634eb18917ee5bd8d582fae39cdd88dfde31c2576c44cf0ac674ccfb414a419
maximedenes/native-coq
type_errors.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Names open Term open Sign open Environ open Reduction (* Type errors. *) type guard_error = (* Fixpoints *) | NotEnoughAbstractionInFixBody | RecursionNotOnInductiveType of constr | RecursionOnIllegalTerm of int * (env * constr) * int list * int list | NotEnoughArgumentsForFixCall of int (* CoFixpoints *) | CodomainNotInductiveType of constr | NestedRecursiveOccurrences | UnguardedRecursiveCall of constr | RecCallInTypeOfAbstraction of constr | RecCallInNonRecArgOfConstructor of constr | RecCallInTypeOfDef of constr | RecCallInCaseFun of constr | RecCallInCaseArg of constr | RecCallInCasePred of constr | NotGuardedForm of constr type arity_error = | NonInformativeToInformative | StrongEliminationOnNonSmallType | WrongArity type type_error = | UnboundRel of int | UnboundVar of variable | NotAType of unsafe_judgment | BadAssumption of unsafe_judgment | ReferenceVariables of constr | ElimArity of inductive * sorts_family list * constr * unsafe_judgment * (sorts_family * sorts_family * arity_error) option | CaseNotInductive of unsafe_judgment | WrongCaseInfo of inductive * case_info | NumberBranches of unsafe_judgment * int | IllFormedBranch of constr * constructor * constr * constr | Generalization of (name * types) * unsafe_judgment | ActualType of unsafe_judgment * types | CantApplyBadType of (int * constr * constr) * unsafe_judgment * unsafe_judgment array | CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array | IllFormedRecBody of guard_error * name array * int * env * unsafe_judgment array | IllTypedRecBody of int * name array * unsafe_judgment array * types array exception TypeError of env * type_error let nfj {uj_val=c;uj_type=ct} = {uj_val=c;uj_type=nf_betaiota ct} let error_unbound_rel env n = raise (TypeError (env, UnboundRel n)) let error_unbound_var env v = raise (TypeError (env, UnboundVar v)) let error_not_type env j = raise (TypeError (env, NotAType j)) let error_assumption env j = raise (TypeError (env, BadAssumption j)) let error_reference_variables env id = raise (TypeError (env, ReferenceVariables id)) let error_elim_arity env ind aritylst c pj okinds = raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds))) let error_case_not_inductive env j = raise (TypeError (env, CaseNotInductive j)) let error_number_branches env cj expn = raise (TypeError (env, NumberBranches (nfj cj,expn))) let error_ill_formed_branch env c i actty expty = raise (TypeError (env, IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty))) let error_generalization env nvar c = raise (TypeError (env, Generalization (nvar,c))) let error_actual_type env j expty = raise (TypeError (env, ActualType (j,expty))) let error_cant_apply_not_functional env rator randl = raise (TypeError (env, CantApplyNonFunctional (rator,randl))) let error_cant_apply_bad_type env t rator randl = raise (TypeError (env, CantApplyBadType (t,rator,randl))) let error_ill_formed_rec_body env why lna i fixenv vdefj = raise (TypeError (env, IllFormedRecBody (why,lna,i,fixenv,vdefj))) let error_ill_typed_rec_body env i lna vdefj vargs = raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs))) let error_elim_explain kp ki = match kp,ki with | (InType | InSet), InProp -> NonInformativeToInformative | InType, InSet -> StrongEliminationOnNonSmallType (* if Set impredicative *) | _ -> WrongArity
null
https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/kernel/type_errors.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Type errors. Fixpoints CoFixpoints if Set impredicative
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Term open Sign open Environ open Reduction type guard_error = | NotEnoughAbstractionInFixBody | RecursionNotOnInductiveType of constr | RecursionOnIllegalTerm of int * (env * constr) * int list * int list | NotEnoughArgumentsForFixCall of int | CodomainNotInductiveType of constr | NestedRecursiveOccurrences | UnguardedRecursiveCall of constr | RecCallInTypeOfAbstraction of constr | RecCallInNonRecArgOfConstructor of constr | RecCallInTypeOfDef of constr | RecCallInCaseFun of constr | RecCallInCaseArg of constr | RecCallInCasePred of constr | NotGuardedForm of constr type arity_error = | NonInformativeToInformative | StrongEliminationOnNonSmallType | WrongArity type type_error = | UnboundRel of int | UnboundVar of variable | NotAType of unsafe_judgment | BadAssumption of unsafe_judgment | ReferenceVariables of constr | ElimArity of inductive * sorts_family list * constr * unsafe_judgment * (sorts_family * sorts_family * arity_error) option | CaseNotInductive of unsafe_judgment | WrongCaseInfo of inductive * case_info | NumberBranches of unsafe_judgment * int | IllFormedBranch of constr * constructor * constr * constr | Generalization of (name * types) * unsafe_judgment | ActualType of unsafe_judgment * types | CantApplyBadType of (int * constr * constr) * unsafe_judgment * unsafe_judgment array | CantApplyNonFunctional of unsafe_judgment * unsafe_judgment array | IllFormedRecBody of guard_error * name array * int * env * unsafe_judgment array | IllTypedRecBody of int * name array * unsafe_judgment array * types array exception TypeError of env * type_error let nfj {uj_val=c;uj_type=ct} = {uj_val=c;uj_type=nf_betaiota ct} let error_unbound_rel env n = raise (TypeError (env, UnboundRel n)) let error_unbound_var env v = raise (TypeError (env, UnboundVar v)) let error_not_type env j = raise (TypeError (env, NotAType j)) let error_assumption env j = raise (TypeError (env, BadAssumption j)) let error_reference_variables env id = raise (TypeError (env, ReferenceVariables id)) let error_elim_arity env ind aritylst c pj okinds = raise (TypeError (env, ElimArity (ind,aritylst,c,pj,okinds))) let error_case_not_inductive env j = raise (TypeError (env, CaseNotInductive j)) let error_number_branches env cj expn = raise (TypeError (env, NumberBranches (nfj cj,expn))) let error_ill_formed_branch env c i actty expty = raise (TypeError (env, IllFormedBranch (c,i,nf_betaiota actty, nf_betaiota expty))) let error_generalization env nvar c = raise (TypeError (env, Generalization (nvar,c))) let error_actual_type env j expty = raise (TypeError (env, ActualType (j,expty))) let error_cant_apply_not_functional env rator randl = raise (TypeError (env, CantApplyNonFunctional (rator,randl))) let error_cant_apply_bad_type env t rator randl = raise (TypeError (env, CantApplyBadType (t,rator,randl))) let error_ill_formed_rec_body env why lna i fixenv vdefj = raise (TypeError (env, IllFormedRecBody (why,lna,i,fixenv,vdefj))) let error_ill_typed_rec_body env i lna vdefj vargs = raise (TypeError (env, IllTypedRecBody (i,lna,vdefj,vargs))) let error_elim_explain kp ki = match kp,ki with | (InType | InSet), InProp -> NonInformativeToInformative | _ -> WrongArity
92972128040a1dfe5300fcebf9480eccce4834f1902eef46f8e1add5125ce7a2
kazu-yamamoto/http3
Client.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # | A client library for HTTP/0.9 . module Network.HQ.Client ( -- * Runner run -- * Runner arguments , H3.ClientConfig(..) , H3.Config(..) , H3.allocSimpleConfig , H3.freeSimpleConfig , H3.Scheme , H3.Authority -- * HQ client , H2.Client -- * Request , Request -- * Creating request , H2.requestNoBody -- * Response , Response -- ** Accessing response , H2.getResponseBodyChunk ) where import qualified Data.ByteString as BS import Data.IORef import Network.HPACK import qualified Network.HTTP2.Client as H2 import Network.HTTP2.Client.Internal (Request(..), Response(..)) import Network.HTTP2.Internal (InpObj(..)) import qualified Network.HTTP2.Internal as H2 import Network.QUIC (Connection) import qualified Network.QUIC as QUIC import qualified UnliftIO.Exception as E import qualified Network.HTTP3.Client as H3 import Network.HTTP3.Recv (newSource, readSource) -- | Running an HQ client. run :: Connection -> H3.ClientConfig -> H3.Config -> H2.Client a -> IO a run conn _ _ client = client $ sendRequest conn sendRequest :: Connection -> Request -> (Response -> IO a) -> IO a sendRequest conn (Request outobj) processResponse = E.bracket open close $ \strm -> do let hdr = H2.outObjHeaders outobj Just path = lookup ":path" hdr requestLine = BS.concat ["GET ", path, "\r\n"] QUIC.sendStream strm requestLine QUIC.shutdownStream strm src <- newSource strm refH <- newIORef Nothing vt <- toHeaderTable [] let readB = readSource src rsp = Response $ InpObj vt Nothing readB refH processResponse rsp where open = QUIC.stream conn close = QUIC.closeStream
null
https://raw.githubusercontent.com/kazu-yamamoto/http3/5bbd91bd9fe02920d1d9099a686183fc10e731c0/Network/HQ/Client.hs
haskell
# LANGUAGE OverloadedStrings # * Runner * Runner arguments * HQ client * Request * Creating request * Response ** Accessing response | Running an HQ client.
# LANGUAGE RecordWildCards # | A client library for HTTP/0.9 . module Network.HQ.Client ( run , H3.ClientConfig(..) , H3.Config(..) , H3.allocSimpleConfig , H3.freeSimpleConfig , H3.Scheme , H3.Authority , H2.Client , Request , H2.requestNoBody , Response , H2.getResponseBodyChunk ) where import qualified Data.ByteString as BS import Data.IORef import Network.HPACK import qualified Network.HTTP2.Client as H2 import Network.HTTP2.Client.Internal (Request(..), Response(..)) import Network.HTTP2.Internal (InpObj(..)) import qualified Network.HTTP2.Internal as H2 import Network.QUIC (Connection) import qualified Network.QUIC as QUIC import qualified UnliftIO.Exception as E import qualified Network.HTTP3.Client as H3 import Network.HTTP3.Recv (newSource, readSource) run :: Connection -> H3.ClientConfig -> H3.Config -> H2.Client a -> IO a run conn _ _ client = client $ sendRequest conn sendRequest :: Connection -> Request -> (Response -> IO a) -> IO a sendRequest conn (Request outobj) processResponse = E.bracket open close $ \strm -> do let hdr = H2.outObjHeaders outobj Just path = lookup ":path" hdr requestLine = BS.concat ["GET ", path, "\r\n"] QUIC.sendStream strm requestLine QUIC.shutdownStream strm src <- newSource strm refH <- newIORef Nothing vt <- toHeaderTable [] let readB = readSource src rsp = Response $ InpObj vt Nothing readB refH processResponse rsp where open = QUIC.stream conn close = QUIC.closeStream
8405f8395f91d313d85879118d1f8517e7ad1922a618a9f963c7dc5e6aa8bbc0
nklein/grid-generators
cuboid.lisp
(in-package :grid-iterate) (iterate:defmacro-driver (iterate:FOR var ON-GRID-TO to &optional FROM from-var BY by-var) (alexandria:with-gensyms (generator new got) (let ((kwd (if iterate:generate 'iterate:generate 'iterate:for))) `(progn (iterate:with ,generator = (grid-generators:make-grid-generator ,to :from ,from-var :by ,by-var)) (,kwd ,var next (multiple-value-bind (,new ,got) (funcall ,generator) (if ,got ,new (iterate:terminate))))))))
null
https://raw.githubusercontent.com/nklein/grid-generators/5f7b790c339123f84710d907ddafdb52c160d44e/src/iterate/cuboid.lisp
lisp
(in-package :grid-iterate) (iterate:defmacro-driver (iterate:FOR var ON-GRID-TO to &optional FROM from-var BY by-var) (alexandria:with-gensyms (generator new got) (let ((kwd (if iterate:generate 'iterate:generate 'iterate:for))) `(progn (iterate:with ,generator = (grid-generators:make-grid-generator ,to :from ,from-var :by ,by-var)) (,kwd ,var next (multiple-value-bind (,new ,got) (funcall ,generator) (if ,got ,new (iterate:terminate))))))))
d20743d98a2fb391c8d0b330ffa12b72ca1c11cbb2dc455ddaa69202f2a15fe4
CmdrDats/igoki
project.clj
(defproject igoki "0.8.0" :description "Igoki, physical Go board/OGS interface" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.3"] #_[com.google.guava/guava "20.0"] [clj-http "3.12.3"] [seesaw "1.5.0"] [org.openpnp/opencv "4.5.1-2"] [cheshire "5.10.1"] [de.schlichtherle.truezip/truezip-file "7.7.10"] [de.schlichtherle.truezip/truezip-driver-zip "7.7.10"] [io.socket/socket.io-client "0.9.0"] [org.clojure/tools.logging "1.1.0"] [log4j "1.2.17"] [org.slf4j/slf4j-api "1.7.32"] [org.slf4j/jul-to-slf4j "1.7.32"] [org.slf4j/slf4j-log4j12 "1.7.32"] [org.nd4j/nd4j "1.0.0-M1.1" :extension "pom"] [org.nd4j/nd4j-native-platform "1.0.0-M1.1"] [org.deeplearning4j/deeplearning4j-core "1.0.0-M1.1"]] :main igoki.core :repl-options {:welcome "Welcome to igoki" :init-ns igoki.core :init (-main)} #_#_:min-lein-version "2.5.0" :uberjar-name "igoki.jar")
null
https://raw.githubusercontent.com/CmdrDats/igoki/4512602512d77ee8c334eb55351a587a19454b96/project.clj
clojure
(defproject igoki "0.8.0" :description "Igoki, physical Go board/OGS interface" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.3"] #_[com.google.guava/guava "20.0"] [clj-http "3.12.3"] [seesaw "1.5.0"] [org.openpnp/opencv "4.5.1-2"] [cheshire "5.10.1"] [de.schlichtherle.truezip/truezip-file "7.7.10"] [de.schlichtherle.truezip/truezip-driver-zip "7.7.10"] [io.socket/socket.io-client "0.9.0"] [org.clojure/tools.logging "1.1.0"] [log4j "1.2.17"] [org.slf4j/slf4j-api "1.7.32"] [org.slf4j/jul-to-slf4j "1.7.32"] [org.slf4j/slf4j-log4j12 "1.7.32"] [org.nd4j/nd4j "1.0.0-M1.1" :extension "pom"] [org.nd4j/nd4j-native-platform "1.0.0-M1.1"] [org.deeplearning4j/deeplearning4j-core "1.0.0-M1.1"]] :main igoki.core :repl-options {:welcome "Welcome to igoki" :init-ns igoki.core :init (-main)} #_#_:min-lein-version "2.5.0" :uberjar-name "igoki.jar")
26b1391537ad1df3c02ec27d124b66620a813339e6dd290d2f30f85a2bf950c6
hsyl20/haskus-system
Operand.hs
# LANGUAGE LambdaCase # # LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE BinaryLiterals # # LANGUAGE TypeApplications # # LANGUAGE StandaloneDeriving # # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # -- | Operand module Haskus.Arch.X86_64.ISA.Operand ( OperandFam(..) , OperandFamT , OperandFamP , OperandStorage(..) , OperandSpec (..) , OperandSpecP , OperandSpecT , AccessMode (..) , Operand(..) , Addr(..) , SubRegType (..) , MemType (..) , isImmediate , opFamToOp ) where import Haskus.Arch.Common.Solver import Haskus.Arch.Common.Immediate import Haskus.Arch.Common.Register import Haskus.Arch.X86_64.ISA.Solver import Haskus.Arch.X86_64.ISA.Register import Haskus.Arch.X86_64.ISA.Immediate import Haskus.Arch.X86_64.ISA.Memory import Haskus.Utils.Solver import Haskus.Utils.Flow import Haskus.Utils.List (nub) ------------------------------------------------------------------- Operands ------------------------------------------------------------------- -- Note [Operand size] -- ~~~~~~~~~~~~~~~~~~~ -- -- Default operand size(s) -- ----------------------- * In virtual 8086 - mode , real - mode and system management mode : 16 - bit * In protected mode or compatibility mode : 16 - bit or 32 - bit ( a flag is set -- for each segment) * In 64 - bit mode : 32 - bit . Some instructions have 64 - bit default . -- 0x66 prefix -- ----------- -- In protected mode and compatibility mode, the 0x66 prefix can be used to switch to the second default mode . -- -- Instruction specific operand size -- --------------------------------- -- Some instructions have a bit in the operand indicating whether they use the default operand size or a fixed 8 - bit operand size . -- -- W bit -- ----- -- REX/VEX/XOP prefixes have a W flag that indicates whether the operand size is the default one or 64 - bit . The flag is ignored by some instructions . -- Some instructions only use 32- or 64 - bit selected with the W bit ( e.g. ADOX ) . -- -- L bit -- ----- VEX / XOP prefixes have a L flag that indicates the size of the vector register ( XMM or YMM ) . It can be ignored or fixed at a specified value . -- -- Immediate operands -- ------------------ Immediate operands can be of the operand size ( e.g. MOV ) -- More commonly , they are of the operand size * except in 64 - bit * : -- Operand size | 8 | 16 | 32 | 64 Immediate size | 8 | 16 | 32 | 32 ( sign - extended ) -- Or the immediate size can be fixed to 8 - bit and it is sign - extended . -- -- Or the immediate size can be arbitrarily fixed. -- -- Per-operand size -- ---------------- -- Some instructions ( e.g. CRC32 ) have one operand that follows REX.W ( i.e. 32 - bit or 64 - bit ) while the other one follows the default size ( or sizable -- bit in the opcode). -- Note [Operands] -- ~~~~~~~~~~~~~~~ -- -- The ModRM.RM field allows the encoding of either a memory address or a -- register. -- Only a subset of a register may be used ( e.g. the low - order 64 - bits of a XMM -- register). -- | An operand data Operand = OpImm X86Imm -- ^ Immediate value | OpReg X86Reg -- ^ Register | OpMem X86Mem -- ^ Memory address | OpRegPair X86Reg X86Reg -- ^ REG:REG ^ Immediate 16:16 , or 16:8 ( cf ENTER ) deriving (Show,Eq) -- | Operand family data OperandFam t = T_Mem (X86MemFam t) -- ^ Memory address | T_Reg (X86RegFam t) -- ^ Register | T_Imm (X86ImmFam t) -- ^ Immediate value ^ Pair ( AAA : BBB ) of immediates or registers deriving instance (Show (OperandFam T)) deriving instance (Show (OperandFam (NT X86Pred X86Err))) deriving instance (Eq (OperandFam T)) deriving instance (Eq (OperandFam (NT X86Pred X86Err))) deriving instance (Ord (OperandFam T)) deriving instance (Ord (OperandFam (NT X86Pred X86Err))) -- | Predicated operand type type OperandFamP = OperandFam (NT X86Pred X86Err) -- | Terminal operand type type OperandFamT = OperandFam T instance Predicated (OperandFam (NT X86Pred X86Err)) where type Pred (OperandFam (NT X86Pred X86Err)) = X86Pred type PredErr (OperandFam (NT X86Pred X86Err)) = X86Err type PredTerm (OperandFam (NT X86Pred X86Err)) = OperandFam T liftTerminal = \case T_Pair x y -> T_Pair (liftTerminal x) (liftTerminal y) T_Mem x -> T_Mem (liftTerminal x) T_Reg x -> T_Reg (liftTerminal x) T_Imm x -> T_Imm (liftTerminal x) reducePredicates oracle = \case We allow the first element of the pair not to be reducible , in which -- case it's not a pair. We do this to support the family: AX , DX : AX , EDX : RAX , RDX : RAX T_Pair x@(T_Reg {}) y@(T_Reg {}) -> case reducePredicates oracle x of Match _ -> initP T_Pair T_Pair |> (`applyP` reducePredicates oracle x) |> (`applyP` reducePredicates oracle y) |> resultP _ -> reducePredicates oracle y T_Pair x y -> initP T_Pair T_Pair |> (`applyP` reducePredicates oracle x) |> (`applyP` reducePredicates oracle y) |> resultP T_Mem x -> initP T_Mem T_Mem |> (`applyP` reducePredicates oracle x) |> resultP T_Reg x -> initP T_Reg T_Reg |> (`applyP` reducePredicates oracle x) |> resultP T_Imm x -> initP T_Imm T_Imm |> (`applyP` reducePredicates oracle x) |> resultP getTerminals = \case T_Pair xs ys -> [ T_Pair x y | x <- getTerminals xs , y <- getTerminals ys ] T_Mem xs -> [ T_Mem x | x <- getTerminals xs ] T_Reg xs -> [ T_Reg x | x <- getTerminals xs ] T_Imm xs -> [ T_Imm x | x <- getTerminals xs ] getPredicates = \case T_Pair xs ys -> nub $ concat [ getPredicates xs, getPredicates ys ] T_Mem xs -> getPredicates xs T_Reg xs -> getPredicates xs T_Imm xs -> getPredicates xs -- | Operand storage data OperandStorage ^ Operand stored in ModRM.rm ( + ( V)SIB ) | S_Reg -- ^ Operand stored in ModRM.reg | S_Imm -- ^ Operand stored in immediate bytes ^ Operand stored in bits [ 7:4 ] of the immediate byte ^ Operand stored in bits [ 3:0 ] of the immediate byte | S_Implicit -- ^ Implicit ^ Operand stored in Vex.vvvv field ^ Operand stored in opcode 3 last bits deriving (Show,Eq) -- | Operand specification (parameterized) data OperandSpec t = OperandSpec { opMode :: !AccessMode , opFam :: !(Q t (OperandFam t)) , opStore :: !OperandStorage } deriving instance (Show (OperandSpec T)) deriving instance (Show (OperandSpec (NT X86Pred X86Err))) -- | Predicated operand spec type OperandSpecP = OperandSpec (NT X86Pred X86Err) -- | Operand specification type OperandSpecT = OperandSpec T instance Predicated (OperandSpec (NT X86Pred X86Err)) where type Pred (OperandSpec (NT X86Pred X86Err)) = X86Pred type PredErr (OperandSpec (NT X86Pred X86Err)) = X86Err type PredTerm (OperandSpec (NT X86Pred X86Err)) = OperandSpec T liftTerminal (OperandSpec m t s) = OperandSpec m (liftTerminal (liftTerminal t)) s reducePredicates oracle (OperandSpec m t s) = case reducePredicates oracle t of NoMatch -> NoMatch MatchDiverge xs -> MatchDiverge ((\x -> OperandSpec m x s) <$> xs) MatchFail es -> MatchFail es DontMatch a -> DontMatch (OperandSpec m a s) Match a -> case reducePredicates oracle a of NoMatch -> NoMatch MatchDiverge xs -> MatchDiverge ((\x -> OperandSpec m (liftTerminal x) s) <$> xs) MatchFail es -> MatchFail es DontMatch b -> DontMatch (OperandSpec m (liftTerminal b) s) Match b -> Match (OperandSpec m b s) getTerminals (OperandSpec m ts s) = [ OperandSpec m t s | os <- getTerminals ts , t <- getTerminals os ] getPredicates (OperandSpec _ t _) = nub (getPredicates t ++ concatMap getPredicates (getTerminals t)) -- | Operand access mode data AccessMode = RO -- ^ Read-only | RW -- ^ Read-write | WO -- ^ Write-only | NA -- ^ Meta use of the operand deriving (Show,Eq) -- | Is the operand encoding an immediate? isImmediate :: OperandStorage -> Bool isImmediate = \case S_Imm -> True S_Imm8h -> True S_Imm8l -> True _ -> False -- | Convert an operand family into an operand opFamToOp :: OperandFamT -> Maybe Operand opFamToOp op = case op of T_Reg r -> OpReg <$> regFamToReg r T_Mem m -> OpMem <$> x86memFamToMem m T_Imm i -> OpImm <$> immFamToImm i T_Pair x y -> case (x,y) of (T_Reg r1,T_Reg r2) -> OpRegPair <$> regFamToReg r1 <*> regFamToReg r2 (T_Imm i1,T_Imm i2) -> OpImmPair <$> immFamToImm i1 <*> immFamToImm i2 _ -> error ("opFamToOp: invalid pair: " ++ show (x,y))
null
https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/Arch/X86_64/ISA/Operand.hs
haskell
# LANGUAGE DeriveAnyClass # | Operand ----------------------------------------------------------------- ----------------------------------------------------------------- Note [Operand size] ~~~~~~~~~~~~~~~~~~~ Default operand size(s) ----------------------- for each segment) ----------- In protected mode and compatibility mode, the 0x66 prefix can be used to Instruction specific operand size --------------------------------- Some instructions have a bit in the operand indicating whether they use the W bit ----- REX/VEX/XOP prefixes have a W flag that indicates whether the operand size is L bit ----- Immediate operands ------------------ Operand size | 8 | 16 | 32 | 64 Or the immediate size can be arbitrarily fixed. Per-operand size ---------------- bit in the opcode). Note [Operands] ~~~~~~~~~~~~~~~ The ModRM.RM field allows the encoding of either a memory address or a register. register). | An operand ^ Immediate value ^ Register ^ Memory address ^ REG:REG | Operand family ^ Memory address ^ Register ^ Immediate value | Predicated operand type | Terminal operand type case it's not a pair. We do this to support the family: | Operand storage ^ Operand stored in ModRM.reg ^ Operand stored in immediate bytes ^ Implicit | Operand specification (parameterized) | Predicated operand spec | Operand specification | Operand access mode ^ Read-only ^ Read-write ^ Write-only ^ Meta use of the operand | Is the operand encoding an immediate? | Convert an operand family into an operand
# LANGUAGE LambdaCase # # LANGUAGE DataKinds # # LANGUAGE BinaryLiterals # # LANGUAGE TypeApplications # # LANGUAGE StandaloneDeriving # # LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # module Haskus.Arch.X86_64.ISA.Operand ( OperandFam(..) , OperandFamT , OperandFamP , OperandStorage(..) , OperandSpec (..) , OperandSpecP , OperandSpecT , AccessMode (..) , Operand(..) , Addr(..) , SubRegType (..) , MemType (..) , isImmediate , opFamToOp ) where import Haskus.Arch.Common.Solver import Haskus.Arch.Common.Immediate import Haskus.Arch.Common.Register import Haskus.Arch.X86_64.ISA.Solver import Haskus.Arch.X86_64.ISA.Register import Haskus.Arch.X86_64.ISA.Immediate import Haskus.Arch.X86_64.ISA.Memory import Haskus.Utils.Solver import Haskus.Utils.Flow import Haskus.Utils.List (nub) Operands * In virtual 8086 - mode , real - mode and system management mode : 16 - bit * In protected mode or compatibility mode : 16 - bit or 32 - bit ( a flag is set * In 64 - bit mode : 32 - bit . Some instructions have 64 - bit default . 0x66 prefix switch to the second default mode . default operand size or a fixed 8 - bit operand size . the default one or 64 - bit . The flag is ignored by some instructions . Some instructions only use 32- or 64 - bit selected with the W bit ( e.g. ADOX ) . VEX / XOP prefixes have a L flag that indicates the size of the vector register ( XMM or YMM ) . It can be ignored or fixed at a specified value . Immediate operands can be of the operand size ( e.g. MOV ) More commonly , they are of the operand size * except in 64 - bit * : Immediate size | 8 | 16 | 32 | 32 ( sign - extended ) Or the immediate size can be fixed to 8 - bit and it is sign - extended . Some instructions ( e.g. CRC32 ) have one operand that follows REX.W ( i.e. 32 - bit or 64 - bit ) while the other one follows the default size ( or sizable Only a subset of a register may be used ( e.g. the low - order 64 - bits of a XMM data Operand ^ Immediate 16:16 , or 16:8 ( cf ENTER ) deriving (Show,Eq) data OperandFam t ^ Pair ( AAA : BBB ) of immediates or registers deriving instance (Show (OperandFam T)) deriving instance (Show (OperandFam (NT X86Pred X86Err))) deriving instance (Eq (OperandFam T)) deriving instance (Eq (OperandFam (NT X86Pred X86Err))) deriving instance (Ord (OperandFam T)) deriving instance (Ord (OperandFam (NT X86Pred X86Err))) type OperandFamP = OperandFam (NT X86Pred X86Err) type OperandFamT = OperandFam T instance Predicated (OperandFam (NT X86Pred X86Err)) where type Pred (OperandFam (NT X86Pred X86Err)) = X86Pred type PredErr (OperandFam (NT X86Pred X86Err)) = X86Err type PredTerm (OperandFam (NT X86Pred X86Err)) = OperandFam T liftTerminal = \case T_Pair x y -> T_Pair (liftTerminal x) (liftTerminal y) T_Mem x -> T_Mem (liftTerminal x) T_Reg x -> T_Reg (liftTerminal x) T_Imm x -> T_Imm (liftTerminal x) reducePredicates oracle = \case We allow the first element of the pair not to be reducible , in which AX , DX : AX , EDX : RAX , RDX : RAX T_Pair x@(T_Reg {}) y@(T_Reg {}) -> case reducePredicates oracle x of Match _ -> initP T_Pair T_Pair |> (`applyP` reducePredicates oracle x) |> (`applyP` reducePredicates oracle y) |> resultP _ -> reducePredicates oracle y T_Pair x y -> initP T_Pair T_Pair |> (`applyP` reducePredicates oracle x) |> (`applyP` reducePredicates oracle y) |> resultP T_Mem x -> initP T_Mem T_Mem |> (`applyP` reducePredicates oracle x) |> resultP T_Reg x -> initP T_Reg T_Reg |> (`applyP` reducePredicates oracle x) |> resultP T_Imm x -> initP T_Imm T_Imm |> (`applyP` reducePredicates oracle x) |> resultP getTerminals = \case T_Pair xs ys -> [ T_Pair x y | x <- getTerminals xs , y <- getTerminals ys ] T_Mem xs -> [ T_Mem x | x <- getTerminals xs ] T_Reg xs -> [ T_Reg x | x <- getTerminals xs ] T_Imm xs -> [ T_Imm x | x <- getTerminals xs ] getPredicates = \case T_Pair xs ys -> nub $ concat [ getPredicates xs, getPredicates ys ] T_Mem xs -> getPredicates xs T_Reg xs -> getPredicates xs T_Imm xs -> getPredicates xs data OperandStorage ^ Operand stored in ModRM.rm ( + ( V)SIB ) ^ Operand stored in bits [ 7:4 ] of the immediate byte ^ Operand stored in bits [ 3:0 ] of the immediate byte ^ Operand stored in Vex.vvvv field ^ Operand stored in opcode 3 last bits deriving (Show,Eq) data OperandSpec t = OperandSpec { opMode :: !AccessMode , opFam :: !(Q t (OperandFam t)) , opStore :: !OperandStorage } deriving instance (Show (OperandSpec T)) deriving instance (Show (OperandSpec (NT X86Pred X86Err))) type OperandSpecP = OperandSpec (NT X86Pred X86Err) type OperandSpecT = OperandSpec T instance Predicated (OperandSpec (NT X86Pred X86Err)) where type Pred (OperandSpec (NT X86Pred X86Err)) = X86Pred type PredErr (OperandSpec (NT X86Pred X86Err)) = X86Err type PredTerm (OperandSpec (NT X86Pred X86Err)) = OperandSpec T liftTerminal (OperandSpec m t s) = OperandSpec m (liftTerminal (liftTerminal t)) s reducePredicates oracle (OperandSpec m t s) = case reducePredicates oracle t of NoMatch -> NoMatch MatchDiverge xs -> MatchDiverge ((\x -> OperandSpec m x s) <$> xs) MatchFail es -> MatchFail es DontMatch a -> DontMatch (OperandSpec m a s) Match a -> case reducePredicates oracle a of NoMatch -> NoMatch MatchDiverge xs -> MatchDiverge ((\x -> OperandSpec m (liftTerminal x) s) <$> xs) MatchFail es -> MatchFail es DontMatch b -> DontMatch (OperandSpec m (liftTerminal b) s) Match b -> Match (OperandSpec m b s) getTerminals (OperandSpec m ts s) = [ OperandSpec m t s | os <- getTerminals ts , t <- getTerminals os ] getPredicates (OperandSpec _ t _) = nub (getPredicates t ++ concatMap getPredicates (getTerminals t)) data AccessMode deriving (Show,Eq) isImmediate :: OperandStorage -> Bool isImmediate = \case S_Imm -> True S_Imm8h -> True S_Imm8l -> True _ -> False opFamToOp :: OperandFamT -> Maybe Operand opFamToOp op = case op of T_Reg r -> OpReg <$> regFamToReg r T_Mem m -> OpMem <$> x86memFamToMem m T_Imm i -> OpImm <$> immFamToImm i T_Pair x y -> case (x,y) of (T_Reg r1,T_Reg r2) -> OpRegPair <$> regFamToReg r1 <*> regFamToReg r2 (T_Imm i1,T_Imm i2) -> OpImmPair <$> immFamToImm i1 <*> immFamToImm i2 _ -> error ("opFamToOp: invalid pair: " ++ show (x,y))
7a6b262cd5cf40b1931e4c89f91400d73e609c703d30e6849a703b1bba77b729
janestreet/learn-ocaml-workshop
board.ml
open Base type t = { board : Filled_square.t option array array ; height : int ; width : int } let create ~height ~width = { board = Array.make_matrix ~dimx:width ~dimy:height None; height; width } ;; let get t { Point.col; row } = t.board.(col).(row) let set t { Point.col; row } value = t.board.(col).(row) <- value let mark_squares_that_are_sweepable t = TODO : at the end of this function , all filled_squares that are part of completed squares ( i.e. four tiles in a square arrangement that are all of the same colors ) should be in sweeper state [ To_sweep ] , and all other squares should be [ Unmarked ] . Note that , for example , a 2x3 rectangle of all the same color should also be marked by these criteria . completed squares (i.e. four tiles in a square arrangement that are all of the same colors) should be in sweeper state [To_sweep], and all other squares should be [Unmarked]. Note that, for example, a 2x3 rectangle of all the same color should also be marked by these criteria. *) List.iter (List.range 0 t.width) ~f:(fun col -> List.iter (List.range 0 t.height) ~f:(fun row -> match get t { col; row } with | None -> () | Some filled_square -> Filled_square.unmark filled_square)); List.iter (List.range 0 (t.width - 1)) ~f:(fun col -> List.iter (List.range 0 (t.height - 1)) ~f:(fun row -> let coords = Moving_piece.coords ~bottom_left:{ Point.row; col } in let colors = List.map coords ~f:(get t) |> List.fold ~init:[] ~f:(fun acc t -> match t with | None -> None :: acc | Some t -> let color = Some t.Filled_square.color in (match acc with | [] -> [ color ] | [ c ] -> if Option.equal Color.equal color c then acc else color :: acc | _ -> acc)) in match colors with | [ Some _ ] -> List.iter coords ~f:(fun point -> match get t point with | None -> () | Some filled_square -> Filled_square.to_sweep filled_square) | _ -> ())) ;; let remove_squares t = (* TODO: remove any squares marked as [Swept] from the board. Gravity should be applied appropriately. This is the function that is called by the [Sweeper.t] to clear squares from the board. At the end of this function, we should call [mark_squares_that_are_sweepable] so that we ensure that we leave the board in a valid state. *) let squares_to_remove = List.fold (List.range 0 t.width) ~init:[] ~f:(fun acc col -> List.fold (List.range 0 t.height) ~init:acc ~f:(fun acc row -> let point = { Point.col; row } in match get t point with | Some filled_square -> if Filled_square.Sweeper_state.equal filled_square.sweeper_state Swept then point :: acc else acc | _ -> acc)) |> List.sort ~compare:(fun p1 p2 -> Point.compare_by_row p2 p1) in List.iter squares_to_remove ~f:(fun { Point.col; row } -> List.iter (List.range row (t.height - 1)) ~f:(fun row1 -> set t { Point.row = row1; col } (get t { Point.row = row1 + 1; col })); set t { Point.row = t.height - 1; col } None); mark_squares_that_are_sweepable t ;; let add_piece_and_apply_gravity t ~moving_piece ~col = (* TODO: insert (affix) the moving piece into the board, applying gravity appropriately. Make sure to leave the board in a valid state. *) let find_row ~col = List.find (List.range 0 t.height) ~f:(fun i -> match get t { Point.row = i; col } with | None -> true | Some _ -> false) in let left_row = find_row ~col in let right_row = find_row ~col:(col + 1) in match left_row, right_row with | None, _ | _, None -> false | Some left_row, Some right_row -> if left_row < t.height - 1 && right_row < t.height - 1 then ( set t { row = left_row; col } (Some moving_piece.Moving_piece.bottom_left); set t { row = left_row + 1; col } (Some moving_piece.Moving_piece.top_left); set t { row = right_row; col = col + 1 } (Some moving_piece.Moving_piece.bottom_right); set t { row = right_row + 1; col = col + 1 } (Some moving_piece.Moving_piece.top_right); mark_squares_that_are_sweepable t; true) else false ;; let is_empty t point = match get t point with | None -> true | Some _ -> false ;; (* Tests *) let is_filled_with_color t ~row ~col color = match get t { Point.row; col } with | None -> false | Some square -> Color.equal color square.color ;; let is_marked t ~row ~col = match get t { Point.row; col } with | None -> false | Some square -> Filled_square.Sweeper_state.equal square.Filled_square.sweeper_state Filled_square.Sweeper_state.To_sweep ;; let test_piece = { Moving_piece.top_left = Filled_square.create Color.Orange ; top_right = Filled_square.create Color.White ; bottom_left = Filled_square.create Color.White ; bottom_right = Filled_square.create Color.White } ;; let%test "Testing add_piece_and_apply_gravity add one..." = let t = create ~height:4 ~width:4 in add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && is_filled_with_color t ~row:0 ~col:0 Color.White && is_filled_with_color t ~row:0 ~col:1 Color.White && is_filled_with_color t ~row:1 ~col:0 Color.Orange && is_filled_with_color t ~row:1 ~col:1 Color.White ;; let%test "Testing add_piece_and_apply_gravity add many..." = let t = create ~height:4 ~width:4 in add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && not (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0) ;; let test_removable_piece = { Moving_piece.top_left = Filled_square.create Color.White ; top_right = Filled_square.create Color.White ; bottom_left = Filled_square.create Color.White ; bottom_right = Filled_square.create Color.White } ;; let%test "Testing mark_squares_that_are_sweepable..." = let t = create ~height:4 ~width:4 in assert (add_piece_and_apply_gravity t ~moving_piece:test_removable_piece ~col:0); assert (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0); mark_squares_that_are_sweepable t; is_marked t ~row:0 ~col:0 && is_marked t ~row:0 ~col:1 && is_marked t ~row:1 ~col:0 && is_marked t ~row:1 ~col:1 && is_marked t ~row:2 ~col:0 && is_marked t ~row:2 ~col:1 && (not (is_marked t ~row:3 ~col:0)) && not (is_marked t ~row:3 ~col:1) ;; let sweep_board t = Array.iter t.board ~f:(fun row -> Array.iter row ~f:(fun square -> Option.iter square ~f:(fun square -> ignore (Filled_square.sweep square)))) ;; let%test "Testing Remove_squares..." = let t = create ~height:4 ~width:4 in assert (add_piece_and_apply_gravity t ~moving_piece:test_removable_piece ~col:0); assert (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0); mark_squares_that_are_sweepable t; sweep_board t; remove_squares t; is_filled_with_color t ~row:0 ~col:0 Color.Orange && is_filled_with_color t ~row:0 ~col:1 Color.White ;;
null
https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/solutions/lumines/board.ml
ocaml
TODO: remove any squares marked as [Swept] from the board. Gravity should be applied appropriately. This is the function that is called by the [Sweeper.t] to clear squares from the board. At the end of this function, we should call [mark_squares_that_are_sweepable] so that we ensure that we leave the board in a valid state. TODO: insert (affix) the moving piece into the board, applying gravity appropriately. Make sure to leave the board in a valid state. Tests
open Base type t = { board : Filled_square.t option array array ; height : int ; width : int } let create ~height ~width = { board = Array.make_matrix ~dimx:width ~dimy:height None; height; width } ;; let get t { Point.col; row } = t.board.(col).(row) let set t { Point.col; row } value = t.board.(col).(row) <- value let mark_squares_that_are_sweepable t = TODO : at the end of this function , all filled_squares that are part of completed squares ( i.e. four tiles in a square arrangement that are all of the same colors ) should be in sweeper state [ To_sweep ] , and all other squares should be [ Unmarked ] . Note that , for example , a 2x3 rectangle of all the same color should also be marked by these criteria . completed squares (i.e. four tiles in a square arrangement that are all of the same colors) should be in sweeper state [To_sweep], and all other squares should be [Unmarked]. Note that, for example, a 2x3 rectangle of all the same color should also be marked by these criteria. *) List.iter (List.range 0 t.width) ~f:(fun col -> List.iter (List.range 0 t.height) ~f:(fun row -> match get t { col; row } with | None -> () | Some filled_square -> Filled_square.unmark filled_square)); List.iter (List.range 0 (t.width - 1)) ~f:(fun col -> List.iter (List.range 0 (t.height - 1)) ~f:(fun row -> let coords = Moving_piece.coords ~bottom_left:{ Point.row; col } in let colors = List.map coords ~f:(get t) |> List.fold ~init:[] ~f:(fun acc t -> match t with | None -> None :: acc | Some t -> let color = Some t.Filled_square.color in (match acc with | [] -> [ color ] | [ c ] -> if Option.equal Color.equal color c then acc else color :: acc | _ -> acc)) in match colors with | [ Some _ ] -> List.iter coords ~f:(fun point -> match get t point with | None -> () | Some filled_square -> Filled_square.to_sweep filled_square) | _ -> ())) ;; let remove_squares t = let squares_to_remove = List.fold (List.range 0 t.width) ~init:[] ~f:(fun acc col -> List.fold (List.range 0 t.height) ~init:acc ~f:(fun acc row -> let point = { Point.col; row } in match get t point with | Some filled_square -> if Filled_square.Sweeper_state.equal filled_square.sweeper_state Swept then point :: acc else acc | _ -> acc)) |> List.sort ~compare:(fun p1 p2 -> Point.compare_by_row p2 p1) in List.iter squares_to_remove ~f:(fun { Point.col; row } -> List.iter (List.range row (t.height - 1)) ~f:(fun row1 -> set t { Point.row = row1; col } (get t { Point.row = row1 + 1; col })); set t { Point.row = t.height - 1; col } None); mark_squares_that_are_sweepable t ;; let add_piece_and_apply_gravity t ~moving_piece ~col = let find_row ~col = List.find (List.range 0 t.height) ~f:(fun i -> match get t { Point.row = i; col } with | None -> true | Some _ -> false) in let left_row = find_row ~col in let right_row = find_row ~col:(col + 1) in match left_row, right_row with | None, _ | _, None -> false | Some left_row, Some right_row -> if left_row < t.height - 1 && right_row < t.height - 1 then ( set t { row = left_row; col } (Some moving_piece.Moving_piece.bottom_left); set t { row = left_row + 1; col } (Some moving_piece.Moving_piece.top_left); set t { row = right_row; col = col + 1 } (Some moving_piece.Moving_piece.bottom_right); set t { row = right_row + 1; col = col + 1 } (Some moving_piece.Moving_piece.top_right); mark_squares_that_are_sweepable t; true) else false ;; let is_empty t point = match get t point with | None -> true | Some _ -> false ;; let is_filled_with_color t ~row ~col color = match get t { Point.row; col } with | None -> false | Some square -> Color.equal color square.color ;; let is_marked t ~row ~col = match get t { Point.row; col } with | None -> false | Some square -> Filled_square.Sweeper_state.equal square.Filled_square.sweeper_state Filled_square.Sweeper_state.To_sweep ;; let test_piece = { Moving_piece.top_left = Filled_square.create Color.Orange ; top_right = Filled_square.create Color.White ; bottom_left = Filled_square.create Color.White ; bottom_right = Filled_square.create Color.White } ;; let%test "Testing add_piece_and_apply_gravity add one..." = let t = create ~height:4 ~width:4 in add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && is_filled_with_color t ~row:0 ~col:0 Color.White && is_filled_with_color t ~row:0 ~col:1 Color.White && is_filled_with_color t ~row:1 ~col:0 Color.Orange && is_filled_with_color t ~row:1 ~col:1 Color.White ;; let%test "Testing add_piece_and_apply_gravity add many..." = let t = create ~height:4 ~width:4 in add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0 && not (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0) ;; let test_removable_piece = { Moving_piece.top_left = Filled_square.create Color.White ; top_right = Filled_square.create Color.White ; bottom_left = Filled_square.create Color.White ; bottom_right = Filled_square.create Color.White } ;; let%test "Testing mark_squares_that_are_sweepable..." = let t = create ~height:4 ~width:4 in assert (add_piece_and_apply_gravity t ~moving_piece:test_removable_piece ~col:0); assert (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0); mark_squares_that_are_sweepable t; is_marked t ~row:0 ~col:0 && is_marked t ~row:0 ~col:1 && is_marked t ~row:1 ~col:0 && is_marked t ~row:1 ~col:1 && is_marked t ~row:2 ~col:0 && is_marked t ~row:2 ~col:1 && (not (is_marked t ~row:3 ~col:0)) && not (is_marked t ~row:3 ~col:1) ;; let sweep_board t = Array.iter t.board ~f:(fun row -> Array.iter row ~f:(fun square -> Option.iter square ~f:(fun square -> ignore (Filled_square.sweep square)))) ;; let%test "Testing Remove_squares..." = let t = create ~height:4 ~width:4 in assert (add_piece_and_apply_gravity t ~moving_piece:test_removable_piece ~col:0); assert (add_piece_and_apply_gravity t ~moving_piece:test_piece ~col:0); mark_squares_that_are_sweepable t; sweep_board t; remove_squares t; is_filled_with_color t ~row:0 ~col:0 Color.Orange && is_filled_with_color t ~row:0 ~col:1 Color.White ;;
4aa2db72bb8410f9d4ded23573109e86013c4d00180edd1174d7af6e856beb56
clojure-lsp/clojure-lsp
handlers_test.clj
(ns clojure-lsp.handlers-test (:require [clojure-lsp.handlers :as handlers] [clojure-lsp.kondo :as lsp.kondo] [clojure-lsp.test-helper :as h] [clojure.core.async :as async] [clojure.test :refer [deftest is testing]])) (h/reset-components-before-test) (deftest initialize (testing "detects URI format with lower-case drive letter and encoded colons" (h/reset-components!) (with-redefs [lsp.kondo/config-hash (constantly "123")] (handlers/initialize (h/components) "file" {} {} nil)) (is (= {:encode-colons-in-path? true :upper-case-drive-letter? false} (get-in (h/db) [:settings :uri-format])))) (testing "detects URI format with upper-case drive letter and non-encoded colons" (h/reset-components!) (with-redefs [lsp.kondo/config-hash (constantly "123")] (handlers/initialize (h/components) "file:/project/root" {} {} nil)) (is (= {:encode-colons-in-path? false :upper-case-drive-letter? true} (get-in (h/db) [:settings :uri-format]))))) (deftest did-open (testing "opening a existing file" (h/reset-components!) (let [mock-diagnostics-chan (async/chan 1)] (h/load-code-and-locs "(ns a) (when)" h/default-uri (assoc (h/components) :diagnostics-chan mock-diagnostics-chan)) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")]))) (let [{:keys [uri diagnostics]} (h/take-or-timeout mock-diagnostics-chan 500)] (is (= (h/file-uri "file") uri)) (h/assert-submaps [{:code "missing-body-in-when"} {:code "invalid-arity"}] diagnostics)))) (testing "opening a new clojure file adding the ns" (h/reset-components!) (swap! (h/db*) merge {:settings {:auto-add-ns-to-new-files? true :source-paths #{(h/file-path "/project/src")}} :client-capabilities {:workspace {:workspace-edit {:document-changes true}}} :project-root-uri (h/file-uri "file")}) (let [mock-edits-chan (async/chan 1)] (h/load-code-and-locs "" (h/file-uri "file") (assoc (h/components) :edits-chan mock-edits-chan)) (h/assert-submaps [{:edits [{:range {:start {:line 0, :character 0} :end {:line 999998, :character 999998}} :new-text "(ns foo.bar)"}]}] (:document-changes (h/take-or-timeout mock-edits-chan 500))) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")]))))) (testing "opening a new edn file not adding the ns" (h/reset-components!) (swap! (h/db*) merge {:settings {:auto-add-ns-to-new-files? true :source-paths #{(h/file-path "/project/src")}} :client-capabilities {:workspace {:workspace-edit {:document-changes true}}} :project-root-uri (h/file-uri "file")}) (let [mock-edits-chan (async/chan 1)] (h/load-code-and-locs "" (h/file-uri "file") (assoc (h/components) :edits-chan mock-edits-chan)) (h/assert-no-take mock-edits-chan 500) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")])))))) (deftest document-symbol (let [code "(ns a) (def bar ::bar) (def ^:m baz 1) (defmulti mult identity) (defmethod mult \"foo\")" result #{{:name "a" :kind :namespace :range {:start {:line 0 :character 0} :end {:line 999999 :character 999999}} :selection-range {:start {:line 0 :character 0} :end {:line 0 :character 6}} :children [{:name "bar" :kind :variable :range {:start {:line 0 :character 7} :end {:line 0 :character 22}} :selection-range {:start {:line 0 :character 12} :end {:line 0 :character 15}} :tags []} {:name "baz" :kind :variable :range {:start {:line 0 :character 23} :end {:line 0 :character 38}} :selection-range {:start {:line 0 :character 32} :end {:line 0 :character 35}} :tags []} ;; defmulti {:name "mult", :kind :interface, :range {:start {:line 0, :character 39}, :end {:line 0, :character 63}}, :selection-range {:start {:line 0, :character 49}, :end {:line 0, :character 53}} :tags []} ;; defmethod {:name "mult \"foo\"", :kind :function, :range {:start {:line 0, :character 75}, :end {:line 0, :character 79}}, :selection-range {:start {:line 0, :character 75}, :end {:line 0, :character 79}} :tags []}]}}] (testing "clj files" (h/load-code-and-locs code) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))) (testing "cljs files" (h/load-code-and-locs code (h/file-uri "file")) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))) (testing "cljc files" (h/load-code-and-locs code (h/file-uri "file")) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))))) (deftest document-highlight (let [[bar-start] (h/load-code-and-locs "(ns a) (def |bar ::bar) (def ^:m baz 1)")] (h/assert-submaps [{:range {:start {:line 0 :character 12} :end {:line 0 :character 15}}}] (handlers/document-highlight (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-start)})))) (deftest references (testing "simple single reference" (let [[bar-def-pos] (h/load-code-and-locs "(ns a) (def |bar 1)") _ (h/load-code-and-locs "(ns b (:require [a :as foo])) (foo/bar)" (h/file-uri "file"))] (h/assert-submaps [{:uri (h/file-uri "file") :range {:start {:line 0 :character 31} :end {:line 0 :character 38}}}] (handlers/references (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-def-pos)})))) (testing "when including declaration" (let [[bar-def-pos] (h/load-code-and-locs "(ns a) (def |bar 1)") _ (h/load-code-and-locs "(ns b (:require [a :as foo])) (foo/bar)" (h/file-uri "file"))] (h/assert-submaps #{{:uri (h/file-uri "file") :range {:start {:line 0 :character 12} :end {:line 0 :character 15}}} {:uri (h/file-uri "file") :range {:start {:line 0 :character 31} :end {:line 0 :character 38}}}} (handlers/references (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-def-pos) :context {:include-declaration true}}))))) (deftest test-rename (let [[abar-start abar-stop akw-start akwbar-start akwbar-stop abaz-start abaz-stop] (h/load-code-and-locs (h/code "(ns a.aa)" "(def |bar| |::|bar|)" "(def ^:m |baz| 1)") (h/file-uri "file")) [balias-start balias-stop ba1-start _ba1-stop bbar-start bbar-stop ba2-kw-start ba2-kw-stop] (h/load-code-and-locs (h/code "(ns b.bb (:require [a.aa :as |aa|]))" "(def x |aa|/|bar|)" "|::aa/bar|" ":aa/bar") (h/file-uri "file")) [cbar-start cbar-stop cbaz-start cbaz-stop] (h/load-code-and-locs (h/code "(ns c.cc (:require [a.aa :as aa]))" "(def x aa/|bar|)" "^:xab aa/|baz|") (h/file-uri "file")) [d-name-kw-start d-name-kw-stop] (h/load-code-and-locs (h/code "(ns d.dd)" "(def name |::name|)") (h/file-uri "file")) [kw-aliased-start kw-aliased-stop kw-unaliased-start kw-unaliased-stop] (h/load-code-and-locs (h/code "(ns e.ee (:require [d.dd :as dd]))" "(def name |::dd/name|)" "(def other-name |:d.dd/name|)") (h/file-uri "file")) [main-uname-kw-start main-uname-kw-end] (h/load-code-and-locs (h/code "(ns main (:require [user :as u]))" "(def name |::u/name|)") (h/file-uri "file")) [uname-kw-start uname-kw-end] (h/load-code-and-locs (h/code "(ns user)" "(def name |::name|)") (h/file-uri "file"))] (testing "on symbol without namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position abar-start) :new-name "foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range bbar-start bbar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on symbol with metadata namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position abaz-start) :new-name "qux"}))] (is (= {(h/file-uri "file") [{:new-text "qux" :range (h/->range abaz-start abaz-stop)}] (h/file-uri "file") [{:new-text "qux" :range (h/->range cbaz-start cbaz-stop)}]} changes)))) (testing "on symbol with namespace adds existing namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position [(first bbar-start) (dec (second bbar-start))]) :new-name "foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range bbar-start bbar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on symbol with namespace removes passed-in namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bbar-start) :new-name "aa/foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "aa/foo" :range (h/->range ba1-start bbar-stop)} {:new-text "aa" :range (h/->range balias-start balias-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on ::keyword" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position akwbar-start) :new-name "::foo"}))] (is (= {(h/file-uri "file") [{:new-text "::foo" :range (h/->range akw-start akwbar-stop)}] (h/file-uri "file") [{:new-text "::aa/foo" :range (h/->range ba2-kw-start ba2-kw-stop)}]} changes)))) (testing "on single-name-namespace'd keyword" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position main-uname-kw-start) :new-name "::full-name"}))] (is (= {(h/file-uri "file") [{:new-text "::u/full-name" :range (h/->range main-uname-kw-start main-uname-kw-end)}] (h/file-uri "file") [{:new-text "::full-name" :range (h/->range uname-kw-start uname-kw-end)}]} changes)))) (testing "on qualified keyword without alias" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position d-name-kw-start) :new-name "::other-name"}))] (is (= {(h/file-uri "file") [{:new-text "::other-name" :range (h/->range d-name-kw-start d-name-kw-stop)}] (h/file-uri "file") [{:new-text "::dd/other-name" :range (h/->range kw-aliased-start kw-aliased-stop)} {:new-text ":d.dd/other-name" :range (h/->range kw-unaliased-start kw-unaliased-stop)}]} changes)))) (testing "on alias changes namespaces inside file" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position balias-start) :new-name "xx"}))] (is (= {(h/file-uri "file") [{:range (h/->range balias-start balias-stop) :new-text "xx"} {:range (h/->range ba2-kw-start ba2-kw-stop) :new-text "::xx/bar"} {:range (h/->range ba1-start bbar-stop) :new-text "xx/bar"}]} changes)))))) (deftest test-code-actions-handle (h/load-code-and-locs (str "(ns some-ns)\n" "(def foo)") (h/file-uri "file")) (h/load-code-and-locs (str "(ns other-ns (:require [some-ns :as sns]))\n" "(def bar 1)\n" "(defn baz []\n" " bar)") (h/file-uri "file")) (h/load-code-and-locs (str "(ns another-ns)\n" "(def bar ons/bar)\n" "(def foo sns/foo)\n" "(deftest some-test)\n" "MyClass.\n" "Date.") (h/file-uri "file")) (testing "when it has unresolved-namespace and can find namespace" (is (some #(= (:title %) "Add require '[some-ns :as sns]' × 1") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics [{:code "unresolved-namespace" :range {:start {:line 2 :character 10}}}]} :range {:start {:line 2 :character 10}}})))) (testing "without workspace edit client capability" (swap! (h/db*) merge {:client-capabilities {:workspace {:workspace-edit false}}}) (is (not-any? #(= (:title %) "Clean namespace") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics []} :range {:start {:line 1 :character 1}}})))) (testing "with workspace edit client capability" (swap! (h/db*) merge {:client-capabilities {:workspace {:workspace-edit true}}}) (is (some #(= (:title %) "Clean namespace") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics []} :range {:start {:line 1 :character 1}}}))))) (deftest code-lens-can-be-resolved (h/load-code-and-locs (str "(ns some-ns)\n" "(def foo 1)\n" "(defn- foo2 []\n" " foo)\n" "(defn bar [a b]\n" " (+ a b (foo2)))\n" "(s/defn baz []\n" " (bar 2 3))\n")) (let [code-lenses (handlers/code-lens (h/components) {:text-document {:uri h/default-uri}}) resolved-code-lenses (map (fn [code-lens] (handlers/code-lens-resolve (h/components) code-lens)) code-lenses)] (is (= [0 1 2 4] (map #(get-in % [:range :start :line]) resolved-code-lenses))) (is (= ["0 references" "1 reference" "1 reference" "1 reference"] (map #(get-in % [:command :title]) resolved-code-lenses))))) (deftest server-info-raw (testing "returns kebab-case strings, to avoid camelCase conversion of keywords" (is (seq (get (handlers/server-info-raw (h/components)) "server-version"))))) (deftest cursor-info-raw (testing "returns kebab-case strings, to avoid camelCase conversion of keywords" (let [[row-and-col] (h/load-code-and-locs "(ns |a)")] (is (seq (get (handlers/cursor-info-raw (h/components) {:text-document {:uri h/default-uri} :position (h/->position row-and-col)}) "elements"))))))
null
https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/374928dbcdd138c68943a835aaf639a8c1ef2002/lib/test/clojure_lsp/handlers_test.clj
clojure
defmulti defmethod
(ns clojure-lsp.handlers-test (:require [clojure-lsp.handlers :as handlers] [clojure-lsp.kondo :as lsp.kondo] [clojure-lsp.test-helper :as h] [clojure.core.async :as async] [clojure.test :refer [deftest is testing]])) (h/reset-components-before-test) (deftest initialize (testing "detects URI format with lower-case drive letter and encoded colons" (h/reset-components!) (with-redefs [lsp.kondo/config-hash (constantly "123")] (handlers/initialize (h/components) "file" {} {} nil)) (is (= {:encode-colons-in-path? true :upper-case-drive-letter? false} (get-in (h/db) [:settings :uri-format])))) (testing "detects URI format with upper-case drive letter and non-encoded colons" (h/reset-components!) (with-redefs [lsp.kondo/config-hash (constantly "123")] (handlers/initialize (h/components) "file:/project/root" {} {} nil)) (is (= {:encode-colons-in-path? false :upper-case-drive-letter? true} (get-in (h/db) [:settings :uri-format]))))) (deftest did-open (testing "opening a existing file" (h/reset-components!) (let [mock-diagnostics-chan (async/chan 1)] (h/load-code-and-locs "(ns a) (when)" h/default-uri (assoc (h/components) :diagnostics-chan mock-diagnostics-chan)) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")]))) (let [{:keys [uri diagnostics]} (h/take-or-timeout mock-diagnostics-chan 500)] (is (= (h/file-uri "file") uri)) (h/assert-submaps [{:code "missing-body-in-when"} {:code "invalid-arity"}] diagnostics)))) (testing "opening a new clojure file adding the ns" (h/reset-components!) (swap! (h/db*) merge {:settings {:auto-add-ns-to-new-files? true :source-paths #{(h/file-path "/project/src")}} :client-capabilities {:workspace {:workspace-edit {:document-changes true}}} :project-root-uri (h/file-uri "file")}) (let [mock-edits-chan (async/chan 1)] (h/load-code-and-locs "" (h/file-uri "file") (assoc (h/components) :edits-chan mock-edits-chan)) (h/assert-submaps [{:edits [{:range {:start {:line 0, :character 0} :end {:line 999998, :character 999998}} :new-text "(ns foo.bar)"}]}] (:document-changes (h/take-or-timeout mock-edits-chan 500))) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")]))))) (testing "opening a new edn file not adding the ns" (h/reset-components!) (swap! (h/db*) merge {:settings {:auto-add-ns-to-new-files? true :source-paths #{(h/file-path "/project/src")}} :client-capabilities {:workspace {:workspace-edit {:document-changes true}}} :project-root-uri (h/file-uri "file")}) (let [mock-edits-chan (async/chan 1)] (h/load-code-and-locs "" (h/file-uri "file") (assoc (h/components) :edits-chan mock-edits-chan)) (h/assert-no-take mock-edits-chan 500) (is (some? (get-in (h/db) [:analysis (h/file-uri "file")])))))) (deftest document-symbol (let [code "(ns a) (def bar ::bar) (def ^:m baz 1) (defmulti mult identity) (defmethod mult \"foo\")" result #{{:name "a" :kind :namespace :range {:start {:line 0 :character 0} :end {:line 999999 :character 999999}} :selection-range {:start {:line 0 :character 0} :end {:line 0 :character 6}} :children [{:name "bar" :kind :variable :range {:start {:line 0 :character 7} :end {:line 0 :character 22}} :selection-range {:start {:line 0 :character 12} :end {:line 0 :character 15}} :tags []} {:name "baz" :kind :variable :range {:start {:line 0 :character 23} :end {:line 0 :character 38}} :selection-range {:start {:line 0 :character 32} :end {:line 0 :character 35}} :tags []} {:name "mult", :kind :interface, :range {:start {:line 0, :character 39}, :end {:line 0, :character 63}}, :selection-range {:start {:line 0, :character 49}, :end {:line 0, :character 53}} :tags []} {:name "mult \"foo\"", :kind :function, :range {:start {:line 0, :character 75}, :end {:line 0, :character 79}}, :selection-range {:start {:line 0, :character 75}, :end {:line 0, :character 79}} :tags []}]}}] (testing "clj files" (h/load-code-and-locs code) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))) (testing "cljs files" (h/load-code-and-locs code (h/file-uri "file")) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))) (testing "cljc files" (h/load-code-and-locs code (h/file-uri "file")) (h/assert-submaps result (handlers/document-symbol (h/components) {:text-document {:uri (h/file-uri "file")}}))))) (deftest document-highlight (let [[bar-start] (h/load-code-and-locs "(ns a) (def |bar ::bar) (def ^:m baz 1)")] (h/assert-submaps [{:range {:start {:line 0 :character 12} :end {:line 0 :character 15}}}] (handlers/document-highlight (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-start)})))) (deftest references (testing "simple single reference" (let [[bar-def-pos] (h/load-code-and-locs "(ns a) (def |bar 1)") _ (h/load-code-and-locs "(ns b (:require [a :as foo])) (foo/bar)" (h/file-uri "file"))] (h/assert-submaps [{:uri (h/file-uri "file") :range {:start {:line 0 :character 31} :end {:line 0 :character 38}}}] (handlers/references (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-def-pos)})))) (testing "when including declaration" (let [[bar-def-pos] (h/load-code-and-locs "(ns a) (def |bar 1)") _ (h/load-code-and-locs "(ns b (:require [a :as foo])) (foo/bar)" (h/file-uri "file"))] (h/assert-submaps #{{:uri (h/file-uri "file") :range {:start {:line 0 :character 12} :end {:line 0 :character 15}}} {:uri (h/file-uri "file") :range {:start {:line 0 :character 31} :end {:line 0 :character 38}}}} (handlers/references (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bar-def-pos) :context {:include-declaration true}}))))) (deftest test-rename (let [[abar-start abar-stop akw-start akwbar-start akwbar-stop abaz-start abaz-stop] (h/load-code-and-locs (h/code "(ns a.aa)" "(def |bar| |::|bar|)" "(def ^:m |baz| 1)") (h/file-uri "file")) [balias-start balias-stop ba1-start _ba1-stop bbar-start bbar-stop ba2-kw-start ba2-kw-stop] (h/load-code-and-locs (h/code "(ns b.bb (:require [a.aa :as |aa|]))" "(def x |aa|/|bar|)" "|::aa/bar|" ":aa/bar") (h/file-uri "file")) [cbar-start cbar-stop cbaz-start cbaz-stop] (h/load-code-and-locs (h/code "(ns c.cc (:require [a.aa :as aa]))" "(def x aa/|bar|)" "^:xab aa/|baz|") (h/file-uri "file")) [d-name-kw-start d-name-kw-stop] (h/load-code-and-locs (h/code "(ns d.dd)" "(def name |::name|)") (h/file-uri "file")) [kw-aliased-start kw-aliased-stop kw-unaliased-start kw-unaliased-stop] (h/load-code-and-locs (h/code "(ns e.ee (:require [d.dd :as dd]))" "(def name |::dd/name|)" "(def other-name |:d.dd/name|)") (h/file-uri "file")) [main-uname-kw-start main-uname-kw-end] (h/load-code-and-locs (h/code "(ns main (:require [user :as u]))" "(def name |::u/name|)") (h/file-uri "file")) [uname-kw-start uname-kw-end] (h/load-code-and-locs (h/code "(ns user)" "(def name |::name|)") (h/file-uri "file"))] (testing "on symbol without namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position abar-start) :new-name "foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range bbar-start bbar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on symbol with metadata namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position abaz-start) :new-name "qux"}))] (is (= {(h/file-uri "file") [{:new-text "qux" :range (h/->range abaz-start abaz-stop)}] (h/file-uri "file") [{:new-text "qux" :range (h/->range cbaz-start cbaz-stop)}]} changes)))) (testing "on symbol with namespace adds existing namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position [(first bbar-start) (dec (second bbar-start))]) :new-name "foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range bbar-start bbar-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on symbol with namespace removes passed-in namespace" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position bbar-start) :new-name "aa/foo"}))] (is (= {(h/file-uri "file") [{:new-text "foo" :range (h/->range abar-start abar-stop)}] (h/file-uri "file") [{:new-text "aa/foo" :range (h/->range ba1-start bbar-stop)} {:new-text "aa" :range (h/->range balias-start balias-stop)}] (h/file-uri "file") [{:new-text "foo" :range (h/->range cbar-start cbar-stop)}]} changes)))) (testing "on ::keyword" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position akwbar-start) :new-name "::foo"}))] (is (= {(h/file-uri "file") [{:new-text "::foo" :range (h/->range akw-start akwbar-stop)}] (h/file-uri "file") [{:new-text "::aa/foo" :range (h/->range ba2-kw-start ba2-kw-stop)}]} changes)))) (testing "on single-name-namespace'd keyword" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position main-uname-kw-start) :new-name "::full-name"}))] (is (= {(h/file-uri "file") [{:new-text "::u/full-name" :range (h/->range main-uname-kw-start main-uname-kw-end)}] (h/file-uri "file") [{:new-text "::full-name" :range (h/->range uname-kw-start uname-kw-end)}]} changes)))) (testing "on qualified keyword without alias" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position d-name-kw-start) :new-name "::other-name"}))] (is (= {(h/file-uri "file") [{:new-text "::other-name" :range (h/->range d-name-kw-start d-name-kw-stop)}] (h/file-uri "file") [{:new-text "::dd/other-name" :range (h/->range kw-aliased-start kw-aliased-stop)} {:new-text ":d.dd/other-name" :range (h/->range kw-unaliased-start kw-unaliased-stop)}]} changes)))) (testing "on alias changes namespaces inside file" (let [changes (:changes (handlers/rename (h/components) {:text-document {:uri (h/file-uri "file")} :position (h/->position balias-start) :new-name "xx"}))] (is (= {(h/file-uri "file") [{:range (h/->range balias-start balias-stop) :new-text "xx"} {:range (h/->range ba2-kw-start ba2-kw-stop) :new-text "::xx/bar"} {:range (h/->range ba1-start bbar-stop) :new-text "xx/bar"}]} changes)))))) (deftest test-code-actions-handle (h/load-code-and-locs (str "(ns some-ns)\n" "(def foo)") (h/file-uri "file")) (h/load-code-and-locs (str "(ns other-ns (:require [some-ns :as sns]))\n" "(def bar 1)\n" "(defn baz []\n" " bar)") (h/file-uri "file")) (h/load-code-and-locs (str "(ns another-ns)\n" "(def bar ons/bar)\n" "(def foo sns/foo)\n" "(deftest some-test)\n" "MyClass.\n" "Date.") (h/file-uri "file")) (testing "when it has unresolved-namespace and can find namespace" (is (some #(= (:title %) "Add require '[some-ns :as sns]' × 1") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics [{:code "unresolved-namespace" :range {:start {:line 2 :character 10}}}]} :range {:start {:line 2 :character 10}}})))) (testing "without workspace edit client capability" (swap! (h/db*) merge {:client-capabilities {:workspace {:workspace-edit false}}}) (is (not-any? #(= (:title %) "Clean namespace") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics []} :range {:start {:line 1 :character 1}}})))) (testing "with workspace edit client capability" (swap! (h/db*) merge {:client-capabilities {:workspace {:workspace-edit true}}}) (is (some #(= (:title %) "Clean namespace") (handlers/code-actions (h/components) {:text-document {:uri (h/file-uri "file")} :context {:diagnostics []} :range {:start {:line 1 :character 1}}}))))) (deftest code-lens-can-be-resolved (h/load-code-and-locs (str "(ns some-ns)\n" "(def foo 1)\n" "(defn- foo2 []\n" " foo)\n" "(defn bar [a b]\n" " (+ a b (foo2)))\n" "(s/defn baz []\n" " (bar 2 3))\n")) (let [code-lenses (handlers/code-lens (h/components) {:text-document {:uri h/default-uri}}) resolved-code-lenses (map (fn [code-lens] (handlers/code-lens-resolve (h/components) code-lens)) code-lenses)] (is (= [0 1 2 4] (map #(get-in % [:range :start :line]) resolved-code-lenses))) (is (= ["0 references" "1 reference" "1 reference" "1 reference"] (map #(get-in % [:command :title]) resolved-code-lenses))))) (deftest server-info-raw (testing "returns kebab-case strings, to avoid camelCase conversion of keywords" (is (seq (get (handlers/server-info-raw (h/components)) "server-version"))))) (deftest cursor-info-raw (testing "returns kebab-case strings, to avoid camelCase conversion of keywords" (let [[row-and-col] (h/load-code-and-locs "(ns |a)")] (is (seq (get (handlers/cursor-info-raw (h/components) {:text-document {:uri h/default-uri} :position (h/->position row-and-col)}) "elements"))))))
65ebafb605f720f3dcf3af49ec4d1fb7819626f1002e5f9628353bb56dc9b883
reifyhealth/specmonstah
queries.cljs
(ns specmonstah-demo.examples.queries (:require [shadow.resource :as rc])) (def queries [{:name "specify usernames" :description "Specmonstah generates a lot of data for you, but you have the power to customize any of it." :query {:user [[:custom-user-1 {:spec-gen {:user-name "Captain Crunch"}}] [:custom-user-2 {:spec-gen {:id 100}}]]}} {:name "multiple ents" :description "Generate 3 todos. Try generating more or fewer." :query {:todo [[3]]}} {:name ":coll constraint" :description "Projects store multiple todo list ids under :todo-list-ids." :query {:project [[:_ {:refs {:todo-list-ids 3}}]]}} {:name ":uniq constraint" :description "Users can't watch the same todo list twice. Therefore, when generating todo list watches, also generate unique todo lists to watch." :query {:todo-list-watch [[3]]}}])
null
https://raw.githubusercontent.com/reifyhealth/specmonstah/afe38e7a39149836c31719f7e36a7504c14dbb80/demo/src/specmonstah_demo/examples/queries.cljs
clojure
(ns specmonstah-demo.examples.queries (:require [shadow.resource :as rc])) (def queries [{:name "specify usernames" :description "Specmonstah generates a lot of data for you, but you have the power to customize any of it." :query {:user [[:custom-user-1 {:spec-gen {:user-name "Captain Crunch"}}] [:custom-user-2 {:spec-gen {:id 100}}]]}} {:name "multiple ents" :description "Generate 3 todos. Try generating more or fewer." :query {:todo [[3]]}} {:name ":coll constraint" :description "Projects store multiple todo list ids under :todo-list-ids." :query {:project [[:_ {:refs {:todo-list-ids 3}}]]}} {:name ":uniq constraint" :description "Users can't watch the same todo list twice. Therefore, when generating todo list watches, also generate unique todo lists to watch." :query {:todo-list-watch [[3]]}}])
5e81b380c9bfeec3d49503cfe453e347e1136a3854d8452de5cf116a987fa2dd
xavierleroy/camlidl
lexpr.ml
(***********************************************************************) (* *) (* CamlIDL *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed (* under the terms of the GNU Lesser General Public License LGPL v2.1 *) (* *) (***********************************************************************) $ I d : lexpr.ml , v 1.11 2002 - 01 - 16 16:15:32 xleroy Exp $ (* Evaluation and pretty-printing of limited expressions *) open Printf open Idltypes open Utils type constant_value = Cst_int of int32 | Cst_long of nativeint | Cst_longlong of int64 | Cst_string of string (* Bind values to constant names *) let const_val = (Hashtbl.create 29 : (string, constant_value) Hashtbl.t) let bind_const name v = Hashtbl.add const_val name v (* Evaluate a limited expression to a constant *) let is_true = function Cst_int n -> n <> Int32.zero | Cst_long n -> n <> Nativeint.zero | Cst_longlong n -> n <> Int64.zero hmph let cst_true = Cst_int Int32.one let cst_false = Cst_int Int32.zero let compare rel (v1, v2) = match (v1, v2) with (Cst_int n1, Cst_int n2) -> if rel v1 v2 then cst_true else cst_false | (Cst_long n1, Cst_long n2) -> if rel v1 v2 then cst_true else cst_false | (Cst_longlong n1, Cst_longlong n2) -> if rel v1 v2 then cst_true else cst_false | (_, _) -> error("illegal comparison") let int_val = function Cst_int n -> Int32.to_int n | Cst_long n -> Nativeint.to_int n | Cst_longlong n -> Int64.to_int n | _ -> error "string value in integer context" let int32_val = function Cst_int n -> n | Cst_long n -> Nativeint.to_int32 n | Cst_longlong n -> Int64.to_int32 n | _ -> error "string value in integer context" let nativeint_val = function Cst_int n -> Nativeint.of_int32 n | Cst_long n -> n | Cst_longlong n -> Int64.to_nativeint n | _ -> error "string value in integer context" let int64_val = function Cst_int n -> Int64.of_int32 n | Cst_long n -> Int64.of_nativeint n | Cst_longlong n -> n | _ -> error "string value in integer context" let string_val = function Cst_string s -> s | _ -> error "integer value in string context" (* Expand a typedef name, returning its definition *) let expand_typedef = ref ((fun _ -> assert false) : string -> idltype) let rec cast_value ty v = match ty with Type_int(kind, _) -> begin match kind with Int | UInt -> Cst_int(int32_val v) | Long | ULong -> Cst_long(nativeint_val v) | Hyper | UHyper -> Cst_longlong(int64_val v) | USmall | Char | UChar | Byte | Boolean -> Cst_int(Int32.logand (int32_val v) (Int32.of_int 0xFF)) | Small | SChar -> Cst_int(Int32.shift_right (Int32.shift_left (int32_val v) 24) 24) | Short -> Cst_int(Int32.shift_right (Int32.shift_left (int32_val v) 16) 16) | UShort -> Cst_int(Int32.logand (int32_val v) (Int32.of_int 0xFFFF)) end | Type_pointer(_, Type_int((Char|UChar|SChar), _)) | Type_array({is_string = true}, _) -> Cst_string(string_val v) | Type_named(modname, tyname) -> let ty' = try !expand_typedef tyname with Not_found -> error (sprintf "unknown type name %s" tyname) in cast_value ty' v | Type_const ty' -> cast_value ty' v | _ -> error "unsupported type for constant expression" (* Evaluate a limited expression *) let rec eval = function Expr_ident v -> (try Hashtbl.find const_val v with Not_found -> error (sprintf "%s is not a constant" v)) | Expr_int n -> if n < Int64.of_int32 Int32.max_int && n >= Int64.of_int32 Int32.min_int then Cst_int(Int64.to_int32 n) else if n < Int64.of_nativeint Nativeint.max_int && n >= Int64.of_nativeint Nativeint.min_int then Cst_long(Int64.to_nativeint n) else Cst_longlong n | Expr_string s -> Cst_string s | Expr_cond (e1, e2, e3) -> if is_true(eval e1) then eval e2 else eval e3 | Expr_sequand (e1, e2) -> let v1 = eval e1 in if is_true v1 then eval e2 else v1 | Expr_sequor (e1, e2) -> let v1 = eval e1 in if is_true v1 then v1 else eval e2 | Expr_logor (e1, e2) -> eval_binary Int32.logor Nativeint.logor Int64.logor e1 e2 | Expr_logxor (e1, e2) -> eval_binary Int32.logxor Nativeint.logxor Int64.logxor e1 e2 | Expr_logand (e1, e2) -> eval_binary Int32.logand Nativeint.logand Int64.logand e1 e2 | Expr_eq (e1, e2) -> compare (=) (eval_promote e1 e2) | Expr_ne (e1, e2) -> compare (<>) (eval_promote e1 e2) | Expr_lt (e1, e2) -> compare (<) (eval_promote e1 e2) | Expr_gt (e1, e2) -> compare (>) (eval_promote e1 e2) | Expr_le (e1, e2) -> compare (<=) (eval_promote e1 e2) | Expr_ge (e1, e2) -> compare (>=) (eval_promote e1 e2) | Expr_lshift (e1, e2) -> eval_shift Int32.shift_left Nativeint.shift_left Int64.shift_left e1 e2 | Expr_rshift (e1, e2) -> eval_shift Int32.shift_right Nativeint.shift_right Int64.shift_right e1 e2 | Expr_rshift_unsigned (e1, e2) -> eval_shift Int32.shift_right_logical Nativeint.shift_right_logical Int64.shift_right_logical e1 e2 | Expr_plus (e1, e2) -> eval_binary Int32.add Nativeint.add Int64.add e1 e2 | Expr_minus (e1, e2) -> eval_binary Int32.sub Nativeint.sub Int64.sub e1 e2 | Expr_times (e1, e2) -> eval_binary Int32.mul Nativeint.mul Int64.mul e1 e2 | Expr_div (e1, e2) -> begin try eval_binary Int32.div Nativeint.div Int64.div e1 e2 with Division_by_zero -> error "division by zero" end | Expr_mod (e1, e2) -> begin try eval_binary Int32.rem Nativeint.rem Int64.rem e1 e2 with Division_by_zero -> error "division by zero" end | Expr_neg e1 -> eval_unary Int32.neg Nativeint.neg Int64.neg e1 | Expr_lognot e1 -> eval_unary Int32.lognot Nativeint.lognot Int64.lognot e1 | Expr_boolnot e1 -> if is_true(eval e1) then cst_false else cst_true | Expr_cast(ty, e1) -> cast_value ty (eval e1) | Expr_sizeof ty -> Cst_int(Int32.of_int(match ty with Type_int((Int|UInt), _) -> 4 | Type_int((Long|ULong), _) -> Sys.word_size / 4 | Type_int((Hyper|UHyper), _) -> 8 | Type_int((Small|USmall|Char|UChar|SChar|Byte|Boolean), _) -> 1 | Type_int((Short|UShort), _) -> 2 | Type_float -> 4 | Type_double -> 8 | Type_pointer(_, _) -> Sys.word_size / 4 | _ -> error "cannot compute sizeof")) | _ -> error("illegal operation in constant expression") and eval_promote e1 e2 = let v1 = eval e1 and v2 = eval e2 in match (v1, v2) with | (Cst_int n1, Cst_long n2) -> (Cst_long (Nativeint.of_int32 n1), v2) | (Cst_long n1, Cst_int n2) -> (v1, Cst_long(Nativeint.of_int32 n2)) | (Cst_int n1, Cst_longlong n2) -> (Cst_longlong(Int64.of_int32 n1), v2) | (Cst_longlong n1, Cst_int n2) -> (v1, Cst_longlong(Int64.of_int32 n2)) | (Cst_long n1, Cst_longlong n2) -> (Cst_longlong(Int64.of_nativeint n1), v2) | (Cst_longlong n1, Cst_long n2) -> (v1, Cst_longlong(Int64.of_nativeint n2)) | (_, _) -> (v1, v2) and eval_binary op32 opnative op64 e1 e2 = match eval_promote e1 e2 with (Cst_int n1, Cst_int n2) -> Cst_int(op32 n1 n2) | (Cst_long n1, Cst_long n2) -> Cst_long(opnative n1 n2) | (Cst_longlong n1, Cst_longlong n2) -> Cst_longlong(op64 n1 n2) | (_, _) -> error("non-integer arguments to integer operation") and eval_unary op32 opnative op64 e1 = match eval e1 with Cst_int n1 -> Cst_int(op32 n1) | Cst_long n1 -> Cst_long(opnative n1) | Cst_longlong n1 -> Cst_longlong(op64 n1) | _ -> error("non-integer argument to integer operation") and eval_shift op32 opnative op64 e1 e2 = let n2 = int_val(eval e2) in match eval e1 with Cst_int n1 -> Cst_int(op32 n1 n2) | Cst_long n1 -> Cst_long(opnative n1 n2) | Cst_longlong n1 -> Cst_longlong(op64 n1 n2) | _ -> error("non-integer arguments to integer operation") (* Evaluate a limited expression to an integer *) let eval_int e = int_val(eval e) (* Test if this expression is just an identifier, possibly by reference [*x] *) let is_identifier_deref = function | Expr_ident _ -> true | Expr_deref (Expr_ident _) -> true | _ -> false (* Pretty-print a limited expression *) open Buffer let b = create 80 let rec tstype trail = function Type_int(kind,_) -> add_string b (integer_type kind); add_string b trail | Type_float -> add_string b "float"; add_string b trail | Type_double -> add_string b "double"; add_string b trail | Type_void -> add_string b "void"; add_string b trail | Type_struct sd -> assert (sd.sd_name <> ""); add_string b "struct "; add_string b sd.sd_name; add_string b trail | Type_union(ud, discr) -> assert (ud.ud_name <> ""); add_string b "union "; add_string b ud.ud_name; add_string b trail | Type_enum (en, attr) -> add_string b "int"; add_string b trail | Type_named(modl, ty_name) -> add_string b ty_name; add_string b trail | Type_pointer(attr, (Type_array(_,_) as ty)) -> tstype (sprintf "(*%s)" trail) ty | Type_pointer(attr, ty) -> tstype (sprintf "*%s" trail) ty | Type_array(attr, ty) -> let trail' = match attr.bound with Some n -> sprintf "%s[]" trail | None -> sprintf "*%s" trail in tstype trail' ty | Type_bigarray(attr, ty) -> tstype (sprintf "*%s" trail) ty | Type_interface(modl, intf_name) -> add_string b "struct "; add_string b intf_name; add_string b trail | Type_const ty -> tstype (sprintf " const %s" trail) ty and integer_type = function Int -> "int" | Long -> "long" | Hyper -> Config.int64_type | Small -> "signed char" | Short -> "short" | Char -> "char" | UInt -> "unsigned int" | ULong -> "unsigned long" | UHyper -> Config.uint64_type | USmall -> "unsigned char" | UShort -> "unsigned short" | UChar -> "unsigned char" | SChar -> "signed char" | Byte -> "unsigned char" | Boolean -> "int" let add_escaped_string s = add_char b '"'; for i = 0 to String.length s - 1 do let c = s.[i] in if c >= ' ' && c <= '~' then add_char b c else add_string b (sprintf "\\%03o" (Char.code c)) done; add_char b '"' let tostr pref e = let rec ts = function Expr_cond(e1, e2, e3) -> ts1 e1; add_string b " ? "; ts1 e2; add_string b " : "; ts1 e3 | e -> ts1 e and ts1 = function Expr_sequor(e1, e2) -> ts2 e1; add_string b " || "; ts2 e2 | Expr_sequand(e1, e2) -> ts2 e1; add_string b " && "; ts2 e2 | e -> ts2 e and ts2 = function Expr_logand(e1, e2) -> ts3 e1; add_string b " & "; ts3 e2 | Expr_logor(e1, e2) -> ts3 e1; add_string b " | "; ts3 e2 | Expr_logxor(e1, e2) -> ts3 e1; add_string b " ^ "; ts3 e2 | e -> ts3 e and ts3 = function Expr_eq(e1, e2) -> ts4 e1; add_string b " == "; ts4 e2 | Expr_ne(e1, e2) -> ts4 e1; add_string b " != "; ts4 e2 | Expr_lt(e1, e2) -> ts4 e1; add_string b " < "; ts4 e2 | Expr_gt(e1, e2) -> ts4 e1; add_string b " > "; ts4 e2 | Expr_le(e1, e2) -> ts4 e1; add_string b " <= "; ts4 e2 | Expr_ge(e1, e2) -> ts4 e1; add_string b " >= "; ts4 e2 | e -> ts4 e and ts4 = function Expr_lshift(e1, e2) -> ts5 e1; add_string b " << "; ts5 e2 | Expr_rshift(e1, e2) -> ts5 e1; add_string b " >> "; ts5 e2 | Expr_rshift_unsigned(e1, e2) -> (*revise!*) ts5 e1; add_string b " >> "; ts5 e2 | e -> ts5 e and ts5 = function Expr_plus(e1, e2) -> ts5 e1; add_string b " + "; ts5 e2 | Expr_minus(e1, e2) -> ts5 e1; add_string b " - "; ts6 e2 | e -> ts6 e and ts6 = function Expr_times(e1, e2) -> ts6 e1; add_string b " * "; ts6 e2 | Expr_div(e1, e2) -> ts6 e1; add_string b " / "; ts7 e2 | Expr_mod(e1, e2) -> ts6 e1; add_string b " % "; ts7 e2 | e -> ts7 e and ts7 = function Expr_neg e -> add_string b "-"; ts7 e | Expr_lognot e -> add_string b "~"; ts7 e | Expr_boolnot e -> add_string b "!"; ts7 e | Expr_deref e -> add_string b "*"; ts7 e | Expr_addressof e -> add_string b "&"; ts7 e | Expr_cast(ty, e) -> add_string b "("; tstype "" ty; add_string b ") "; ts7 e | Expr_sizeof(ty) -> add_string b "sizeof("; tstype "" ty; add_string b ")" | e -> ts8 e and ts8 = function Expr_subscript(e1, e2) -> ts8 e1; add_string b "["; ts e2; add_string b "]" | Expr_dereffield(e1, s) -> ts8 e1; add_string b "->"; add_string b s | Expr_field(e1, s) -> ts8 e1; add_string b "."; add_string b s | e -> ts9 e and ts9 = function Expr_ident s -> begin try match Hashtbl.find const_val s with Cst_int n -> add_string b (Int32.to_string n) | Cst_long n -> add_string b (Nativeint.to_string n); add_char b 'L' | Cst_longlong n -> add_string b (Int64.to_string n); add_string b "LL" | Cst_string s -> add_escaped_string s with Not_found -> add_string b (Prefix.for_ident pref s); add_string b s end | Expr_int n -> add_string b (Int64.to_string n) | Expr_string s -> add_escaped_string s | e -> add_char b '('; ts e; add_char b ')' in ts7 e let tostring pref e = Buffer.clear b; tostr pref e; let res = Buffer.contents b in Buffer.reset b; res let output oc (pref, e) = Buffer.clear b; tostr pref e; Buffer.output_buffer oc b; Buffer.reset b (* Check if a variable is free in a limited expression *) let is_free v e = let rec free = function Expr_ident s -> s = v | Expr_int n -> false | Expr_string s -> false | Expr_cond (e1, e2, e3) -> free e1 || free e2 || free e3 | Expr_sequand (e1, e2) -> free e1 || free e2 | Expr_sequor (e1, e2) -> free e1 || free e2 | Expr_logor (e1, e2) -> free e1 || free e2 | Expr_logxor (e1, e2) -> free e1 || free e2 | Expr_logand (e1, e2) -> free e1 || free e2 | Expr_eq (e1, e2) -> free e1 || free e2 | Expr_ne (e1, e2) -> free e1 || free e2 | Expr_lt (e1, e2) -> free e1 || free e2 | Expr_gt (e1, e2) -> free e1 || free e2 | Expr_le (e1, e2) -> free e1 || free e2 | Expr_ge (e1, e2) -> free e1 || free e2 | Expr_lshift (e1, e2) -> free e1 || free e2 | Expr_rshift (e1, e2) -> free e1 || free e2 | Expr_rshift_unsigned (e1, e2) -> free e1 || free e2 | Expr_plus (e1, e2) -> free e1 || free e2 | Expr_minus (e1, e2) -> free e1 || free e2 | Expr_times (e1, e2) -> free e1 || free e2 | Expr_div (e1, e2) -> free e1 || free e2 | Expr_mod (e1, e2) -> free e1 || free e2 | Expr_neg (e1) -> free e1 | Expr_lognot (e1) -> free e1 | Expr_boolnot (e1) -> free e1 | Expr_deref (e1) -> free e1 | Expr_addressof (e1) -> free e1 | Expr_cast (ty, e1) -> free e1 | Expr_sizeof ty -> false | Expr_subscript (e1, e2) -> free e1 || free e2 | Expr_dereffield (e1, s) -> free e1 | Expr_field (e1, s) -> free e1 in free e let is_free_opt v opte = match opte with None -> false | Some e -> is_free v e (* Check if a variable appears in a dependent type *) let rec is_dependent v ty = match ty with Type_array(attr, ty) -> is_free_opt v attr.size || is_free_opt v attr.length || is_dependent v ty | Type_bigarray(attr, ty) -> List.exists (fun a -> is_free_opt v a.size || is_free_opt v a.length) attr.dims || is_dependent v ty | Type_union(name, attr) -> is_free v attr.discriminant | Type_pointer(_, ty) -> is_dependent v ty | Type_const ty -> is_dependent v ty | _ -> false
null
https://raw.githubusercontent.com/xavierleroy/camlidl/b192760875fe6e97b13004bd289720618e12ee22/compiler/lexpr.ml
ocaml
********************************************************************* CamlIDL under the terms of the GNU Lesser General Public License LGPL v2.1 ********************************************************************* Evaluation and pretty-printing of limited expressions Bind values to constant names Evaluate a limited expression to a constant Expand a typedef name, returning its definition Evaluate a limited expression Evaluate a limited expression to an integer Test if this expression is just an identifier, possibly by reference [*x] Pretty-print a limited expression revise! Check if a variable is free in a limited expression Check if a variable appears in a dependent type
, projet Cristal , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed $ I d : lexpr.ml , v 1.11 2002 - 01 - 16 16:15:32 xleroy Exp $ open Printf open Idltypes open Utils type constant_value = Cst_int of int32 | Cst_long of nativeint | Cst_longlong of int64 | Cst_string of string let const_val = (Hashtbl.create 29 : (string, constant_value) Hashtbl.t) let bind_const name v = Hashtbl.add const_val name v let is_true = function Cst_int n -> n <> Int32.zero | Cst_long n -> n <> Nativeint.zero | Cst_longlong n -> n <> Int64.zero hmph let cst_true = Cst_int Int32.one let cst_false = Cst_int Int32.zero let compare rel (v1, v2) = match (v1, v2) with (Cst_int n1, Cst_int n2) -> if rel v1 v2 then cst_true else cst_false | (Cst_long n1, Cst_long n2) -> if rel v1 v2 then cst_true else cst_false | (Cst_longlong n1, Cst_longlong n2) -> if rel v1 v2 then cst_true else cst_false | (_, _) -> error("illegal comparison") let int_val = function Cst_int n -> Int32.to_int n | Cst_long n -> Nativeint.to_int n | Cst_longlong n -> Int64.to_int n | _ -> error "string value in integer context" let int32_val = function Cst_int n -> n | Cst_long n -> Nativeint.to_int32 n | Cst_longlong n -> Int64.to_int32 n | _ -> error "string value in integer context" let nativeint_val = function Cst_int n -> Nativeint.of_int32 n | Cst_long n -> n | Cst_longlong n -> Int64.to_nativeint n | _ -> error "string value in integer context" let int64_val = function Cst_int n -> Int64.of_int32 n | Cst_long n -> Int64.of_nativeint n | Cst_longlong n -> n | _ -> error "string value in integer context" let string_val = function Cst_string s -> s | _ -> error "integer value in string context" let expand_typedef = ref ((fun _ -> assert false) : string -> idltype) let rec cast_value ty v = match ty with Type_int(kind, _) -> begin match kind with Int | UInt -> Cst_int(int32_val v) | Long | ULong -> Cst_long(nativeint_val v) | Hyper | UHyper -> Cst_longlong(int64_val v) | USmall | Char | UChar | Byte | Boolean -> Cst_int(Int32.logand (int32_val v) (Int32.of_int 0xFF)) | Small | SChar -> Cst_int(Int32.shift_right (Int32.shift_left (int32_val v) 24) 24) | Short -> Cst_int(Int32.shift_right (Int32.shift_left (int32_val v) 16) 16) | UShort -> Cst_int(Int32.logand (int32_val v) (Int32.of_int 0xFFFF)) end | Type_pointer(_, Type_int((Char|UChar|SChar), _)) | Type_array({is_string = true}, _) -> Cst_string(string_val v) | Type_named(modname, tyname) -> let ty' = try !expand_typedef tyname with Not_found -> error (sprintf "unknown type name %s" tyname) in cast_value ty' v | Type_const ty' -> cast_value ty' v | _ -> error "unsupported type for constant expression" let rec eval = function Expr_ident v -> (try Hashtbl.find const_val v with Not_found -> error (sprintf "%s is not a constant" v)) | Expr_int n -> if n < Int64.of_int32 Int32.max_int && n >= Int64.of_int32 Int32.min_int then Cst_int(Int64.to_int32 n) else if n < Int64.of_nativeint Nativeint.max_int && n >= Int64.of_nativeint Nativeint.min_int then Cst_long(Int64.to_nativeint n) else Cst_longlong n | Expr_string s -> Cst_string s | Expr_cond (e1, e2, e3) -> if is_true(eval e1) then eval e2 else eval e3 | Expr_sequand (e1, e2) -> let v1 = eval e1 in if is_true v1 then eval e2 else v1 | Expr_sequor (e1, e2) -> let v1 = eval e1 in if is_true v1 then v1 else eval e2 | Expr_logor (e1, e2) -> eval_binary Int32.logor Nativeint.logor Int64.logor e1 e2 | Expr_logxor (e1, e2) -> eval_binary Int32.logxor Nativeint.logxor Int64.logxor e1 e2 | Expr_logand (e1, e2) -> eval_binary Int32.logand Nativeint.logand Int64.logand e1 e2 | Expr_eq (e1, e2) -> compare (=) (eval_promote e1 e2) | Expr_ne (e1, e2) -> compare (<>) (eval_promote e1 e2) | Expr_lt (e1, e2) -> compare (<) (eval_promote e1 e2) | Expr_gt (e1, e2) -> compare (>) (eval_promote e1 e2) | Expr_le (e1, e2) -> compare (<=) (eval_promote e1 e2) | Expr_ge (e1, e2) -> compare (>=) (eval_promote e1 e2) | Expr_lshift (e1, e2) -> eval_shift Int32.shift_left Nativeint.shift_left Int64.shift_left e1 e2 | Expr_rshift (e1, e2) -> eval_shift Int32.shift_right Nativeint.shift_right Int64.shift_right e1 e2 | Expr_rshift_unsigned (e1, e2) -> eval_shift Int32.shift_right_logical Nativeint.shift_right_logical Int64.shift_right_logical e1 e2 | Expr_plus (e1, e2) -> eval_binary Int32.add Nativeint.add Int64.add e1 e2 | Expr_minus (e1, e2) -> eval_binary Int32.sub Nativeint.sub Int64.sub e1 e2 | Expr_times (e1, e2) -> eval_binary Int32.mul Nativeint.mul Int64.mul e1 e2 | Expr_div (e1, e2) -> begin try eval_binary Int32.div Nativeint.div Int64.div e1 e2 with Division_by_zero -> error "division by zero" end | Expr_mod (e1, e2) -> begin try eval_binary Int32.rem Nativeint.rem Int64.rem e1 e2 with Division_by_zero -> error "division by zero" end | Expr_neg e1 -> eval_unary Int32.neg Nativeint.neg Int64.neg e1 | Expr_lognot e1 -> eval_unary Int32.lognot Nativeint.lognot Int64.lognot e1 | Expr_boolnot e1 -> if is_true(eval e1) then cst_false else cst_true | Expr_cast(ty, e1) -> cast_value ty (eval e1) | Expr_sizeof ty -> Cst_int(Int32.of_int(match ty with Type_int((Int|UInt), _) -> 4 | Type_int((Long|ULong), _) -> Sys.word_size / 4 | Type_int((Hyper|UHyper), _) -> 8 | Type_int((Small|USmall|Char|UChar|SChar|Byte|Boolean), _) -> 1 | Type_int((Short|UShort), _) -> 2 | Type_float -> 4 | Type_double -> 8 | Type_pointer(_, _) -> Sys.word_size / 4 | _ -> error "cannot compute sizeof")) | _ -> error("illegal operation in constant expression") and eval_promote e1 e2 = let v1 = eval e1 and v2 = eval e2 in match (v1, v2) with | (Cst_int n1, Cst_long n2) -> (Cst_long (Nativeint.of_int32 n1), v2) | (Cst_long n1, Cst_int n2) -> (v1, Cst_long(Nativeint.of_int32 n2)) | (Cst_int n1, Cst_longlong n2) -> (Cst_longlong(Int64.of_int32 n1), v2) | (Cst_longlong n1, Cst_int n2) -> (v1, Cst_longlong(Int64.of_int32 n2)) | (Cst_long n1, Cst_longlong n2) -> (Cst_longlong(Int64.of_nativeint n1), v2) | (Cst_longlong n1, Cst_long n2) -> (v1, Cst_longlong(Int64.of_nativeint n2)) | (_, _) -> (v1, v2) and eval_binary op32 opnative op64 e1 e2 = match eval_promote e1 e2 with (Cst_int n1, Cst_int n2) -> Cst_int(op32 n1 n2) | (Cst_long n1, Cst_long n2) -> Cst_long(opnative n1 n2) | (Cst_longlong n1, Cst_longlong n2) -> Cst_longlong(op64 n1 n2) | (_, _) -> error("non-integer arguments to integer operation") and eval_unary op32 opnative op64 e1 = match eval e1 with Cst_int n1 -> Cst_int(op32 n1) | Cst_long n1 -> Cst_long(opnative n1) | Cst_longlong n1 -> Cst_longlong(op64 n1) | _ -> error("non-integer argument to integer operation") and eval_shift op32 opnative op64 e1 e2 = let n2 = int_val(eval e2) in match eval e1 with Cst_int n1 -> Cst_int(op32 n1 n2) | Cst_long n1 -> Cst_long(opnative n1 n2) | Cst_longlong n1 -> Cst_longlong(op64 n1 n2) | _ -> error("non-integer arguments to integer operation") let eval_int e = int_val(eval e) let is_identifier_deref = function | Expr_ident _ -> true | Expr_deref (Expr_ident _) -> true | _ -> false open Buffer let b = create 80 let rec tstype trail = function Type_int(kind,_) -> add_string b (integer_type kind); add_string b trail | Type_float -> add_string b "float"; add_string b trail | Type_double -> add_string b "double"; add_string b trail | Type_void -> add_string b "void"; add_string b trail | Type_struct sd -> assert (sd.sd_name <> ""); add_string b "struct "; add_string b sd.sd_name; add_string b trail | Type_union(ud, discr) -> assert (ud.ud_name <> ""); add_string b "union "; add_string b ud.ud_name; add_string b trail | Type_enum (en, attr) -> add_string b "int"; add_string b trail | Type_named(modl, ty_name) -> add_string b ty_name; add_string b trail | Type_pointer(attr, (Type_array(_,_) as ty)) -> tstype (sprintf "(*%s)" trail) ty | Type_pointer(attr, ty) -> tstype (sprintf "*%s" trail) ty | Type_array(attr, ty) -> let trail' = match attr.bound with Some n -> sprintf "%s[]" trail | None -> sprintf "*%s" trail in tstype trail' ty | Type_bigarray(attr, ty) -> tstype (sprintf "*%s" trail) ty | Type_interface(modl, intf_name) -> add_string b "struct "; add_string b intf_name; add_string b trail | Type_const ty -> tstype (sprintf " const %s" trail) ty and integer_type = function Int -> "int" | Long -> "long" | Hyper -> Config.int64_type | Small -> "signed char" | Short -> "short" | Char -> "char" | UInt -> "unsigned int" | ULong -> "unsigned long" | UHyper -> Config.uint64_type | USmall -> "unsigned char" | UShort -> "unsigned short" | UChar -> "unsigned char" | SChar -> "signed char" | Byte -> "unsigned char" | Boolean -> "int" let add_escaped_string s = add_char b '"'; for i = 0 to String.length s - 1 do let c = s.[i] in if c >= ' ' && c <= '~' then add_char b c else add_string b (sprintf "\\%03o" (Char.code c)) done; add_char b '"' let tostr pref e = let rec ts = function Expr_cond(e1, e2, e3) -> ts1 e1; add_string b " ? "; ts1 e2; add_string b " : "; ts1 e3 | e -> ts1 e and ts1 = function Expr_sequor(e1, e2) -> ts2 e1; add_string b " || "; ts2 e2 | Expr_sequand(e1, e2) -> ts2 e1; add_string b " && "; ts2 e2 | e -> ts2 e and ts2 = function Expr_logand(e1, e2) -> ts3 e1; add_string b " & "; ts3 e2 | Expr_logor(e1, e2) -> ts3 e1; add_string b " | "; ts3 e2 | Expr_logxor(e1, e2) -> ts3 e1; add_string b " ^ "; ts3 e2 | e -> ts3 e and ts3 = function Expr_eq(e1, e2) -> ts4 e1; add_string b " == "; ts4 e2 | Expr_ne(e1, e2) -> ts4 e1; add_string b " != "; ts4 e2 | Expr_lt(e1, e2) -> ts4 e1; add_string b " < "; ts4 e2 | Expr_gt(e1, e2) -> ts4 e1; add_string b " > "; ts4 e2 | Expr_le(e1, e2) -> ts4 e1; add_string b " <= "; ts4 e2 | Expr_ge(e1, e2) -> ts4 e1; add_string b " >= "; ts4 e2 | e -> ts4 e and ts4 = function Expr_lshift(e1, e2) -> ts5 e1; add_string b " << "; ts5 e2 | Expr_rshift(e1, e2) -> ts5 e1; add_string b " >> "; ts5 e2 ts5 e1; add_string b " >> "; ts5 e2 | e -> ts5 e and ts5 = function Expr_plus(e1, e2) -> ts5 e1; add_string b " + "; ts5 e2 | Expr_minus(e1, e2) -> ts5 e1; add_string b " - "; ts6 e2 | e -> ts6 e and ts6 = function Expr_times(e1, e2) -> ts6 e1; add_string b " * "; ts6 e2 | Expr_div(e1, e2) -> ts6 e1; add_string b " / "; ts7 e2 | Expr_mod(e1, e2) -> ts6 e1; add_string b " % "; ts7 e2 | e -> ts7 e and ts7 = function Expr_neg e -> add_string b "-"; ts7 e | Expr_lognot e -> add_string b "~"; ts7 e | Expr_boolnot e -> add_string b "!"; ts7 e | Expr_deref e -> add_string b "*"; ts7 e | Expr_addressof e -> add_string b "&"; ts7 e | Expr_cast(ty, e) -> add_string b "("; tstype "" ty; add_string b ") "; ts7 e | Expr_sizeof(ty) -> add_string b "sizeof("; tstype "" ty; add_string b ")" | e -> ts8 e and ts8 = function Expr_subscript(e1, e2) -> ts8 e1; add_string b "["; ts e2; add_string b "]" | Expr_dereffield(e1, s) -> ts8 e1; add_string b "->"; add_string b s | Expr_field(e1, s) -> ts8 e1; add_string b "."; add_string b s | e -> ts9 e and ts9 = function Expr_ident s -> begin try match Hashtbl.find const_val s with Cst_int n -> add_string b (Int32.to_string n) | Cst_long n -> add_string b (Nativeint.to_string n); add_char b 'L' | Cst_longlong n -> add_string b (Int64.to_string n); add_string b "LL" | Cst_string s -> add_escaped_string s with Not_found -> add_string b (Prefix.for_ident pref s); add_string b s end | Expr_int n -> add_string b (Int64.to_string n) | Expr_string s -> add_escaped_string s | e -> add_char b '('; ts e; add_char b ')' in ts7 e let tostring pref e = Buffer.clear b; tostr pref e; let res = Buffer.contents b in Buffer.reset b; res let output oc (pref, e) = Buffer.clear b; tostr pref e; Buffer.output_buffer oc b; Buffer.reset b let is_free v e = let rec free = function Expr_ident s -> s = v | Expr_int n -> false | Expr_string s -> false | Expr_cond (e1, e2, e3) -> free e1 || free e2 || free e3 | Expr_sequand (e1, e2) -> free e1 || free e2 | Expr_sequor (e1, e2) -> free e1 || free e2 | Expr_logor (e1, e2) -> free e1 || free e2 | Expr_logxor (e1, e2) -> free e1 || free e2 | Expr_logand (e1, e2) -> free e1 || free e2 | Expr_eq (e1, e2) -> free e1 || free e2 | Expr_ne (e1, e2) -> free e1 || free e2 | Expr_lt (e1, e2) -> free e1 || free e2 | Expr_gt (e1, e2) -> free e1 || free e2 | Expr_le (e1, e2) -> free e1 || free e2 | Expr_ge (e1, e2) -> free e1 || free e2 | Expr_lshift (e1, e2) -> free e1 || free e2 | Expr_rshift (e1, e2) -> free e1 || free e2 | Expr_rshift_unsigned (e1, e2) -> free e1 || free e2 | Expr_plus (e1, e2) -> free e1 || free e2 | Expr_minus (e1, e2) -> free e1 || free e2 | Expr_times (e1, e2) -> free e1 || free e2 | Expr_div (e1, e2) -> free e1 || free e2 | Expr_mod (e1, e2) -> free e1 || free e2 | Expr_neg (e1) -> free e1 | Expr_lognot (e1) -> free e1 | Expr_boolnot (e1) -> free e1 | Expr_deref (e1) -> free e1 | Expr_addressof (e1) -> free e1 | Expr_cast (ty, e1) -> free e1 | Expr_sizeof ty -> false | Expr_subscript (e1, e2) -> free e1 || free e2 | Expr_dereffield (e1, s) -> free e1 | Expr_field (e1, s) -> free e1 in free e let is_free_opt v opte = match opte with None -> false | Some e -> is_free v e let rec is_dependent v ty = match ty with Type_array(attr, ty) -> is_free_opt v attr.size || is_free_opt v attr.length || is_dependent v ty | Type_bigarray(attr, ty) -> List.exists (fun a -> is_free_opt v a.size || is_free_opt v a.length) attr.dims || is_dependent v ty | Type_union(name, attr) -> is_free v attr.discriminant | Type_pointer(_, ty) -> is_dependent v ty | Type_const ty -> is_dependent v ty | _ -> false
22f8991c5e074ccd7af9907c51f23cccc421d75b42c6483a5974f2828cb6d522
nmeum/edward
buffer.scm
(import (edward buffer)) (define (test-buffer name expected proc) (test name expected (let ((b (make-buffer))) (proc b) (buffer->list b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (test-group "append" (test-buffer "append start" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")))) (test-buffer "append between" '("foo" "baz" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-append! b 1 '("baz")))) (test-buffer "append at end" '("foo" "123") (lambda (b) (buffer-append! b 0 '("foo")) (buffer-append! b 1 '("123"))))) (test-group "remove" (test-buffer "remove start full" '() (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-remove! b 0 2))) (test-buffer "remove start partial" '("bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-remove! b 0 1))) (test-buffer "remove between" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "baz" "bar")) (buffer-remove! b 2 2))) (test-buffer "remove last" '("foo" "baz") (lambda (b) (buffer-append! b 0 '("foo" "baz" "bar")) (buffer-remove! b 3 3)))) (test-group "replace command" (test-buffer "replace single line" '("foo" "345" "bar") (lambda (b) (buffer-append! b 0 '("foo" "123" "bar")) (buffer-replace! b 2 2 '("345")))) (test-buffer "replace multiple lines" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("1" "2")) (buffer-replace! b 1 2 '("foo" "bar")))) (test-buffer "replace add lines" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "test test")) (buffer-replace! b 2 2 '("bar" "baz")))) (test-buffer "buffer replace everything" '() (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-replace! b 1 3 '())))) (test-group "join command" (test-buffer "join entire buffer" '("foobar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-join! b 0 2))) (test-buffer "join keep last" '("foobar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-join! b 1 2))) (test-buffer "join keep first" '("foo" "barbaz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-join! b 2 3))) (test-buffer "join betwen" '("foo" "123" "bar") (lambda (b) (buffer-append! b 0 '("foo" "1" "2" "3" "bar")) (buffer-join! b 2 4)))) (test-group "move command" (test-buffer "move to end" '("bar" "baz" "foo") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 2 3 0))) (test-buffer "move to start" '("baz" "foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 1 2 3))) (test-buffer "move single to middle" '("foo" "123" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar" "123")) (buffer-move! b 3 3 1))) (test-buffer "move multiple after destination" '("foo" "bar" "---" "t1" "t2" "end") (lambda (b) (buffer-append! b 0 '("foo" "t1" "t2" "bar" "---" "end")) (buffer-move! b 2 3 5))) (test-buffer "move multiple before destination" '("foo" "t1" "t2" "bar" "---" "end") (lambda (b) (buffer-append! b 0 '("foo" "bar" "---" "t1" "t2" "end")) (buffer-move! b 4 5 1))) (test-buffer "move everything" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 1 3 0)))) (test-group "undo command" (test-buffer "undo append" '() (lambda (b) (buffer-with-undo b (lambda () (buffer-append! b 0 '("foo" "bar")))) (buffer-undo! b))) (test-buffer "undo remove" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-with-undo b (lambda () (buffer-remove! b 2 3))) (buffer-undo! b))) (test-buffer "undo undo" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-undo! b) ;; undo append (buffer-undo! b))) ;; undo undo (test-buffer "undo replace" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 1 2 '("first" "second")))) (buffer-undo! b))) (test-buffer "undo append last" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-append! b 2 '("second line")))) (buffer-undo! b))) (test-buffer "undo replace last" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 2 2 '("second line")))) (buffer-undo! b))) (test-buffer "undo replace undo" '("test" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 1 1 '("test")) (buffer-undo! b) )) ;; undo replace (buffer-undo! b))) ;; undo undo (test-buffer "undo replace nothing" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 0 0 '()))) (buffer-undo! b))) (test-buffer "undo join" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-join! b 0 2))) (buffer-undo! b))) (test-buffer "undo multiple" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-append! b 0 '("1")) (buffer-append! b 0 '("2")) (buffer-replace! b 0 0 '("0")))) (buffer-undo! b))) (test-buffer "undo move" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-with-undo b (lambda () (buffer-move! b 2 3 0))) (buffer-undo! b))) (test "empty undo buffer" #f (let ((b (make-buffer))) (buffer-has-undo? b))) (test "operation without buffer-undo" #f (let ((b (make-buffer))) (buffer-append! b 0 '("foo" "bar")) (buffer-has-undo? b))) (test "non-empty undo buffer" #t (let ((b (make-buffer))) (buffer-with-undo b (lambda () (buffer-append! b 0 '("foo" "bar" "baz")))) (buffer-has-undo? b))))
null
https://raw.githubusercontent.com/nmeum/edward/035166ba90055c93b24efe0d4535636a6169250c/tests/buffer.scm
scheme
undo append undo undo undo replace undo undo
(import (edward buffer)) (define (test-buffer name expected proc) (test name expected (let ((b (make-buffer))) (proc b) (buffer->list b)))) (test-group "append" (test-buffer "append start" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")))) (test-buffer "append between" '("foo" "baz" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-append! b 1 '("baz")))) (test-buffer "append at end" '("foo" "123") (lambda (b) (buffer-append! b 0 '("foo")) (buffer-append! b 1 '("123"))))) (test-group "remove" (test-buffer "remove start full" '() (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-remove! b 0 2))) (test-buffer "remove start partial" '("bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-remove! b 0 1))) (test-buffer "remove between" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "baz" "bar")) (buffer-remove! b 2 2))) (test-buffer "remove last" '("foo" "baz") (lambda (b) (buffer-append! b 0 '("foo" "baz" "bar")) (buffer-remove! b 3 3)))) (test-group "replace command" (test-buffer "replace single line" '("foo" "345" "bar") (lambda (b) (buffer-append! b 0 '("foo" "123" "bar")) (buffer-replace! b 2 2 '("345")))) (test-buffer "replace multiple lines" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("1" "2")) (buffer-replace! b 1 2 '("foo" "bar")))) (test-buffer "replace add lines" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "test test")) (buffer-replace! b 2 2 '("bar" "baz")))) (test-buffer "buffer replace everything" '() (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-replace! b 1 3 '())))) (test-group "join command" (test-buffer "join entire buffer" '("foobar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-join! b 0 2))) (test-buffer "join keep last" '("foobar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-join! b 1 2))) (test-buffer "join keep first" '("foo" "barbaz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-join! b 2 3))) (test-buffer "join betwen" '("foo" "123" "bar") (lambda (b) (buffer-append! b 0 '("foo" "1" "2" "3" "bar")) (buffer-join! b 2 4)))) (test-group "move command" (test-buffer "move to end" '("bar" "baz" "foo") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 2 3 0))) (test-buffer "move to start" '("baz" "foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 1 2 3))) (test-buffer "move single to middle" '("foo" "123" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar" "123")) (buffer-move! b 3 3 1))) (test-buffer "move multiple after destination" '("foo" "bar" "---" "t1" "t2" "end") (lambda (b) (buffer-append! b 0 '("foo" "t1" "t2" "bar" "---" "end")) (buffer-move! b 2 3 5))) (test-buffer "move multiple before destination" '("foo" "t1" "t2" "bar" "---" "end") (lambda (b) (buffer-append! b 0 '("foo" "bar" "---" "t1" "t2" "end")) (buffer-move! b 4 5 1))) (test-buffer "move everything" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-move! b 1 3 0)))) (test-group "undo command" (test-buffer "undo append" '() (lambda (b) (buffer-with-undo b (lambda () (buffer-append! b 0 '("foo" "bar")))) (buffer-undo! b))) (test-buffer "undo remove" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-with-undo b (lambda () (buffer-remove! b 2 3))) (buffer-undo! b))) (test-buffer "undo undo" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (test-buffer "undo replace" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 1 2 '("first" "second")))) (buffer-undo! b))) (test-buffer "undo append last" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-append! b 2 '("second line")))) (buffer-undo! b))) (test-buffer "undo replace last" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 2 2 '("second line")))) (buffer-undo! b))) (test-buffer "undo replace undo" '("test" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 1 1 '("test")) (test-buffer "undo replace nothing" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-replace! b 0 0 '()))) (buffer-undo! b))) (test-buffer "undo join" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-join! b 0 2))) (buffer-undo! b))) (test-buffer "undo multiple" '("foo" "bar") (lambda (b) (buffer-append! b 0 '("foo" "bar")) (buffer-with-undo b (lambda () (buffer-append! b 0 '("1")) (buffer-append! b 0 '("2")) (buffer-replace! b 0 0 '("0")))) (buffer-undo! b))) (test-buffer "undo move" '("foo" "bar" "baz") (lambda (b) (buffer-append! b 0 '("foo" "bar" "baz")) (buffer-with-undo b (lambda () (buffer-move! b 2 3 0))) (buffer-undo! b))) (test "empty undo buffer" #f (let ((b (make-buffer))) (buffer-has-undo? b))) (test "operation without buffer-undo" #f (let ((b (make-buffer))) (buffer-append! b 0 '("foo" "bar")) (buffer-has-undo? b))) (test "non-empty undo buffer" #t (let ((b (make-buffer))) (buffer-with-undo b (lambda () (buffer-append! b 0 '("foo" "bar" "baz")))) (buffer-has-undo? b))))
1b44e1e3188430aa179226ffcbbffef47b6eb0cd53963fca5fd18dd1845b14fd
ocaml-multicore/ocaml-tsan
odoc_class.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2001 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Representation and manipulation of classes and class types.*) module Name = Odoc_name type class_element = Class_attribute of Odoc_value.t_attribute | Class_method of Odoc_value.t_method | Class_comment of Odoc_types.text (** Used when we can reference t_class or t_class_type. *) type cct = Cl of t_class | Cltype of t_class_type * Types.type_expr list (** class type and type parameters *) and inherited_class = { ic_name : Name.t ; (** Complete name of the inherited class *) mutable ic_class : cct option ; (** The associated t_class or t_class_type *) ic_text : Odoc_types.text option ; (** The inheritance comment, if any *) } and class_apply = { capp_name : Name.t ; (** The complete name of the applied class *) mutable capp_class : t_class option; (** The associated t_class if we found it *) capp_params : Types.type_expr list; (** The type of expressions the class is applied to *) capp_params_code : string list ; (** The code of these expressions *) } and class_constr = { cco_name : Name.t ; (** The complete name of the applied class *) mutable cco_class : cct option; (** The associated class of the class type if we found it *) cco_type_parameters : Types.type_expr list; (** The type parameters of the class, if needed *) } and class_kind = Class_structure of inherited_class list * class_element list (** an explicit class structure, used in implementation and interface *) | Class_apply of class_apply (** application/alias of a class, used in implementation only *) | Class_constr of class_constr (** a class used to give the type of the defined class, instead of a structure, used in interface only. For example, it will be used with the name "M1.M2....tutu" when the class toto is defined like this : class toto : int -> tutu *) | Class_constraint of class_kind * class_type_kind (** A class definition with a constraint. *) (** Representation of a class. *) and t_class = { cl_name : Name.t ; (** Name of the class *) mutable cl_info : Odoc_types.info option ; (** The optional associated user information *) cl_type : Types.class_type ; cl_type_parameters : Types.type_expr list ; (** Type parameters *) cl_virtual : bool ; (** true = virtual *) mutable cl_kind : class_kind ; mutable cl_parameters : Odoc_parameter.parameter list ; mutable cl_loc : Odoc_types.location ; } and class_type_alias = { cta_name : Name.t ; mutable cta_class : cct option ; (** we can have a t_class or a t_class_type *) cta_type_parameters : Types.type_expr list ; (** the type parameters *) } and class_type_kind = Class_signature of inherited_class list * class_element list | Class_type of class_type_alias (** a class type eventually applied to type args *) (** Representation of a class type. *) and t_class_type = { clt_name : Name.t ; mutable clt_info : Odoc_types.info option ; (** The optional associated user information *) clt_type : Types.class_type ; clt_type_parameters : Types.type_expr list ; (** type parameters *) clt_virtual : bool ; (** true = virtual *) mutable clt_kind : class_type_kind ; mutable clt_loc : Odoc_types.location ; } let class_parameter_text_by_name cl label = match cl.cl_info with None -> None | Some i -> try let t = List.assoc label i.Odoc_types.i_params in Some t with Not_found -> None let rec class_elements ?(trans=true) cl = let rec iter_kind k = match k with Class_structure (_, elements) -> elements | Class_constraint (c_kind, _ct_kind) -> iter_kind c_kind FIXME : use c_kind or ct_kind ? For now , as ct_kind is not analyzed , we search inside c_kind class_type_elements ~trans : trans { clt_name = " " ; = None ; clt_type_parameters = [ ] ; clt_virtual = false ; clt_kind = ct_kind } For now, as ct_kind is not analyzed, we search inside c_kind class_type_elements ~trans: trans { clt_name = "" ; clt_info = None ; clt_type_parameters = [] ; clt_virtual = false ; clt_kind = ct_kind } *) | Class_apply capp -> ( match capp.capp_class with Some c when trans -> class_elements ~trans: trans c | _ -> [] ) | Class_constr cco -> ( match cco.cco_class with Some (Cl c) when trans -> class_elements ~trans: trans c | Some (Cltype (ct,_)) when trans -> class_type_elements ~trans: trans ct | _ -> [] ) in iter_kind cl.cl_kind and class_type_elements ?(trans=true) clt = match clt.clt_kind with Class_signature (_, elements) -> elements | Class_type { cta_class = Some (Cltype (ct, _)) } when trans -> class_type_elements ~trans ct | Class_type { cta_class = Some (Cl c) } when trans -> class_elements ~trans c | Class_type _ -> [] let class_attributes ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_attribute a -> acc @ [ a ] | _ -> acc ) [] (class_elements ~trans cl) let class_methods ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_method m -> acc @ [ m ] | _ -> acc ) [] (class_elements ~trans cl) let class_comments ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_comment t -> acc @ [ t ] | _ -> acc ) [] (class_elements ~trans cl) let class_update_parameters_text cl = let f p = Odoc_parameter.update_parameter_text (class_parameter_text_by_name cl) p in List.iter f cl.cl_parameters let class_type_attributes ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_attribute a -> acc @ [ a ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_methods ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_method m -> acc @ [ m ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_comments ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_comment m -> acc @ [ m ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_parameter_text_by_name clt label = match clt.clt_info with None -> None | Some i -> try let t = List.assoc label i.Odoc_types.i_params in Some t with Not_found -> None
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/ocamldoc/odoc_class.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Representation and manipulation of classes and class types. * Used when we can reference t_class or t_class_type. * class type and type parameters * Complete name of the inherited class * The associated t_class or t_class_type * The inheritance comment, if any * The complete name of the applied class * The associated t_class if we found it * The type of expressions the class is applied to * The code of these expressions * The complete name of the applied class * The associated class of the class type if we found it * The type parameters of the class, if needed * an explicit class structure, used in implementation and interface * application/alias of a class, used in implementation only * a class used to give the type of the defined class, instead of a structure, used in interface only. For example, it will be used with the name "M1.M2....tutu" when the class toto is defined like this : class toto : int -> tutu * A class definition with a constraint. * Representation of a class. * Name of the class * The optional associated user information * Type parameters * true = virtual * we can have a t_class or a t_class_type * the type parameters * a class type eventually applied to type args * Representation of a class type. * The optional associated user information * type parameters * true = virtual
, projet Cristal , INRIA Rocquencourt Copyright 2001 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the module Name = Odoc_name type class_element = Class_attribute of Odoc_value.t_attribute | Class_method of Odoc_value.t_method | Class_comment of Odoc_types.text type cct = Cl of t_class and inherited_class = { } and class_apply = { } and class_constr = { } and class_kind = Class_structure of inherited_class list * class_element list | Class_constraint of class_kind * class_type_kind and t_class = { cl_type : Types.class_type ; mutable cl_kind : class_kind ; mutable cl_parameters : Odoc_parameter.parameter list ; mutable cl_loc : Odoc_types.location ; } and class_type_alias = { cta_name : Name.t ; } and class_type_kind = Class_signature of inherited_class list * class_element list and t_class_type = { clt_name : Name.t ; clt_type : Types.class_type ; mutable clt_kind : class_type_kind ; mutable clt_loc : Odoc_types.location ; } let class_parameter_text_by_name cl label = match cl.cl_info with None -> None | Some i -> try let t = List.assoc label i.Odoc_types.i_params in Some t with Not_found -> None let rec class_elements ?(trans=true) cl = let rec iter_kind k = match k with Class_structure (_, elements) -> elements | Class_constraint (c_kind, _ct_kind) -> iter_kind c_kind FIXME : use c_kind or ct_kind ? For now , as ct_kind is not analyzed , we search inside c_kind class_type_elements ~trans : trans { clt_name = " " ; = None ; clt_type_parameters = [ ] ; clt_virtual = false ; clt_kind = ct_kind } For now, as ct_kind is not analyzed, we search inside c_kind class_type_elements ~trans: trans { clt_name = "" ; clt_info = None ; clt_type_parameters = [] ; clt_virtual = false ; clt_kind = ct_kind } *) | Class_apply capp -> ( match capp.capp_class with Some c when trans -> class_elements ~trans: trans c | _ -> [] ) | Class_constr cco -> ( match cco.cco_class with Some (Cl c) when trans -> class_elements ~trans: trans c | Some (Cltype (ct,_)) when trans -> class_type_elements ~trans: trans ct | _ -> [] ) in iter_kind cl.cl_kind and class_type_elements ?(trans=true) clt = match clt.clt_kind with Class_signature (_, elements) -> elements | Class_type { cta_class = Some (Cltype (ct, _)) } when trans -> class_type_elements ~trans ct | Class_type { cta_class = Some (Cl c) } when trans -> class_elements ~trans c | Class_type _ -> [] let class_attributes ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_attribute a -> acc @ [ a ] | _ -> acc ) [] (class_elements ~trans cl) let class_methods ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_method m -> acc @ [ m ] | _ -> acc ) [] (class_elements ~trans cl) let class_comments ?(trans=true) cl = List.fold_left (fun acc -> fun ele -> match ele with Class_comment t -> acc @ [ t ] | _ -> acc ) [] (class_elements ~trans cl) let class_update_parameters_text cl = let f p = Odoc_parameter.update_parameter_text (class_parameter_text_by_name cl) p in List.iter f cl.cl_parameters let class_type_attributes ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_attribute a -> acc @ [ a ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_methods ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_method m -> acc @ [ m ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_comments ?(trans=true) clt = List.fold_left (fun acc -> fun ele -> match ele with Class_comment m -> acc @ [ m ] | _ -> acc ) [] (class_type_elements ~trans clt) let class_type_parameter_text_by_name clt label = match clt.clt_info with None -> None | Some i -> try let t = List.assoc label i.Odoc_types.i_params in Some t with Not_found -> None
7644e5af374ade6f79e1492b5448c5aa4784e12f408a2350e0647a038f6de6c8
samcoy3/advent-of-code-template
Day22.hs
module Days.Day22 (runDay) where {- ORMOLU_DISABLE -} import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Vector (Vector) import qualified Data.Vector as Vec import qualified Util.Util as U import qualified Program.RunDay as R (runDay, Day) import Data.Attoparsec.Text import Data.Void ORMOLU_ENABLE runDay :: R.Day runDay = R.runDay inputParser partA partB ------------ PARSER ------------ inputParser :: Parser Input inputParser = error "Not implemented yet!" ---------- TYPES ------------ type Input = Void type OutputA = Void type OutputB = Void ------------ PART A ------------ partA :: Input -> OutputA partA = error "Not implemented yet!" ------------ PART B ------------ partB :: Input -> OutputB partB = error "Not implemented yet!"
null
https://raw.githubusercontent.com/samcoy3/advent-of-code-template/ddc27cfd7ca36d6ebf0df2a2297347d02ee0f1a6/src/Days/Day22.hs
haskell
ORMOLU_DISABLE ---------- PARSER ------------ -------- TYPES ------------ ---------- PART A ------------ ---------- PART B ------------
module Days.Day22 (runDay) where import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Vector (Vector) import qualified Data.Vector as Vec import qualified Util.Util as U import qualified Program.RunDay as R (runDay, Day) import Data.Attoparsec.Text import Data.Void ORMOLU_ENABLE runDay :: R.Day runDay = R.runDay inputParser partA partB inputParser :: Parser Input inputParser = error "Not implemented yet!" type Input = Void type OutputA = Void type OutputB = Void partA :: Input -> OutputA partA = error "Not implemented yet!" partB :: Input -> OutputB partB = error "Not implemented yet!"
6897571fc48e523b09e08511dd9001173e4ecee21b351156cc0b86864b892125
soarlab/FPTaylor
example.ml
open Interval;; let _ = let a = {low=3.0;high=3.0} in let b = 1. /.$ a in printf_I "%f" a; print_newline(); printf_I "%f" b; print_newline (); Printf.printf "%e\n" (b.high -. b.low);;
null
https://raw.githubusercontent.com/soarlab/FPTaylor/efbbc83970fe3c9f4cb33fafbbe1050dd18749cd/INTERVAL/EXAMPLES/example.ml
ocaml
open Interval;; let _ = let a = {low=3.0;high=3.0} in let b = 1. /.$ a in printf_I "%f" a; print_newline(); printf_I "%f" b; print_newline (); Printf.printf "%e\n" (b.high -. b.low);;
f174acaabdb9734f1b016bb65817ae6e42733b3017960d2e072233387cfe917e
diku-dk/futhark
Interval.hs
{-# LANGUAGE OverloadedStrings #-} module Futhark.IR.Mem.Interval ( Interval (..), distributeOffset, expandOffset, intervalOverlap, selfOverlap, primBool, intervalPairs, justLeafExp, ) where import Data.Function (on) import Data.List (maximumBy, minimumBy, (\\)) import Futhark.Analysis.AlgSimplify qualified as AlgSimplify import Futhark.Analysis.PrimExp.Convert import Futhark.IR.Prop import Futhark.IR.Syntax hiding (Result) import Futhark.Util data Interval = Interval { lowerBound :: TPrimExp Int64 VName, numElements :: TPrimExp Int64 VName, stride :: TPrimExp Int64 VName } deriving (Show, Eq) instance FreeIn Interval where freeIn' (Interval lb ne st) = freeIn' lb <> freeIn' ne <> freeIn' st distributeOffset :: MonadFail m => AlgSimplify.SofP -> [Interval] -> m [Interval] distributeOffset [] interval = pure interval distributeOffset offset [] = fail $ "Cannot distribute offset " <> show offset <> " across empty interval" distributeOffset offset [Interval lb ne 1] = pure [Interval (lb + TPrimExp (AlgSimplify.sumToExp offset)) ne 1] distributeOffset offset (Interval lb ne st0 : is) | st <- AlgSimplify.Prod False [untyped st0], Just (before, quotient, after) <- focusMaybe (`AlgSimplify.maybeDivide` st) offset = distributeOffset (before <> after) $ Interval (lb + TPrimExp (AlgSimplify.sumToExp [quotient])) ne st0 : is | [st] <- AlgSimplify.simplify0 $ untyped st0, Just (before, quotient, after) <- focusMaybe (`AlgSimplify.maybeDivide` st) offset = distributeOffset (before <> after) $ Interval (lb + TPrimExp (AlgSimplify.sumToExp [quotient])) ne st0 : is | otherwise = do rest <- distributeOffset offset is pure $ Interval lb ne st0 : rest findMostComplexTerm :: AlgSimplify.SofP -> (AlgSimplify.Prod, AlgSimplify.SofP) findMostComplexTerm prods = let max_prod = maximumBy (compare `on` (length . AlgSimplify.atoms)) prods in (max_prod, prods \\ [max_prod]) findClosestStride :: [PrimExp VName] -> [Interval] -> (PrimExp VName, [PrimExp VName]) findClosestStride offset_term is = let strides = map (untyped . stride) is p = minimumBy ( compare `on` ( termDifferenceLength . minimumBy (compare `on` \s -> length (offset_term \\ AlgSimplify.atoms s)) . AlgSimplify.simplify0 ) ) strides in ( p, (offset_term \\) $ AlgSimplify.atoms $ minimumBy (compare `on` \s -> length (offset_term \\ AlgSimplify.atoms s)) $ AlgSimplify.simplify0 p ) where termDifferenceLength (AlgSimplify.Prod _ xs) = length (offset_term \\ xs) expandOffset :: AlgSimplify.SofP -> [Interval] -> Maybe AlgSimplify.SofP expandOffset [] _ = Nothing expandOffset offset i1 | (AlgSimplify.Prod b term_to_add, offset_rest) <- findMostComplexTerm offset, -- Find gnb find ( nb - b , ) target <- [AlgSimplify.Prod b $ closest_stride : first_term_divisor], -- g(nb-b) diff <- AlgSimplify.sumOfProducts $ AlgSimplify.sumToExp $ AlgSimplify.Prod b term_to_add : map AlgSimplify.negate target, -- gnb - gnb + gb = gnb - g(nb-b) replacement <- target <> diff -- gnb = g(nb-b) + gnb - gnb + gb = Just (replacement <> offset_rest) intervalOverlap :: [(VName, PrimExp VName)] -> Names -> Interval -> Interval -> Bool intervalOverlap less_thans non_negatives (Interval lb1 ne1 st1) (Interval lb2 ne2 st2) | st1 == st2, AlgSimplify.lessThanish less_thans non_negatives lb1 lb2, AlgSimplify.lessThanish less_thans non_negatives (lb1 + ne1 - 1) lb2 = False | st1 == st2, AlgSimplify.lessThanish less_thans non_negatives lb2 lb1, AlgSimplify.lessThanish less_thans non_negatives (lb2 + ne2 - 1) lb1 = False | otherwise = True primBool :: TPrimExp Bool VName -> Maybe Bool primBool p | Just (BoolValue b) <- evalPrimExp (const Nothing) $ untyped p = Just b | otherwise = Nothing intervalPairs :: [Interval] -> [Interval] -> [(Interval, Interval)] intervalPairs = intervalPairs' [] where intervalPairs' :: [(Interval, Interval)] -> [Interval] -> [Interval] -> [(Interval, Interval)] intervalPairs' acc [] [] = reverse acc intervalPairs' acc (i@(Interval lb _ st) : is) [] = intervalPairs' ((i, Interval lb 1 st) : acc) is [] intervalPairs' acc [] (i@(Interval lb _ st) : is) = intervalPairs' ((Interval lb 1 st, i) : acc) [] is intervalPairs' acc (i1@(Interval lb1 _ st1) : is1) (i2@(Interval lb2 _ st2) : is2) | st1 == st2 = intervalPairs' ((i1, i2) : acc) is1 is2 | otherwise = let res1 = intervalPairs' ((i1, Interval lb1 1 st1) : acc) is1 (i2 : is2) res2 = intervalPairs' ((Interval lb2 1 st2, i2) : acc) (i1 : is1) is2 in if length res1 <= length res2 then res1 else res2 -- | Returns true if the intervals are self-overlapping, meaning that for a -- given dimension d, the stride of d is larger than the aggregate spans of the -- lower dimensions. selfOverlap :: scope -> asserts -> [(VName, PrimExp VName)] -> [PrimExp VName] -> [Interval] -> Maybe Interval selfOverlap _ _ _ _ [_] = Nothing selfOverlap _ _ less_thans non_negatives' is | Just non_negatives <- namesFromList <$> mapM justLeafExp non_negatives' = -- TODO: Do we need to do something clever using some ranges of known values? let selfOverlap' acc (x : xs) = let interval_span = (lowerBound x + numElements x - 1) * stride x res = AlgSimplify.lessThanish less_thans non_negatives (AlgSimplify.simplify' acc) (AlgSimplify.simplify' $ stride x) in if res then selfOverlap' (acc + interval_span) xs else Just x selfOverlap' _ [] = Nothing in selfOverlap' 0 $ reverse is selfOverlap _ _ _ _ (x : _) = Just x selfOverlap _ _ _ _ [] = Nothing justLeafExp :: PrimExp VName -> Maybe VName justLeafExp (LeafExp v _) = Just v justLeafExp _ = Nothing
null
https://raw.githubusercontent.com/diku-dk/futhark/5b24fb6f8c227f8d9264982ec39a58fb16e07757/src/Futhark/IR/Mem/Interval.hs
haskell
# LANGUAGE OverloadedStrings # Find gnb g(nb-b) gnb - gnb + gb = gnb - g(nb-b) gnb = g(nb-b) + gnb - gnb + gb | Returns true if the intervals are self-overlapping, meaning that for a given dimension d, the stride of d is larger than the aggregate spans of the lower dimensions. TODO: Do we need to do something clever using some ranges of known values?
module Futhark.IR.Mem.Interval ( Interval (..), distributeOffset, expandOffset, intervalOverlap, selfOverlap, primBool, intervalPairs, justLeafExp, ) where import Data.Function (on) import Data.List (maximumBy, minimumBy, (\\)) import Futhark.Analysis.AlgSimplify qualified as AlgSimplify import Futhark.Analysis.PrimExp.Convert import Futhark.IR.Prop import Futhark.IR.Syntax hiding (Result) import Futhark.Util data Interval = Interval { lowerBound :: TPrimExp Int64 VName, numElements :: TPrimExp Int64 VName, stride :: TPrimExp Int64 VName } deriving (Show, Eq) instance FreeIn Interval where freeIn' (Interval lb ne st) = freeIn' lb <> freeIn' ne <> freeIn' st distributeOffset :: MonadFail m => AlgSimplify.SofP -> [Interval] -> m [Interval] distributeOffset [] interval = pure interval distributeOffset offset [] = fail $ "Cannot distribute offset " <> show offset <> " across empty interval" distributeOffset offset [Interval lb ne 1] = pure [Interval (lb + TPrimExp (AlgSimplify.sumToExp offset)) ne 1] distributeOffset offset (Interval lb ne st0 : is) | st <- AlgSimplify.Prod False [untyped st0], Just (before, quotient, after) <- focusMaybe (`AlgSimplify.maybeDivide` st) offset = distributeOffset (before <> after) $ Interval (lb + TPrimExp (AlgSimplify.sumToExp [quotient])) ne st0 : is | [st] <- AlgSimplify.simplify0 $ untyped st0, Just (before, quotient, after) <- focusMaybe (`AlgSimplify.maybeDivide` st) offset = distributeOffset (before <> after) $ Interval (lb + TPrimExp (AlgSimplify.sumToExp [quotient])) ne st0 : is | otherwise = do rest <- distributeOffset offset is pure $ Interval lb ne st0 : rest findMostComplexTerm :: AlgSimplify.SofP -> (AlgSimplify.Prod, AlgSimplify.SofP) findMostComplexTerm prods = let max_prod = maximumBy (compare `on` (length . AlgSimplify.atoms)) prods in (max_prod, prods \\ [max_prod]) findClosestStride :: [PrimExp VName] -> [Interval] -> (PrimExp VName, [PrimExp VName]) findClosestStride offset_term is = let strides = map (untyped . stride) is p = minimumBy ( compare `on` ( termDifferenceLength . minimumBy (compare `on` \s -> length (offset_term \\ AlgSimplify.atoms s)) . AlgSimplify.simplify0 ) ) strides in ( p, (offset_term \\) $ AlgSimplify.atoms $ minimumBy (compare `on` \s -> length (offset_term \\ AlgSimplify.atoms s)) $ AlgSimplify.simplify0 p ) where termDifferenceLength (AlgSimplify.Prod _ xs) = length (offset_term \\ xs) expandOffset :: AlgSimplify.SofP -> [Interval] -> Maybe AlgSimplify.SofP expandOffset [] _ = Nothing expandOffset offset i1 find ( nb - b , ) = Just (replacement <> offset_rest) intervalOverlap :: [(VName, PrimExp VName)] -> Names -> Interval -> Interval -> Bool intervalOverlap less_thans non_negatives (Interval lb1 ne1 st1) (Interval lb2 ne2 st2) | st1 == st2, AlgSimplify.lessThanish less_thans non_negatives lb1 lb2, AlgSimplify.lessThanish less_thans non_negatives (lb1 + ne1 - 1) lb2 = False | st1 == st2, AlgSimplify.lessThanish less_thans non_negatives lb2 lb1, AlgSimplify.lessThanish less_thans non_negatives (lb2 + ne2 - 1) lb1 = False | otherwise = True primBool :: TPrimExp Bool VName -> Maybe Bool primBool p | Just (BoolValue b) <- evalPrimExp (const Nothing) $ untyped p = Just b | otherwise = Nothing intervalPairs :: [Interval] -> [Interval] -> [(Interval, Interval)] intervalPairs = intervalPairs' [] where intervalPairs' :: [(Interval, Interval)] -> [Interval] -> [Interval] -> [(Interval, Interval)] intervalPairs' acc [] [] = reverse acc intervalPairs' acc (i@(Interval lb _ st) : is) [] = intervalPairs' ((i, Interval lb 1 st) : acc) is [] intervalPairs' acc [] (i@(Interval lb _ st) : is) = intervalPairs' ((Interval lb 1 st, i) : acc) [] is intervalPairs' acc (i1@(Interval lb1 _ st1) : is1) (i2@(Interval lb2 _ st2) : is2) | st1 == st2 = intervalPairs' ((i1, i2) : acc) is1 is2 | otherwise = let res1 = intervalPairs' ((i1, Interval lb1 1 st1) : acc) is1 (i2 : is2) res2 = intervalPairs' ((Interval lb2 1 st2, i2) : acc) (i1 : is1) is2 in if length res1 <= length res2 then res1 else res2 selfOverlap :: scope -> asserts -> [(VName, PrimExp VName)] -> [PrimExp VName] -> [Interval] -> Maybe Interval selfOverlap _ _ _ _ [_] = Nothing selfOverlap _ _ less_thans non_negatives' is | Just non_negatives <- namesFromList <$> mapM justLeafExp non_negatives' = let selfOverlap' acc (x : xs) = let interval_span = (lowerBound x + numElements x - 1) * stride x res = AlgSimplify.lessThanish less_thans non_negatives (AlgSimplify.simplify' acc) (AlgSimplify.simplify' $ stride x) in if res then selfOverlap' (acc + interval_span) xs else Just x selfOverlap' _ [] = Nothing in selfOverlap' 0 $ reverse is selfOverlap _ _ _ _ (x : _) = Just x selfOverlap _ _ _ _ [] = Nothing justLeafExp :: PrimExp VName -> Maybe VName justLeafExp (LeafExp v _) = Just v justLeafExp _ = Nothing
147e15b494e25b22c7f688e874cb1e4e9efb37924d277f276c273b86610003c1
bitemyapp/bloodhound
BHRequest.hs
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeFamilies # -- | -- Module : Database.Bloodhound.Client Copyright : ( C ) 2014 , 2018 -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : provisional Portability : GHC -- Client side abstractions to interact with Elasticsearch servers . module Database.Bloodhound.Internal.Client.BHRequest ( -- * Request BHRequest (..), mkFullRequest, mkSimpleRequest, Server (..), Endpoint (..), mkEndpoint, withQueries, getEndpoint, -- * Response BHResponse (..), -- * Response interpretation ParsedEsResponse, decodeResponse, eitherDecodeResponse, parseEsResponse, parseEsResponseWith, isVersionConflict, isSuccess, isCreated, statusCodeIs, -- * Response handling EsProtocolException (..), EsResult (..), EsResultFound (..), EsError (..), -- * Common results Acknowledged (..), Accepted (..), ) where import qualified Blaze.ByteString.Builder as BB import Control.Applicative as A import Control.Monad import Control.Monad.Catch import Data.Aeson import qualified Data.ByteString.Lazy as BL import Data.Ix import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Database.Bloodhound.Internal.Client.Doc import GHC.Exts import Network.HTTP.Client import qualified Network.HTTP.Types.Method as NHTM import qualified Network.HTTP.Types.Status as NHTS import qualified Network.HTTP.Types.URI as NHTU import Prelude hiding (filter, head) | ' Server ' is used with the client functions to point at the ES instance newtype Server = Server Text deriving stock (Eq, Show) deriving newtype (FromJSON) -- | 'Endpoint' represents an url before being built data Endpoint = Endpoint { getRawEndpoint :: [Text], getRawEndpointQueries :: [(Text, Maybe Text)] } deriving stock (Eq, Show) instance IsList Endpoint where type Item Endpoint = Text toList = getRawEndpoint fromList = mkEndpoint -- | Create an 'Endpoint' from a list of url parts mkEndpoint :: [Text] -> Endpoint mkEndpoint urlParts = Endpoint urlParts mempty -- | Generate the raw URL getEndpoint :: Server -> Endpoint -> Text getEndpoint (Server serverRoot) endpoint = T.intercalate "/" (serverRoot : getRawEndpoint endpoint) <> queries where queries = T.decodeUtf8 $ BB.toByteString $ NHTU.renderQueryText prependQuestionMark $ getRawEndpointQueries endpoint prependQuestionMark = True -- | Severely dumbed down query renderer. Assumes your data doesn't -- need any encoding withQueries :: Endpoint -> [(Text, Maybe Text)] -> Endpoint withQueries endpoint queries = endpoint {getRawEndpointQueries = getRawEndpointQueries endpoint <> queries} | ' Request ' upon Elasticsearch 's server . -- -- @responseBody@ is a phantom type for the expected result data BHRequest responseBody = BHRequest { bhRequestMethod :: NHTM.Method, bhRequestEndpoint :: Endpoint, bhRequestBody :: Maybe BL.ByteString } deriving stock (Eq, Show) -- | 'BHRequest' with a body mkFullRequest :: NHTM.Method -> Endpoint -> BL.ByteString -> BHRequest body mkFullRequest method' endpoint body = BHRequest { bhRequestMethod = method', bhRequestEndpoint = endpoint, bhRequestBody = Just body } | ' BHRequest ' without a body mkSimpleRequest :: NHTM.Method -> Endpoint -> BHRequest body mkSimpleRequest method' endpoint = BHRequest { bhRequestMethod = method', bhRequestEndpoint = endpoint, bhRequestBody = Nothing } | Result of a ' BHRequest ' newtype BHResponse body = BHResponse {getResponse :: Network.HTTP.Client.Response BL.ByteString} deriving stock (Show) -- | Result of a 'parseEsResponse' type ParsedEsResponse a = Either EsError a -- | Tries to parse a response body as the expected type @body@ and failing that tries to parse it as an EsError . All well - formed , JSON responses from elasticsearch should fall into these two -- categories. If they don't, a 'EsProtocolException' will be -- thrown. If you encounter this, please report the full body it reports along with your Elasticsearch version . parseEsResponse :: ( MonadThrow m, FromJSON body ) => BHResponse body -> m (ParsedEsResponse body) parseEsResponse response | isSuccess response = case eitherDecode body of Right a -> return (Right a) Left err -> tryParseError err | otherwise = tryParseError "Non-200 status code" where body = responseBody $ getResponse response tryParseError originalError = case eitherDecode body of Right e -> return (Left e) -- Failed to parse the error message. Left err -> explode ("Original error was: " <> originalError <> " Error parse failure was: " <> err) explode errorMsg = throwM $ EsProtocolException (T.pack errorMsg) body | Parse ' BHResponse ' with an arbitrary parser parseEsResponseWith :: ( MonadThrow m, FromJSON body ) => (body -> Either String parsed) -> BHResponse body -> m parsed parseEsResponseWith parser response = case eitherDecode body of Left e -> explode e Right parsed -> case parser parsed of Right a -> return a Left e -> explode e where body = responseBody $ getResponse response explode errorMsg = throwM $ EsProtocolException (T.pack errorMsg) body -- | Helper around 'aeson' 'decode' decodeResponse :: FromJSON a => BHResponse a -> Maybe a decodeResponse = decode . responseBody . getResponse -- | Helper around 'aeson' 'eitherDecode' eitherDecodeResponse :: FromJSON a => BHResponse a -> Either String a eitherDecodeResponse = eitherDecode . responseBody . getResponse -- | Was there an optimistic concurrency control conflict when -- indexing a document? isVersionConflict :: BHResponse a -> Bool isVersionConflict = statusCheck (== 409) | Check ' 2xx ' status codes isSuccess :: BHResponse a -> Bool isSuccess = statusCodeIs (200, 299) -- | Check '201' status code isCreated :: BHResponse a -> Bool isCreated = statusCheck (== 201) -- | Check status code statusCheck :: (Int -> Bool) -> BHResponse a -> Bool statusCheck prd = prd . NHTS.statusCode . responseStatus . getResponse -- | Check status code in range statusCodeIs :: (Int, Int) -> BHResponse body -> Bool statusCodeIs r resp = inRange r $ NHTS.statusCode (responseStatus $ getResponse resp) | ' ' describes the standard wrapper JSON document that you see in successful Elasticsearch lookups or lookups that could n't find the document . data EsResult a = EsResult { _index :: Text, _type :: Text, _id :: Text, foundResult :: Maybe (EsResultFound a) } deriving (Eq, Show) -- | 'EsResultFound' contains the document and its metadata inside of an ' ' when the document was successfully found . data EsResultFound a = EsResultFound { _version :: DocVersion, _source :: a } deriving (Eq, Show) instance (FromJSON a) => FromJSON (EsResult a) where parseJSON jsonVal@(Object v) = do found <- v .:? "found" .!= False fr <- if found then parseJSON jsonVal else return Nothing EsResult <$> v .: "_index" <*> v .: "_type" <*> v .: "_id" <*> pure fr parseJSON _ = empty instance (FromJSON a) => FromJSON (EsResultFound a) where parseJSON (Object v) = EsResultFound <$> v .: "_version" <*> v .: "_source" parseJSON _ = empty | ' EsError ' is the generic type that will be returned when there was a -- problem. If you can't parse the expected response, its a good idea to -- try parsing this. data EsError = EsError { errorStatus :: Int, errorMessage :: Text } deriving (Eq, Show) instance FromJSON EsError where parseJSON (Object v) = EsError <$> v .: "status" <*> (v .: "error" <|> (v .: "error" >>= (.: "reason"))) parseJSON _ = empty | ' EsProtocolException ' will be thrown if Bloodhound can not parse a response returned by the Elasticsearch server . If you encounter this error , please -- verify that your domain data types and FromJSON instances are working properly ( for example , the ' a ' of ' [ Hit a ] ' in ' SearchResult.searchHits.hits ' ) . If you 're -- sure that your mappings are correct, then this error may be an indication of an incompatibility between Bloodhound and Elasticsearch . Please open a bug report -- and be sure to include the exception body. data EsProtocolException = EsProtocolException { esProtoExMessage :: !Text, esProtoExResponse :: !BL.ByteString } deriving (Eq, Show) instance Exception EsProtocolException newtype Acknowledged = Acknowledged {isAcknowledged :: Bool} deriving stock (Eq, Show) instance FromJSON Acknowledged where parseJSON = withObject "Acknowledged" $ fmap Acknowledged . (.: "acknowledged") newtype Accepted = Accepted {isAccepted :: Bool} deriving stock (Eq, Show) instance FromJSON Accepted where parseJSON = withObject "Accepted" $ fmap Accepted . (.: "accepted")
null
https://raw.githubusercontent.com/bitemyapp/bloodhound/76a8c39860a6c1bbb8b86a19ef7b59a90d79798d/src/Database/Bloodhound/Internal/Client/BHRequest.hs
haskell
# LANGUAGE OverloadedStrings # | Module : Database.Bloodhound.Client License : BSD-style (see the file LICENSE) Stability : provisional * Request * Response * Response interpretation * Response handling * Common results | 'Endpoint' represents an url before being built | Create an 'Endpoint' from a list of url parts | Generate the raw URL | Severely dumbed down query renderer. Assumes your data doesn't need any encoding @responseBody@ is a phantom type for the expected result | 'BHRequest' with a body | Result of a 'parseEsResponse' | Tries to parse a response body as the expected type @body@ and categories. If they don't, a 'EsProtocolException' will be thrown. If you encounter this, please report the full body it Failed to parse the error message. | Helper around 'aeson' 'decode' | Helper around 'aeson' 'eitherDecode' | Was there an optimistic concurrency control conflict when indexing a document? | Check '201' status code | Check status code | Check status code in range | 'EsResultFound' contains the document and its metadata inside of an problem. If you can't parse the expected response, its a good idea to try parsing this. verify that your domain data types and FromJSON instances are working properly sure that your mappings are correct, then this error may be an indication of an and be sure to include the exception body.
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE TypeFamilies # Copyright : ( C ) 2014 , 2018 Maintainer : < > Portability : GHC Client side abstractions to interact with Elasticsearch servers . module Database.Bloodhound.Internal.Client.BHRequest BHRequest (..), mkFullRequest, mkSimpleRequest, Server (..), Endpoint (..), mkEndpoint, withQueries, getEndpoint, BHResponse (..), ParsedEsResponse, decodeResponse, eitherDecodeResponse, parseEsResponse, parseEsResponseWith, isVersionConflict, isSuccess, isCreated, statusCodeIs, EsProtocolException (..), EsResult (..), EsResultFound (..), EsError (..), Acknowledged (..), Accepted (..), ) where import qualified Blaze.ByteString.Builder as BB import Control.Applicative as A import Control.Monad import Control.Monad.Catch import Data.Aeson import qualified Data.ByteString.Lazy as BL import Data.Ix import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Database.Bloodhound.Internal.Client.Doc import GHC.Exts import Network.HTTP.Client import qualified Network.HTTP.Types.Method as NHTM import qualified Network.HTTP.Types.Status as NHTS import qualified Network.HTTP.Types.URI as NHTU import Prelude hiding (filter, head) | ' Server ' is used with the client functions to point at the ES instance newtype Server = Server Text deriving stock (Eq, Show) deriving newtype (FromJSON) data Endpoint = Endpoint { getRawEndpoint :: [Text], getRawEndpointQueries :: [(Text, Maybe Text)] } deriving stock (Eq, Show) instance IsList Endpoint where type Item Endpoint = Text toList = getRawEndpoint fromList = mkEndpoint mkEndpoint :: [Text] -> Endpoint mkEndpoint urlParts = Endpoint urlParts mempty getEndpoint :: Server -> Endpoint -> Text getEndpoint (Server serverRoot) endpoint = T.intercalate "/" (serverRoot : getRawEndpoint endpoint) <> queries where queries = T.decodeUtf8 $ BB.toByteString $ NHTU.renderQueryText prependQuestionMark $ getRawEndpointQueries endpoint prependQuestionMark = True withQueries :: Endpoint -> [(Text, Maybe Text)] -> Endpoint withQueries endpoint queries = endpoint {getRawEndpointQueries = getRawEndpointQueries endpoint <> queries} | ' Request ' upon Elasticsearch 's server . data BHRequest responseBody = BHRequest { bhRequestMethod :: NHTM.Method, bhRequestEndpoint :: Endpoint, bhRequestBody :: Maybe BL.ByteString } deriving stock (Eq, Show) mkFullRequest :: NHTM.Method -> Endpoint -> BL.ByteString -> BHRequest body mkFullRequest method' endpoint body = BHRequest { bhRequestMethod = method', bhRequestEndpoint = endpoint, bhRequestBody = Just body } | ' BHRequest ' without a body mkSimpleRequest :: NHTM.Method -> Endpoint -> BHRequest body mkSimpleRequest method' endpoint = BHRequest { bhRequestMethod = method', bhRequestEndpoint = endpoint, bhRequestBody = Nothing } | Result of a ' BHRequest ' newtype BHResponse body = BHResponse {getResponse :: Network.HTTP.Client.Response BL.ByteString} deriving stock (Show) type ParsedEsResponse a = Either EsError a failing that tries to parse it as an EsError . All well - formed , JSON responses from elasticsearch should fall into these two reports along with your Elasticsearch version . parseEsResponse :: ( MonadThrow m, FromJSON body ) => BHResponse body -> m (ParsedEsResponse body) parseEsResponse response | isSuccess response = case eitherDecode body of Right a -> return (Right a) Left err -> tryParseError err | otherwise = tryParseError "Non-200 status code" where body = responseBody $ getResponse response tryParseError originalError = case eitherDecode body of Right e -> return (Left e) Left err -> explode ("Original error was: " <> originalError <> " Error parse failure was: " <> err) explode errorMsg = throwM $ EsProtocolException (T.pack errorMsg) body | Parse ' BHResponse ' with an arbitrary parser parseEsResponseWith :: ( MonadThrow m, FromJSON body ) => (body -> Either String parsed) -> BHResponse body -> m parsed parseEsResponseWith parser response = case eitherDecode body of Left e -> explode e Right parsed -> case parser parsed of Right a -> return a Left e -> explode e where body = responseBody $ getResponse response explode errorMsg = throwM $ EsProtocolException (T.pack errorMsg) body decodeResponse :: FromJSON a => BHResponse a -> Maybe a decodeResponse = decode . responseBody . getResponse eitherDecodeResponse :: FromJSON a => BHResponse a -> Either String a eitherDecodeResponse = eitherDecode . responseBody . getResponse isVersionConflict :: BHResponse a -> Bool isVersionConflict = statusCheck (== 409) | Check ' 2xx ' status codes isSuccess :: BHResponse a -> Bool isSuccess = statusCodeIs (200, 299) isCreated :: BHResponse a -> Bool isCreated = statusCheck (== 201) statusCheck :: (Int -> Bool) -> BHResponse a -> Bool statusCheck prd = prd . NHTS.statusCode . responseStatus . getResponse statusCodeIs :: (Int, Int) -> BHResponse body -> Bool statusCodeIs r resp = inRange r $ NHTS.statusCode (responseStatus $ getResponse resp) | ' ' describes the standard wrapper JSON document that you see in successful Elasticsearch lookups or lookups that could n't find the document . data EsResult a = EsResult { _index :: Text, _type :: Text, _id :: Text, foundResult :: Maybe (EsResultFound a) } deriving (Eq, Show) ' ' when the document was successfully found . data EsResultFound a = EsResultFound { _version :: DocVersion, _source :: a } deriving (Eq, Show) instance (FromJSON a) => FromJSON (EsResult a) where parseJSON jsonVal@(Object v) = do found <- v .:? "found" .!= False fr <- if found then parseJSON jsonVal else return Nothing EsResult <$> v .: "_index" <*> v .: "_type" <*> v .: "_id" <*> pure fr parseJSON _ = empty instance (FromJSON a) => FromJSON (EsResultFound a) where parseJSON (Object v) = EsResultFound <$> v .: "_version" <*> v .: "_source" parseJSON _ = empty | ' EsError ' is the generic type that will be returned when there was a data EsError = EsError { errorStatus :: Int, errorMessage :: Text } deriving (Eq, Show) instance FromJSON EsError where parseJSON (Object v) = EsError <$> v .: "status" <*> (v .: "error" <|> (v .: "error" >>= (.: "reason"))) parseJSON _ = empty | ' EsProtocolException ' will be thrown if Bloodhound can not parse a response returned by the Elasticsearch server . If you encounter this error , please ( for example , the ' a ' of ' [ Hit a ] ' in ' SearchResult.searchHits.hits ' ) . If you 're incompatibility between Bloodhound and Elasticsearch . Please open a bug report data EsProtocolException = EsProtocolException { esProtoExMessage :: !Text, esProtoExResponse :: !BL.ByteString } deriving (Eq, Show) instance Exception EsProtocolException newtype Acknowledged = Acknowledged {isAcknowledged :: Bool} deriving stock (Eq, Show) instance FromJSON Acknowledged where parseJSON = withObject "Acknowledged" $ fmap Acknowledged . (.: "acknowledged") newtype Accepted = Accepted {isAccepted :: Bool} deriving stock (Eq, Show) instance FromJSON Accepted where parseJSON = withObject "Accepted" $ fmap Accepted . (.: "accepted")
37c778a40f8d06e3b570e62c178419f94513a2b99d7ff5247fb5824d9ccebf76
AbstractMachinesLab/caramel
btype.ml
(**************************************************************************) (* *) (* OCaml *) (* *) and , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Basic operations on core types *) open Misc open Asttypes open Types (**** Sets, maps and hashtables of types ****) module TypeSet = Set.Make(TypeOps) module TypeMap = Map.Make (TypeOps) module TypeHash = Hashtbl.Make(TypeOps) (**** Forward declarations ****) let print_raw = ref (fun _ -> assert false : Format.formatter -> type_expr -> unit) (**** Type level management ****) let generic_level = 100000000 (* Used to mark a type during a traversal. *) let lowest_level = 0 let pivot_level = 2 * lowest_level - 1 (* pivot_level - lowest_level < lowest_level *) (**** Some type creators ****) let new_id = ref (-1) let newty2 level desc = incr new_id; { desc; level; id = !new_id } let newgenty desc = newty2 generic_level desc let newgenvar ?name () = newgenty (Tvar name) let newmarkedvar level = incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id } let ( ) = incr new_id ; { desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id } let newmarkedvar level = incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id } let newmarkedgenvar () = incr new_id; { desc = Tvar; level = pivot_level - generic_level; id = !new_id } *) (**** Check some types ****) let is_Tvar = function {desc=Tvar _} -> true | _ -> false let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false let dummy_method = "*dummy method*" let default_mty = function Some mty -> mty | None -> Mty_signature [] (**** Definitions for backtracking ****) type change = Ctype of type_expr * type_desc | Ccompress of type_expr * type_desc * type_desc | Clevel of type_expr * int | Cname of (Path.t * type_expr list) option ref * (Path.t * type_expr list) option | Crow of row_field option ref * row_field option | Ckind of field_kind option ref * field_kind option | Ccommu of commutable ref * commutable | Cuniv of type_expr option ref * type_expr option | Ctypeset of TypeSet.t ref * TypeSet.t type changes = Change of change * changes ref | Unchanged | Invalid let trail = Weak.create 1 let log_change ch = match Weak.get trail 0 with None -> () | Some r -> let r' = ref Unchanged in r := Change (ch, r'); Weak.set trail 0 (Some r') (**** Representative of a type ****) let rec field_kind_repr = function Fvar {contents = Some kind} -> field_kind_repr kind | kind -> kind let rec repr_link compress t d = function {desc = Tlink t' as d'} -> repr_link true t d' t' | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent -> repr_link true t d' t' | t' -> if compress then begin log_change (Ccompress (t, t.desc, d)); t.desc <- d end; t' let repr t = match t.desc with Tlink t' as d -> repr_link false t d t' | Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent -> repr_link false t d t' | _ -> t let rec commu_repr = function Clink r when !r <> Cunknown -> commu_repr !r | c -> c let rec row_field_repr_aux tl = function Reither(_, tl', _, {contents = Some fi}) -> row_field_repr_aux (tl@tl') fi | Reither(c, tl', m, r) -> Reither(c, tl@tl', m, r) | Rpresent (Some _) when tl <> [] -> Rpresent (Some (List.hd tl)) | fi -> fi let row_field_repr fi = row_field_repr_aux [] fi let rec rev_concat l ll = match ll with [] -> l | l'::ll -> rev_concat (l'@l) ll let rec row_repr_aux ll row = match (repr row.row_more).desc with | Tvariant row' -> let f = row.row_fields in row_repr_aux (if f = [] then ll else f::ll) row' | _ -> if ll = [] then row else {row with row_fields = rev_concat row.row_fields ll} let row_repr row = row_repr_aux [] row let rec row_field tag row = let rec find = function | (tag',f) :: fields -> if tag = tag' then row_field_repr f else find fields | [] -> match repr row.row_more with | {desc=Tvariant row'} -> row_field tag row' | _ -> Rabsent in find row.row_fields let rec row_more row = match repr row.row_more with | {desc=Tvariant row'} -> row_more row' | ty -> ty let row_fixed row = let row = row_repr row in row.row_fixed || match (repr row.row_more).desc with Tvar _ | Tnil -> false | Tunivar _ | Tconstr _ -> true | _ -> assert false let static_row row = let row = row_repr row in row.row_closed && List.for_all (fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true) row.row_fields let hash_variant s = let accu = ref 0 in for i = 0 to String.length s - 1 do accu := 223 * !accu + Char.code s.[i] done; reduce to 31 bits accu := !accu land (1 lsl 31 - 1); make it signed for 64 bits architectures if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu let proxy ty = let ty0 = repr ty in match ty0.desc with | Tvariant row when not (static_row row) -> row_more row | Tobject (ty, _) -> let rec proxy_obj ty = match ty.desc with Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty | Tvar _ | Tunivar _ | Tconstr _ -> ty | Tnil -> ty0 | _ -> assert false in proxy_obj ty | _ -> ty0 (**** Utilities for fixed row private types ****) let has_constr_row t = match (repr t).desc with Tobject(t,_) -> let rec check_row t = match (repr t).desc with Tfield(_,_,_,t) -> check_row t | Tconstr _ -> true | _ -> false in check_row t | Tvariant row -> (match row_more row with {desc=Tconstr _} -> true | _ -> false) | _ -> false let is_row_name s = let l = String.length s in if l < 4 then false else String.sub s (l-4) 4 = "#row" let is_constr_row t = match t.desc with Tconstr (Path.Pident id, _, _) -> is_row_name (Ident.name id) | Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s | _ -> false (**********************************) Utilities for type traversal (**********************************) let rec iter_row f row = List.iter (fun (_, fi) -> match row_field_repr fi with | Rpresent(Some ty) -> f ty | Reither(_, tl, _, _) -> List.iter f tl | _ -> ()) row.row_fields; match (repr row.row_more).desc with Tvariant row -> iter_row f row | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil -> Misc.may (fun (_,l) -> List.iter f l) row.row_name | _ -> assert false let iter_type_expr f ty = match ty.desc with Tvar _ -> () | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2 | Ttuple l -> List.iter f l | Tconstr (_, l, _) -> List.iter f l | Tobject(ty, {contents = Some (_, p)}) -> f ty; List.iter f p | Tobject (ty, _) -> f ty | Tvariant row -> iter_row f row; f (row_more row) | Tfield (_, _, ty1, ty2) -> f ty1; f ty2 | Tnil -> () | Tlink ty -> f ty | Tsubst ty -> f ty | Tunivar _ -> () | Tpoly (ty, tyl) -> f ty; List.iter f tyl | Tpackage (_, _, l) -> List.iter f l let rec iter_abbrev f = function Mnil -> () | Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem | Mlink rem -> iter_abbrev f !rem type type_iterators = { it_signature: type_iterators -> signature -> unit; it_signature_item: type_iterators -> signature_item -> unit; it_value_description: type_iterators -> value_description -> unit; it_type_declaration: type_iterators -> type_declaration -> unit; it_extension_constructor: type_iterators -> extension_constructor -> unit; it_module_declaration: type_iterators -> module_declaration -> unit; it_modtype_declaration: type_iterators -> modtype_declaration -> unit; it_class_declaration: type_iterators -> class_declaration -> unit; it_class_type_declaration: type_iterators -> class_type_declaration -> unit; it_module_type: type_iterators -> module_type -> unit; it_class_type: type_iterators -> class_type -> unit; it_type_kind: type_iterators -> type_kind -> unit; it_do_type_expr: type_iterators -> type_expr -> unit; it_type_expr: type_iterators -> type_expr -> unit; it_path: Path.t -> unit; } let iter_type_expr_cstr_args f = function | Cstr_tuple tl -> List.iter f tl | Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls let map_type_expr_cstr_args f = function | Cstr_tuple tl -> Cstr_tuple (List.map f tl) | Cstr_record lbls -> Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls) let iter_type_expr_kind f = function | Type_abstract -> () | Type_variant cstrs -> List.iter (fun cd -> iter_type_expr_cstr_args f cd.cd_args; Misc.may f cd.cd_res ) cstrs | Type_record(lbls, _) -> List.iter (fun d -> f d.ld_type) lbls | Type_open -> () let type_iterators = let it_signature it = List.iter (it.it_signature_item it) and it_signature_item it = function Sig_value (_, vd) -> it.it_value_description it vd | Sig_type (_, td, _) -> it.it_type_declaration it td | Sig_typext (_, td, _) -> it.it_extension_constructor it td | Sig_module (_, md, _) -> it.it_module_declaration it md | Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd | Sig_class (_, cd, _) -> it.it_class_declaration it cd | Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd and it_value_description it vd = it.it_type_expr it vd.val_type and it_type_declaration it td = List.iter (it.it_type_expr it) td.type_params; may (it.it_type_expr it) td.type_manifest; it.it_type_kind it td.type_kind and it_extension_constructor it td = it.it_path td.ext_type_path; List.iter (it.it_type_expr it) td.ext_type_params; iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args; may (it.it_type_expr it) td.ext_ret_type and it_module_declaration it md = it.it_module_type it md.md_type and it_modtype_declaration it mtd = may (it.it_module_type it) mtd.mtd_type and it_class_declaration it cd = List.iter (it.it_type_expr it) cd.cty_params; it.it_class_type it cd.cty_type; may (it.it_type_expr it) cd.cty_new; it.it_path cd.cty_path and it_class_type_declaration it ctd = List.iter (it.it_type_expr it) ctd.clty_params; it.it_class_type it ctd.clty_type; it.it_path ctd.clty_path and it_module_type it = function Mty_ident p | Mty_alias p -> it.it_path p | Mty_signature sg -> it.it_signature it sg | Mty_functor (_, mto, mt) -> may (it.it_module_type it) mto; it.it_module_type it mt and it_class_type it = function Cty_constr (p, tyl, cty) -> it.it_path p; List.iter (it.it_type_expr it) tyl; it.it_class_type it cty | Cty_signature cs -> it.it_type_expr it cs.csig_self; Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars; List.iter (fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl) cs.csig_inher | Cty_arrow (_, ty, cty) -> it.it_type_expr it ty; it.it_class_type it cty and it_type_kind it kind = iter_type_expr_kind (it.it_type_expr it) kind and it_do_type_expr it ty = iter_type_expr (it.it_type_expr it) ty; match ty.desc with Tconstr (p, _, _) | Tobject (_, {contents=Some (p, _)}) | Tpackage (p, _, _) -> it.it_path p | Tvariant row -> may (fun (p,_) -> it.it_path p) (row_repr row).row_name | _ -> () and it_path p = () in { it_path; it_type_expr = it_do_type_expr; it_do_type_expr; it_type_kind; it_class_type; it_module_type; it_signature; it_class_type_declaration; it_class_declaration; it_modtype_declaration; it_module_declaration; it_extension_constructor; it_type_declaration; it_value_description; it_signature_item; } let copy_row f fixed row keep more = let fields = List.map (fun (l, fi) -> l, match row_field_repr fi with | Rpresent(Some ty) -> Rpresent(Some(f ty)) | Reither(c, tl, m, e) -> let e = if keep then e else ref None in let m = if row.row_fixed then fixed else m in let tl = List.map f tl in Reither(c, tl, m, e) | _ -> fi) row.row_fields in let name = match row.row_name with None -> None | Some (path, tl) -> Some (path, List.map f tl) in { row_fields = fields; row_more = more; row_bound = (); row_fixed = row.row_fixed && fixed; row_closed = row.row_closed; row_name = name; } let rec copy_kind = function Fvar{contents = Some k} -> copy_kind k | Fvar _ -> Fvar (ref None) | Fpresent -> Fpresent | Fabsent -> assert false let copy_commu c = if commu_repr c = Cok then Cok else Clink (ref Cunknown) (* Since univars may be used as row variables, we need to do some encoding during substitution *) let rec norm_univar ty = match ty.desc with Tunivar _ | Tsubst _ -> ty | Tlink ty -> norm_univar ty | Ttuple (ty :: _) -> norm_univar ty | _ -> assert false let rec copy_type_desc ?(keep_names=false) f = function Tvar _ as ty -> if keep_names then ty else Tvar None | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c) | Ttuple l -> Ttuple (List.map f l) | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil) | Tobject(ty, {contents = Some (p, tl)}) -> Tobject (f ty, ref (Some(p, List.map f tl))) | Tobject (ty, _) -> Tobject (f ty, ref None) | Tvariant row -> assert false (* too ambiguous *) | Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *) Tfield (p, field_kind_repr k, f ty1, f ty2) | Tnil -> Tnil | Tlink ty -> copy_type_desc f ty.desc | Tsubst ty -> assert false | Tunivar _ as ty -> ty (* always keep the name *) | Tpoly (ty, tyl) -> let tyl = List.map (fun x -> norm_univar (f x)) tyl in Tpoly (f ty, tyl) | Tpackage (p, n, l) -> Tpackage (p, n, List.map f l) Utilities for copying let saved_desc = ref [] (* Saved association of generic nodes with their description. *) let save_desc ty desc = saved_desc := (ty, desc)::!saved_desc let saved_kinds = ref [] (* duplicated kind variables *) let new_kinds = ref [] (* new kind variables *) let dup_kind r = (match !r with None -> () | Some _ -> assert false); if not (List.memq r !new_kinds) then begin saved_kinds := r :: !saved_kinds; let r' = ref None in new_kinds := r' :: !new_kinds; r := Some (Fvar r') end (* Restored type descriptions. *) let cleanup_types () = List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc; List.iter (fun r -> r := None) !saved_kinds; saved_desc := []; saved_kinds := []; new_kinds := [] (* Mark a type. *) let rec mark_type ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr mark_type ty end let mark_type_node ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; end let mark_type_params ty = iter_type_expr mark_type ty let type_iterators = let it_type_expr it ty = let ty = repr ty in if ty.level >= lowest_level then begin mark_type_node ty; it.it_do_type_expr it ty; end in {type_iterators with it_type_expr} (* Remove marks from a type. *) let rec unmark_type ty = let ty = repr ty in if ty.level < lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr unmark_type ty end let unmark_iterators = let it_type_expr it ty = unmark_type ty in {type_iterators with it_type_expr} let unmark_type_decl decl = unmark_iterators.it_type_declaration unmark_iterators decl let unmark_extension_constructor ext = List.iter unmark_type ext.ext_type_params; iter_type_expr_cstr_args unmark_type ext.ext_args; Misc.may unmark_type ext.ext_ret_type let unmark_class_signature sign = unmark_type sign.csig_self; Vars.iter (fun l (m, v, t) -> unmark_type t) sign.csig_vars let unmark_class_type cty = unmark_iterators.it_class_type unmark_iterators cty (*******************************************) (* Memorization of abbreviation expansion *) (*******************************************) (* Search whether the expansion has been memorized. *) let lte_public p1 p2 = (* Private <= Public *) match p1, p2 with | Private, _ | _, Public -> true | Public, Private -> false let rec find_expans priv p1 = function Mnil -> None | Mcons (priv', p2, ty0, ty, _) when lte_public priv priv' && Path.same p1 p2 -> Some ty | Mcons (_, _, _, _, rem) -> find_expans priv p1 rem | Mlink {contents = rem} -> find_expans priv p1 rem debug : check for cycles in abbreviation . only works with -principal let rec check_expans visited ty = let ty = repr ty in assert ( not ( visited ) ) ; match ty.desc with Tconstr ( path , args , abbrev ) - > begin match find_expans path ! abbrev with Some ty ' - > check_expans ( ty : : visited ) ty ' | None - > ( ) end | _ - > ( ) let rec check_expans visited ty = let ty = repr ty in assert (not (List.memq ty visited)); match ty.desc with Tconstr (path, args, abbrev) -> begin match find_expans path !abbrev with Some ty' -> check_expans (ty :: visited) ty' | None -> () end | _ -> () *) let memo = ref [] (* Contains the list of saved abbreviation expansions. *) let cleanup_abbrev () = (* Remove all memorized abbreviation expansions. *) List.iter (fun abbr -> abbr := Mnil) !memo; memo := [] let memorize_abbrev mem priv path v v' = (* Memorize the expansion of an abbreviation. *) mem := Mcons (priv, path, v, v', !mem); check_expans [ ] v ; memo := mem :: !memo let rec forget_abbrev_rec mem path = match mem with Mnil -> assert false | Mcons (_, path', _, _, rem) when Path.same path path' -> rem | Mcons (priv, path', v, v', rem) -> Mcons (priv, path', v, v', forget_abbrev_rec rem path) | Mlink mem' -> mem' := forget_abbrev_rec !mem' path; raise Exit let forget_abbrev mem path = try mem := forget_abbrev_rec !mem path with Exit -> () debug : check for invalid abbreviations let rec check_abbrev_rec = function Mnil - > true | Mcons ( _ , , ty2 , rem ) - > repr ! = repr ty2 | Mlink mem ' - > check_abbrev_rec ! ' let ( ) = List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo let rec check_abbrev_rec = function Mnil -> true | Mcons (_, ty1, ty2, rem) -> repr ty1 != repr ty2 | Mlink mem' -> check_abbrev_rec !mem' let check_memorized_abbrevs () = List.for_all (fun mem -> check_abbrev_rec !mem) !memo *) (**********************************) Utilities for labels (**********************************) let is_optional = function Optional _ -> true | _ -> false let label_name = function Nolabel -> "" | Labelled s | Optional s -> s let prefixed_label_name = function Nolabel -> "" | Labelled s -> "~" ^ s | Optional s -> "?" ^ s let rec extract_label_aux hd l = function [] -> raise Not_found | (l',t as p) :: ls -> if label_name l' = l then (l', t, List.rev hd, ls) else extract_label_aux (p::hd) l ls let extract_label l ls = extract_label_aux [] l ls (**********************************) Utilities for backtracking (**********************************) let undo_change = function Ctype (ty, desc) -> ty.desc <- desc | Ccompress (ty, desc, _) -> ty.desc <- desc | Clevel (ty, level) -> ty.level <- level | Cname (r, v) -> r := v | Crow (r, v) -> r := v | Ckind (r, v) -> r := v | Ccommu (r, v) -> r := v | Cuniv (r, v) -> r := v | Ctypeset (r, v) -> r := v type snapshot = changes ref * int let last_snapshot = ref 0 let log_type ty = if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc)) let link_type ty ty' = log_type ty; let desc = ty.desc in ty.desc <- Tlink ty'; (* Name is a user-supplied name for this unification variable (obtained * through a type annotation for instance). *) match desc, ty'.desc with Tvar name, Tvar name' -> begin match name, name' with | Some _, None -> log_type ty'; ty'.desc <- Tvar name | None, Some _ -> () | Some _, Some _ -> if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name) | None, None -> () end | _ -> () ; assert ( ( ) ) ; check_expans [ ] ty ' let set_level ty level = if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level)); ty.level <- level let set_univar rty ty = log_change (Cuniv (rty, !rty)); rty := Some ty let set_name nm v = log_change (Cname (nm, !nm)); nm := v let set_row_field e v = log_change (Crow (e, !e)); e := Some v let set_kind rk k = log_change (Ckind (rk, !rk)); rk := Some k let set_commu rc c = log_change (Ccommu (rc, !rc)); rc := c let set_typeset rs s = log_change (Ctypeset (rs, !rs)); rs := s let snapshot () = let old = !last_snapshot in last_snapshot := !new_id; match Weak.get trail 0 with Some r -> (r, old) | None -> let r = ref Unchanged in Weak.set trail 0 (Some r); (r, old) let rec rev_log accu = function Unchanged -> accu | Invalid -> assert false | Change (ch, next) -> let d = !next in next := Invalid; rev_log (ch::accu) d let backtrack (changes, old) = match !changes with Unchanged -> last_snapshot := old | Invalid -> failwith "Btype.backtrack" | Change _ as change -> cleanup_abbrev (); let backlog = rev_log [] change in List.iter undo_change backlog; changes := Unchanged; last_snapshot := old; Weak.set trail 0 (Some changes) let rec rev_compress_log log r = match !r with Unchanged | Invalid -> log | Change (Ccompress _, next) -> rev_compress_log (r::log) next | Change (_, next) -> rev_compress_log log next let undo_compress (changes, old) = match !changes with Unchanged | Invalid -> () | Change _ -> let log = rev_compress_log [] changes in List.iter (fun r -> match !r with Change (Ccompress (ty, desc, d), next) when ty.desc == d -> ty.desc <- desc; r := !next | _ -> ()) log
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/upstream/ocaml_403/typing/btype.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Basic operations on core types *** Sets, maps and hashtables of types *** *** Forward declarations *** *** Type level management *** Used to mark a type during a traversal. pivot_level - lowest_level < lowest_level *** Some type creators *** *** Check some types *** *** Definitions for backtracking *** *** Representative of a type *** *** Utilities for fixed row private types *** ******************************** ******************************** Since univars may be used as row variables, we need to do some encoding during substitution too ambiguous the kind is kept shared always keep the name Saved association of generic nodes with their description. duplicated kind variables new kind variables Restored type descriptions. Mark a type. Remove marks from a type. ***************************************** Memorization of abbreviation expansion ***************************************** Search whether the expansion has been memorized. Private <= Public Contains the list of saved abbreviation expansions. Remove all memorized abbreviation expansions. Memorize the expansion of an abbreviation. ******************************** ******************************** ******************************** ******************************** Name is a user-supplied name for this unification variable (obtained * through a type annotation for instance).
and , projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Misc open Asttypes open Types module TypeSet = Set.Make(TypeOps) module TypeMap = Map.Make (TypeOps) module TypeHash = Hashtbl.Make(TypeOps) let print_raw = ref (fun _ -> assert false : Format.formatter -> type_expr -> unit) let generic_level = 100000000 let lowest_level = 0 let pivot_level = 2 * lowest_level - 1 let new_id = ref (-1) let newty2 level desc = incr new_id; { desc; level; id = !new_id } let newgenty desc = newty2 generic_level desc let newgenvar ?name () = newgenty (Tvar name) let newmarkedvar level = incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id } let ( ) = incr new_id ; { desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id } let newmarkedvar level = incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id } let newmarkedgenvar () = incr new_id; { desc = Tvar; level = pivot_level - generic_level; id = !new_id } *) let is_Tvar = function {desc=Tvar _} -> true | _ -> false let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false let dummy_method = "*dummy method*" let default_mty = function Some mty -> mty | None -> Mty_signature [] type change = Ctype of type_expr * type_desc | Ccompress of type_expr * type_desc * type_desc | Clevel of type_expr * int | Cname of (Path.t * type_expr list) option ref * (Path.t * type_expr list) option | Crow of row_field option ref * row_field option | Ckind of field_kind option ref * field_kind option | Ccommu of commutable ref * commutable | Cuniv of type_expr option ref * type_expr option | Ctypeset of TypeSet.t ref * TypeSet.t type changes = Change of change * changes ref | Unchanged | Invalid let trail = Weak.create 1 let log_change ch = match Weak.get trail 0 with None -> () | Some r -> let r' = ref Unchanged in r := Change (ch, r'); Weak.set trail 0 (Some r') let rec field_kind_repr = function Fvar {contents = Some kind} -> field_kind_repr kind | kind -> kind let rec repr_link compress t d = function {desc = Tlink t' as d'} -> repr_link true t d' t' | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent -> repr_link true t d' t' | t' -> if compress then begin log_change (Ccompress (t, t.desc, d)); t.desc <- d end; t' let repr t = match t.desc with Tlink t' as d -> repr_link false t d t' | Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent -> repr_link false t d t' | _ -> t let rec commu_repr = function Clink r when !r <> Cunknown -> commu_repr !r | c -> c let rec row_field_repr_aux tl = function Reither(_, tl', _, {contents = Some fi}) -> row_field_repr_aux (tl@tl') fi | Reither(c, tl', m, r) -> Reither(c, tl@tl', m, r) | Rpresent (Some _) when tl <> [] -> Rpresent (Some (List.hd tl)) | fi -> fi let row_field_repr fi = row_field_repr_aux [] fi let rec rev_concat l ll = match ll with [] -> l | l'::ll -> rev_concat (l'@l) ll let rec row_repr_aux ll row = match (repr row.row_more).desc with | Tvariant row' -> let f = row.row_fields in row_repr_aux (if f = [] then ll else f::ll) row' | _ -> if ll = [] then row else {row with row_fields = rev_concat row.row_fields ll} let row_repr row = row_repr_aux [] row let rec row_field tag row = let rec find = function | (tag',f) :: fields -> if tag = tag' then row_field_repr f else find fields | [] -> match repr row.row_more with | {desc=Tvariant row'} -> row_field tag row' | _ -> Rabsent in find row.row_fields let rec row_more row = match repr row.row_more with | {desc=Tvariant row'} -> row_more row' | ty -> ty let row_fixed row = let row = row_repr row in row.row_fixed || match (repr row.row_more).desc with Tvar _ | Tnil -> false | Tunivar _ | Tconstr _ -> true | _ -> assert false let static_row row = let row = row_repr row in row.row_closed && List.for_all (fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true) row.row_fields let hash_variant s = let accu = ref 0 in for i = 0 to String.length s - 1 do accu := 223 * !accu + Char.code s.[i] done; reduce to 31 bits accu := !accu land (1 lsl 31 - 1); make it signed for 64 bits architectures if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu let proxy ty = let ty0 = repr ty in match ty0.desc with | Tvariant row when not (static_row row) -> row_more row | Tobject (ty, _) -> let rec proxy_obj ty = match ty.desc with Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty | Tvar _ | Tunivar _ | Tconstr _ -> ty | Tnil -> ty0 | _ -> assert false in proxy_obj ty | _ -> ty0 let has_constr_row t = match (repr t).desc with Tobject(t,_) -> let rec check_row t = match (repr t).desc with Tfield(_,_,_,t) -> check_row t | Tconstr _ -> true | _ -> false in check_row t | Tvariant row -> (match row_more row with {desc=Tconstr _} -> true | _ -> false) | _ -> false let is_row_name s = let l = String.length s in if l < 4 then false else String.sub s (l-4) 4 = "#row" let is_constr_row t = match t.desc with Tconstr (Path.Pident id, _, _) -> is_row_name (Ident.name id) | Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s | _ -> false Utilities for type traversal let rec iter_row f row = List.iter (fun (_, fi) -> match row_field_repr fi with | Rpresent(Some ty) -> f ty | Reither(_, tl, _, _) -> List.iter f tl | _ -> ()) row.row_fields; match (repr row.row_more).desc with Tvariant row -> iter_row f row | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil -> Misc.may (fun (_,l) -> List.iter f l) row.row_name | _ -> assert false let iter_type_expr f ty = match ty.desc with Tvar _ -> () | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2 | Ttuple l -> List.iter f l | Tconstr (_, l, _) -> List.iter f l | Tobject(ty, {contents = Some (_, p)}) -> f ty; List.iter f p | Tobject (ty, _) -> f ty | Tvariant row -> iter_row f row; f (row_more row) | Tfield (_, _, ty1, ty2) -> f ty1; f ty2 | Tnil -> () | Tlink ty -> f ty | Tsubst ty -> f ty | Tunivar _ -> () | Tpoly (ty, tyl) -> f ty; List.iter f tyl | Tpackage (_, _, l) -> List.iter f l let rec iter_abbrev f = function Mnil -> () | Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem | Mlink rem -> iter_abbrev f !rem type type_iterators = { it_signature: type_iterators -> signature -> unit; it_signature_item: type_iterators -> signature_item -> unit; it_value_description: type_iterators -> value_description -> unit; it_type_declaration: type_iterators -> type_declaration -> unit; it_extension_constructor: type_iterators -> extension_constructor -> unit; it_module_declaration: type_iterators -> module_declaration -> unit; it_modtype_declaration: type_iterators -> modtype_declaration -> unit; it_class_declaration: type_iterators -> class_declaration -> unit; it_class_type_declaration: type_iterators -> class_type_declaration -> unit; it_module_type: type_iterators -> module_type -> unit; it_class_type: type_iterators -> class_type -> unit; it_type_kind: type_iterators -> type_kind -> unit; it_do_type_expr: type_iterators -> type_expr -> unit; it_type_expr: type_iterators -> type_expr -> unit; it_path: Path.t -> unit; } let iter_type_expr_cstr_args f = function | Cstr_tuple tl -> List.iter f tl | Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls let map_type_expr_cstr_args f = function | Cstr_tuple tl -> Cstr_tuple (List.map f tl) | Cstr_record lbls -> Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls) let iter_type_expr_kind f = function | Type_abstract -> () | Type_variant cstrs -> List.iter (fun cd -> iter_type_expr_cstr_args f cd.cd_args; Misc.may f cd.cd_res ) cstrs | Type_record(lbls, _) -> List.iter (fun d -> f d.ld_type) lbls | Type_open -> () let type_iterators = let it_signature it = List.iter (it.it_signature_item it) and it_signature_item it = function Sig_value (_, vd) -> it.it_value_description it vd | Sig_type (_, td, _) -> it.it_type_declaration it td | Sig_typext (_, td, _) -> it.it_extension_constructor it td | Sig_module (_, md, _) -> it.it_module_declaration it md | Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd | Sig_class (_, cd, _) -> it.it_class_declaration it cd | Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd and it_value_description it vd = it.it_type_expr it vd.val_type and it_type_declaration it td = List.iter (it.it_type_expr it) td.type_params; may (it.it_type_expr it) td.type_manifest; it.it_type_kind it td.type_kind and it_extension_constructor it td = it.it_path td.ext_type_path; List.iter (it.it_type_expr it) td.ext_type_params; iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args; may (it.it_type_expr it) td.ext_ret_type and it_module_declaration it md = it.it_module_type it md.md_type and it_modtype_declaration it mtd = may (it.it_module_type it) mtd.mtd_type and it_class_declaration it cd = List.iter (it.it_type_expr it) cd.cty_params; it.it_class_type it cd.cty_type; may (it.it_type_expr it) cd.cty_new; it.it_path cd.cty_path and it_class_type_declaration it ctd = List.iter (it.it_type_expr it) ctd.clty_params; it.it_class_type it ctd.clty_type; it.it_path ctd.clty_path and it_module_type it = function Mty_ident p | Mty_alias p -> it.it_path p | Mty_signature sg -> it.it_signature it sg | Mty_functor (_, mto, mt) -> may (it.it_module_type it) mto; it.it_module_type it mt and it_class_type it = function Cty_constr (p, tyl, cty) -> it.it_path p; List.iter (it.it_type_expr it) tyl; it.it_class_type it cty | Cty_signature cs -> it.it_type_expr it cs.csig_self; Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars; List.iter (fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl) cs.csig_inher | Cty_arrow (_, ty, cty) -> it.it_type_expr it ty; it.it_class_type it cty and it_type_kind it kind = iter_type_expr_kind (it.it_type_expr it) kind and it_do_type_expr it ty = iter_type_expr (it.it_type_expr it) ty; match ty.desc with Tconstr (p, _, _) | Tobject (_, {contents=Some (p, _)}) | Tpackage (p, _, _) -> it.it_path p | Tvariant row -> may (fun (p,_) -> it.it_path p) (row_repr row).row_name | _ -> () and it_path p = () in { it_path; it_type_expr = it_do_type_expr; it_do_type_expr; it_type_kind; it_class_type; it_module_type; it_signature; it_class_type_declaration; it_class_declaration; it_modtype_declaration; it_module_declaration; it_extension_constructor; it_type_declaration; it_value_description; it_signature_item; } let copy_row f fixed row keep more = let fields = List.map (fun (l, fi) -> l, match row_field_repr fi with | Rpresent(Some ty) -> Rpresent(Some(f ty)) | Reither(c, tl, m, e) -> let e = if keep then e else ref None in let m = if row.row_fixed then fixed else m in let tl = List.map f tl in Reither(c, tl, m, e) | _ -> fi) row.row_fields in let name = match row.row_name with None -> None | Some (path, tl) -> Some (path, List.map f tl) in { row_fields = fields; row_more = more; row_bound = (); row_fixed = row.row_fixed && fixed; row_closed = row.row_closed; row_name = name; } let rec copy_kind = function Fvar{contents = Some k} -> copy_kind k | Fvar _ -> Fvar (ref None) | Fpresent -> Fpresent | Fabsent -> assert false let copy_commu c = if commu_repr c = Cok then Cok else Clink (ref Cunknown) let rec norm_univar ty = match ty.desc with Tunivar _ | Tsubst _ -> ty | Tlink ty -> norm_univar ty | Ttuple (ty :: _) -> norm_univar ty | _ -> assert false let rec copy_type_desc ?(keep_names=false) f = function Tvar _ as ty -> if keep_names then ty else Tvar None | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c) | Ttuple l -> Ttuple (List.map f l) | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil) | Tobject(ty, {contents = Some (p, tl)}) -> Tobject (f ty, ref (Some(p, List.map f tl))) | Tobject (ty, _) -> Tobject (f ty, ref None) Tfield (p, field_kind_repr k, f ty1, f ty2) | Tnil -> Tnil | Tlink ty -> copy_type_desc f ty.desc | Tsubst ty -> assert false | Tpoly (ty, tyl) -> let tyl = List.map (fun x -> norm_univar (f x)) tyl in Tpoly (f ty, tyl) | Tpackage (p, n, l) -> Tpackage (p, n, List.map f l) Utilities for copying let saved_desc = ref [] let save_desc ty desc = saved_desc := (ty, desc)::!saved_desc let dup_kind r = (match !r with None -> () | Some _ -> assert false); if not (List.memq r !new_kinds) then begin saved_kinds := r :: !saved_kinds; let r' = ref None in new_kinds := r' :: !new_kinds; r := Some (Fvar r') end let cleanup_types () = List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc; List.iter (fun r -> r := None) !saved_kinds; saved_desc := []; saved_kinds := []; new_kinds := [] let rec mark_type ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr mark_type ty end let mark_type_node ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; end let mark_type_params ty = iter_type_expr mark_type ty let type_iterators = let it_type_expr it ty = let ty = repr ty in if ty.level >= lowest_level then begin mark_type_node ty; it.it_do_type_expr it ty; end in {type_iterators with it_type_expr} let rec unmark_type ty = let ty = repr ty in if ty.level < lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr unmark_type ty end let unmark_iterators = let it_type_expr it ty = unmark_type ty in {type_iterators with it_type_expr} let unmark_type_decl decl = unmark_iterators.it_type_declaration unmark_iterators decl let unmark_extension_constructor ext = List.iter unmark_type ext.ext_type_params; iter_type_expr_cstr_args unmark_type ext.ext_args; Misc.may unmark_type ext.ext_ret_type let unmark_class_signature sign = unmark_type sign.csig_self; Vars.iter (fun l (m, v, t) -> unmark_type t) sign.csig_vars let unmark_class_type cty = unmark_iterators.it_class_type unmark_iterators cty match p1, p2 with | Private, _ | _, Public -> true | Public, Private -> false let rec find_expans priv p1 = function Mnil -> None | Mcons (priv', p2, ty0, ty, _) when lte_public priv priv' && Path.same p1 p2 -> Some ty | Mcons (_, _, _, _, rem) -> find_expans priv p1 rem | Mlink {contents = rem} -> find_expans priv p1 rem debug : check for cycles in abbreviation . only works with -principal let rec check_expans visited ty = let ty = repr ty in assert ( not ( visited ) ) ; match ty.desc with Tconstr ( path , args , abbrev ) - > begin match find_expans path ! abbrev with Some ty ' - > check_expans ( ty : : visited ) ty ' | None - > ( ) end | _ - > ( ) let rec check_expans visited ty = let ty = repr ty in assert (not (List.memq ty visited)); match ty.desc with Tconstr (path, args, abbrev) -> begin match find_expans path !abbrev with Some ty' -> check_expans (ty :: visited) ty' | None -> () end | _ -> () *) let memo = ref [] let cleanup_abbrev () = List.iter (fun abbr -> abbr := Mnil) !memo; memo := [] let memorize_abbrev mem priv path v v' = mem := Mcons (priv, path, v, v', !mem); check_expans [ ] v ; memo := mem :: !memo let rec forget_abbrev_rec mem path = match mem with Mnil -> assert false | Mcons (_, path', _, _, rem) when Path.same path path' -> rem | Mcons (priv, path', v, v', rem) -> Mcons (priv, path', v, v', forget_abbrev_rec rem path) | Mlink mem' -> mem' := forget_abbrev_rec !mem' path; raise Exit let forget_abbrev mem path = try mem := forget_abbrev_rec !mem path with Exit -> () debug : check for invalid abbreviations let rec check_abbrev_rec = function Mnil - > true | Mcons ( _ , , ty2 , rem ) - > repr ! = repr ty2 | Mlink mem ' - > check_abbrev_rec ! ' let ( ) = List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo let rec check_abbrev_rec = function Mnil -> true | Mcons (_, ty1, ty2, rem) -> repr ty1 != repr ty2 | Mlink mem' -> check_abbrev_rec !mem' let check_memorized_abbrevs () = List.for_all (fun mem -> check_abbrev_rec !mem) !memo *) Utilities for labels let is_optional = function Optional _ -> true | _ -> false let label_name = function Nolabel -> "" | Labelled s | Optional s -> s let prefixed_label_name = function Nolabel -> "" | Labelled s -> "~" ^ s | Optional s -> "?" ^ s let rec extract_label_aux hd l = function [] -> raise Not_found | (l',t as p) :: ls -> if label_name l' = l then (l', t, List.rev hd, ls) else extract_label_aux (p::hd) l ls let extract_label l ls = extract_label_aux [] l ls Utilities for backtracking let undo_change = function Ctype (ty, desc) -> ty.desc <- desc | Ccompress (ty, desc, _) -> ty.desc <- desc | Clevel (ty, level) -> ty.level <- level | Cname (r, v) -> r := v | Crow (r, v) -> r := v | Ckind (r, v) -> r := v | Ccommu (r, v) -> r := v | Cuniv (r, v) -> r := v | Ctypeset (r, v) -> r := v type snapshot = changes ref * int let last_snapshot = ref 0 let log_type ty = if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc)) let link_type ty ty' = log_type ty; let desc = ty.desc in ty.desc <- Tlink ty'; match desc, ty'.desc with Tvar name, Tvar name' -> begin match name, name' with | Some _, None -> log_type ty'; ty'.desc <- Tvar name | None, Some _ -> () | Some _, Some _ -> if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name) | None, None -> () end | _ -> () ; assert ( ( ) ) ; check_expans [ ] ty ' let set_level ty level = if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level)); ty.level <- level let set_univar rty ty = log_change (Cuniv (rty, !rty)); rty := Some ty let set_name nm v = log_change (Cname (nm, !nm)); nm := v let set_row_field e v = log_change (Crow (e, !e)); e := Some v let set_kind rk k = log_change (Ckind (rk, !rk)); rk := Some k let set_commu rc c = log_change (Ccommu (rc, !rc)); rc := c let set_typeset rs s = log_change (Ctypeset (rs, !rs)); rs := s let snapshot () = let old = !last_snapshot in last_snapshot := !new_id; match Weak.get trail 0 with Some r -> (r, old) | None -> let r = ref Unchanged in Weak.set trail 0 (Some r); (r, old) let rec rev_log accu = function Unchanged -> accu | Invalid -> assert false | Change (ch, next) -> let d = !next in next := Invalid; rev_log (ch::accu) d let backtrack (changes, old) = match !changes with Unchanged -> last_snapshot := old | Invalid -> failwith "Btype.backtrack" | Change _ as change -> cleanup_abbrev (); let backlog = rev_log [] change in List.iter undo_change backlog; changes := Unchanged; last_snapshot := old; Weak.set trail 0 (Some changes) let rec rev_compress_log log r = match !r with Unchanged | Invalid -> log | Change (Ccompress _, next) -> rev_compress_log (r::log) next | Change (_, next) -> rev_compress_log log next let undo_compress (changes, old) = match !changes with Unchanged | Invalid -> () | Change _ -> let log = rev_compress_log [] changes in List.iter (fun r -> match !r with Change (Ccompress (ty, desc, d), next) when ty.desc == d -> ty.desc <- desc; r := !next | _ -> ()) log
a7d574a363c9e64ffb15b0e709c1330d49b650f8f305a68baf6ecc4309f62937
goblint/analyzer
lockDomain.ml
module Addr = ValueDomain.Addr module Offs = ValueDomain.Offs module Equ = MusteqDomain.Equ module Exp = CilType.Exp module IdxDom = ValueDomain.IndexDomain open GoblintCil module Mutexes = SetDomain.ToppedSet (Addr) (struct let topname = "All mutexes" end) (* TODO HoareDomain? *) module Simple = Lattice.Reverse (Mutexes) module Priorities = IntDomain.Lifted module Glob = struct module Var = Basetype.Variables module Val = Simple end module Lockset = struct (* true means exclusive lock and false represents reader lock*) module RW = IntDomain.Booleans pair and RW ; also change pretty printing module Lock = struct include Printable.Prod (Addr) (RW) let pretty () (a, write) = if write then Addr.pretty () a else Pretty.dprintf "read lock %a" Addr.pretty a include Printable.SimplePretty ( struct type nonrec t = t let pretty = pretty end ) end TODO : use SetDomain . Reverse module ReverseAddrSet = SetDomain.ToppedSet (Lock) (struct let topname = "All mutexes" end) module AddrSet = Lattice.Reverse (ReverseAddrSet) include AddrSet let rec may_be_same_offset of1 of2 = match of1, of2 with | `NoOffset , `NoOffset -> true TODO : why not fieldinfo equal ? | `Index (x1,y1) , `Index (x2,y2) -> ((IdxDom.to_int x1 = None) || (IdxDom.to_int x2 = None)) || IdxDom.equal x1 x2 && may_be_same_offset y1 y2 | _ -> false let add (addr,rw) set = match (Addr.to_var_offset addr) with | Some (_,x) when Offs.is_definite x -> ReverseAddrSet.add (addr,rw) set | _ -> set let remove (addr,rw) set = let collect_diff_varinfo_with (vi,os) (addr,rw) = match (Addr.to_var_offset addr) with | Some (v,o) when CilType.Varinfo.equal vi v -> not (may_be_same_offset o os) | Some (v,o) -> true | None -> false in match (Addr.to_var_offset addr) with | Some (_,x) when Offs.is_definite x -> ReverseAddrSet.remove (addr,rw) set | Some x -> ReverseAddrSet.filter (collect_diff_varinfo_with x) set | _ -> AddrSet.top () let empty = ReverseAddrSet.empty let is_empty = ReverseAddrSet.is_empty let filter = ReverseAddrSet.filter let fold = ReverseAddrSet.fold let singleton = ReverseAddrSet.singleton let mem = ReverseAddrSet.mem let exists = ReverseAddrSet.exists let export_locks ls = let f (x,_) set = Mutexes.add x set in fold f ls (Mutexes.empty ()) end module MayLockset = struct include Lockset let leq x y = leq y x let join = Lockset.meet let meet = Lockset.join let top = Lockset.bot let bot = Lockset.top end module Symbolic = struct TODO : use SetDomain . Reverse module S = SetDomain.ToppedSet (Exp) (struct let topname = "All mutexes" end) include Lattice.Reverse (S) let rec eq_set (ask: Queries.ask) e = S.union (match ask.f (Queries.EqualSet e) with | es when not (Queries.ES.is_bot es) -> Queries.ES.fold S.add es (S.empty ()) | _ -> S.empty ()) (match e with | SizeOf _ | SizeOfE _ | SizeOfStr _ | AlignOf _ | Const _ | AlignOfE _ | UnOp _ | BinOp _ | Question _ | Real _ | Imag _ | AddrOfLabel _ -> S.empty () | AddrOf (Var _,_) | StartOf (Var _,_) | Lval (Var _,_) -> S.singleton e | AddrOf (Mem e,ofs) -> S.map (fun e -> AddrOf (Mem e,ofs)) (eq_set ask e) | StartOf (Mem e,ofs) -> S.map (fun e -> StartOf (Mem e,ofs)) (eq_set ask e) | Lval (Mem e,ofs) -> S.map (fun e -> Lval (Mem e,ofs)) (eq_set ask e) | CastE (_,e) -> eq_set ask e ) let add (ask: Queries.ask) e st = let no_casts = S.map Expcompare.stripCastsDeepForPtrArith (eq_set ask e) in let addrs = S.filter (function AddrOf _ -> true | _ -> false) no_casts in S.union addrs st let remove ask e st = (* TODO: Removing based on must-equality sets is not sound! *) let no_casts = S.map Expcompare.stripCastsDeepForPtrArith (eq_set ask e) in let addrs = S.filter (function AddrOf _ -> true | _ -> false) no_casts in S.diff st addrs let remove_var v st = S.filter (fun x -> not (SymbLocksDomain.Exp.contains_var v x)) st let filter = S.filter let fold = S.fold end
null
https://raw.githubusercontent.com/goblint/analyzer/fe66b8feba5dc31b4eb612dce1d707b9ef04e6bc/src/cdomains/lockDomain.ml
ocaml
TODO HoareDomain? true means exclusive lock and false represents reader lock TODO: Removing based on must-equality sets is not sound!
module Addr = ValueDomain.Addr module Offs = ValueDomain.Offs module Equ = MusteqDomain.Equ module Exp = CilType.Exp module IdxDom = ValueDomain.IndexDomain open GoblintCil module Simple = Lattice.Reverse (Mutexes) module Priorities = IntDomain.Lifted module Glob = struct module Var = Basetype.Variables module Val = Simple end module Lockset = struct module RW = IntDomain.Booleans pair and RW ; also change pretty printing module Lock = struct include Printable.Prod (Addr) (RW) let pretty () (a, write) = if write then Addr.pretty () a else Pretty.dprintf "read lock %a" Addr.pretty a include Printable.SimplePretty ( struct type nonrec t = t let pretty = pretty end ) end TODO : use SetDomain . Reverse module ReverseAddrSet = SetDomain.ToppedSet (Lock) (struct let topname = "All mutexes" end) module AddrSet = Lattice.Reverse (ReverseAddrSet) include AddrSet let rec may_be_same_offset of1 of2 = match of1, of2 with | `NoOffset , `NoOffset -> true TODO : why not fieldinfo equal ? | `Index (x1,y1) , `Index (x2,y2) -> ((IdxDom.to_int x1 = None) || (IdxDom.to_int x2 = None)) || IdxDom.equal x1 x2 && may_be_same_offset y1 y2 | _ -> false let add (addr,rw) set = match (Addr.to_var_offset addr) with | Some (_,x) when Offs.is_definite x -> ReverseAddrSet.add (addr,rw) set | _ -> set let remove (addr,rw) set = let collect_diff_varinfo_with (vi,os) (addr,rw) = match (Addr.to_var_offset addr) with | Some (v,o) when CilType.Varinfo.equal vi v -> not (may_be_same_offset o os) | Some (v,o) -> true | None -> false in match (Addr.to_var_offset addr) with | Some (_,x) when Offs.is_definite x -> ReverseAddrSet.remove (addr,rw) set | Some x -> ReverseAddrSet.filter (collect_diff_varinfo_with x) set | _ -> AddrSet.top () let empty = ReverseAddrSet.empty let is_empty = ReverseAddrSet.is_empty let filter = ReverseAddrSet.filter let fold = ReverseAddrSet.fold let singleton = ReverseAddrSet.singleton let mem = ReverseAddrSet.mem let exists = ReverseAddrSet.exists let export_locks ls = let f (x,_) set = Mutexes.add x set in fold f ls (Mutexes.empty ()) end module MayLockset = struct include Lockset let leq x y = leq y x let join = Lockset.meet let meet = Lockset.join let top = Lockset.bot let bot = Lockset.top end module Symbolic = struct TODO : use SetDomain . Reverse module S = SetDomain.ToppedSet (Exp) (struct let topname = "All mutexes" end) include Lattice.Reverse (S) let rec eq_set (ask: Queries.ask) e = S.union (match ask.f (Queries.EqualSet e) with | es when not (Queries.ES.is_bot es) -> Queries.ES.fold S.add es (S.empty ()) | _ -> S.empty ()) (match e with | SizeOf _ | SizeOfE _ | SizeOfStr _ | AlignOf _ | Const _ | AlignOfE _ | UnOp _ | BinOp _ | Question _ | Real _ | Imag _ | AddrOfLabel _ -> S.empty () | AddrOf (Var _,_) | StartOf (Var _,_) | Lval (Var _,_) -> S.singleton e | AddrOf (Mem e,ofs) -> S.map (fun e -> AddrOf (Mem e,ofs)) (eq_set ask e) | StartOf (Mem e,ofs) -> S.map (fun e -> StartOf (Mem e,ofs)) (eq_set ask e) | Lval (Mem e,ofs) -> S.map (fun e -> Lval (Mem e,ofs)) (eq_set ask e) | CastE (_,e) -> eq_set ask e ) let add (ask: Queries.ask) e st = let no_casts = S.map Expcompare.stripCastsDeepForPtrArith (eq_set ask e) in let addrs = S.filter (function AddrOf _ -> true | _ -> false) no_casts in S.union addrs st let remove ask e st = let no_casts = S.map Expcompare.stripCastsDeepForPtrArith (eq_set ask e) in let addrs = S.filter (function AddrOf _ -> true | _ -> false) no_casts in S.diff st addrs let remove_var v st = S.filter (fun x -> not (SymbLocksDomain.Exp.contains_var v x)) st let filter = S.filter let fold = S.fold end
31df99892aff9083f62c5db9c04e412b744eabd5a272a72806c1b733a5553fb9
input-output-hk/cardano-wallet
HasDelegation.hs
# LANGUAGE FlexibleInstances # -- | Copyright : © 2018 - 2020 IOHK -- License: Apache-2.0 -- -- Type class that discriminates whether an -- address state supports delegation. module Cardano.Wallet.Address.HasDelegation ( HasDelegation (..) ) where import Prelude import Cardano.Wallet.Primitive.AddressDerivation.Icarus ( IcarusKey ) import Cardano.Wallet.Primitive.AddressDerivation.SharedKey ( SharedKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey ) import Cardano.Wallet.Primitive.AddressDiscovery.Random ( RndState (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( SeqState ) import Cardano.Wallet.Primitive.AddressDiscovery.Shared ( SharedState ) -- | Discriminate whether an address state supports delegation. class HasDelegation s where hasDelegation :: proxy s -> Bool instance HasDelegation (SeqState n ShelleyKey) where hasDelegation _ = True instance HasDelegation (RndState n) where hasDelegation _ = False instance HasDelegation (SeqState n IcarusKey) where hasDelegation _ = False instance HasDelegation (SharedState n SharedKey) where hasDelegation _ = False
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/999e7e15c9cf04133b6ae8593e1dcaca1d1c31d2/lib/wallet/src/Cardano/Wallet/Address/HasDelegation.hs
haskell
| License: Apache-2.0 Type class that discriminates whether an address state supports delegation. | Discriminate whether an address state supports delegation.
# LANGUAGE FlexibleInstances # Copyright : © 2018 - 2020 IOHK module Cardano.Wallet.Address.HasDelegation ( HasDelegation (..) ) where import Prelude import Cardano.Wallet.Primitive.AddressDerivation.Icarus ( IcarusKey ) import Cardano.Wallet.Primitive.AddressDerivation.SharedKey ( SharedKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey ) import Cardano.Wallet.Primitive.AddressDiscovery.Random ( RndState (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( SeqState ) import Cardano.Wallet.Primitive.AddressDiscovery.Shared ( SharedState ) class HasDelegation s where hasDelegation :: proxy s -> Bool instance HasDelegation (SeqState n ShelleyKey) where hasDelegation _ = True instance HasDelegation (RndState n) where hasDelegation _ = False instance HasDelegation (SeqState n IcarusKey) where hasDelegation _ = False instance HasDelegation (SharedState n SharedKey) where hasDelegation _ = False
53dd72b4d8a1de06103b128c3911398af5ea172d277be3aabe951dd8b7039be5
morphismtech/squeal
Example.hs
# LANGUAGE DataKinds , DeriveGeneric , FlexibleContexts , OverloadedLabels , OverloadedStrings , OverloadedLists , TypeApplications , TypeOperators # DataKinds , DeriveGeneric , FlexibleContexts , OverloadedLabels , OverloadedStrings , OverloadedLists , TypeApplications , TypeOperators #-} module Main (main, main2, upsertUser) where import Control.Monad.IO.Class (MonadIO (..)) import Data.Int (Int16, Int32) import Data.Text (Text) import Data.Vector (Vector) import Squeal.PostgreSQL import qualified Data.ByteString.Char8 as Char8 import qualified Generics.SOP as SOP import qualified GHC.Generics as GHC type UserSchema = '[ "users" ::: 'Table ( '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "name" ::: 'NoDef :=> 'NotNull 'PGtext , "vec" ::: 'NoDef :=> 'NotNull ('PGvararray ('Null 'PGint2)) ]) , "emails" ::: 'Table ( '[ "pk_emails" ::: 'PrimaryKey '["id"] , "fk_user_id" ::: 'ForeignKey '["user_id"] "user" "users" '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4 , "email" ::: 'NoDef :=> 'Null 'PGtext ]) ] type PublicSchema = '[ "positive" ::: 'Typedef 'PGfloat4 ] type OrgSchema = '[ "organizations" ::: 'Table ( '[ "pk_organizations" ::: 'PrimaryKey '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]) , "members" ::: 'Table ( '[ "fk_member" ::: 'ForeignKey '["member"] "user" "users" '["id"] , "fk_organization" ::: 'ForeignKey '["organization"] "org" "organizations" '["id"] ] :=> '[ "member" ::: 'NoDef :=> 'NotNull 'PGint4 , "organization" ::: 'NoDef :=> 'NotNull 'PGint4 ]) ] type Schemas = '[ "public" ::: PublicSchema, "user" ::: UserSchema, "org" ::: OrgSchema ] setup :: Definition (Public '[]) Schemas setup = createDomain #positive real (#value .> 0 .&& (#value & isNotNull)) >>> createSchema #user >>> createSchema #org >>> createTable (#user ! #jokers) ( serial `as` #id :* (text & notNullable) `as` #name :* (vararray int2 & notNullable) `as` #vec ) ( primaryKey #id `as` #pk_users ) >>> alterTableRename (#user ! #jokers) #users >>> createTable (#user ! #emails) ( serial `as` #id :* columntypeFrom @Int32 `as` #user_id :* columntypeFrom @(Maybe Text) `as` #email ) ( primaryKey #id `as` #pk_emails :* foreignKey #user_id (#user ! #users) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_user_id ) >>> createTable (#org ! #organizations) ( serial `as` #id :* (text & notNullable) `as` #name ) ( primaryKey #id `as` #pk_organizations ) >>> createTable (#org ! #members) ( notNullable int4 `as` #member :* notNullable int4 `as` #organization ) ( foreignKey #member (#user ! #users) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_member :* foreignKey #organization (#org ! #organizations) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_organization ) teardown :: Definition Schemas (Public '[]) teardown = dropType #positive >>> dropSchemaCascade #user >>> dropSchemaCascade #org insertUser :: Manipulation_ Schemas (Text, VarArray (Vector (Maybe Int16))) (Only Int32) insertUser = insertInto (#user ! #users) (Values_ (Default `as` #id :* Set (param @1) `as` #name :* Set (param @2) `as` #vec)) (OnConflict (OnConstraint #pk_users) DoNothing) (Returning_ (#id `as` #fromOnly)) insertEmail :: Manipulation_ Schemas (Int32, Maybe Text) () insertEmail = insertInto_ (#user ! #emails) (Values_ (Default `as` #id :* Set (param @1) `as` #user_id :* Set (param @2) `as` #email)) getUsers :: Query_ Schemas () User getUsers = select_ (#u ! #name `as` #userName :* #e ! #email `as` #userEmail :* #u ! #vec `as` #userVec) ( from (table ((#user ! #users) `as` #u) & innerJoin (table ((#user ! #emails) `as` #e)) (#u ! #id .== #e ! #user_id)) ) upsertUser :: Manipulation_ Schemas (Int32, String, VarArray [Maybe Int16]) () upsertUser = insertInto (#user ! #users `as` #u) (Values_ (Set (param @1) `as` #id :* setUser)) (OnConflict (OnConstraint #pk_users) (DoUpdate setUser [#u ! #id .== param @1])) (Returning_ Nil) where setUser = Set (param @2) `as` #name :* Set (param @3) `as` #vec :* Nil data User = User { userName :: Text , userEmail :: Maybe Text , userVec :: VarArray (Vector (Maybe Int16)) } deriving (Show, GHC.Generic) instance SOP.Generic User instance SOP.HasDatatypeInfo User users :: [User] users = [ User "Alice" (Just "") (VarArray [Just 1,Just 2,Nothing]) , User "Bob" Nothing (VarArray [Nothing,Just (-3)]) , User "Carole" (Just "") (VarArray [Just 3,Nothing, Just 4]) ] session :: (MonadIO pq, MonadPQ Schemas pq) => pq () session = do liftIO $ Char8.putStrLn "manipulating" idResults <- traversePrepared insertUser ([(userName user, userVec user) | user <- users]) ids <- traverse (fmap fromOnly . getRow 0) (idResults :: [Result (Only Int32)]) traversePrepared_ insertEmail (zip (ids :: [Int32]) (userEmail <$> users)) liftIO $ Char8.putStrLn "querying" usersResult <- runQuery getUsers usersRows <- getRows usersResult liftIO $ print (usersRows :: [User]) main :: IO () main = do Char8.putStrLn "squeal" connectionString <- pure "host=localhost port=5432 dbname=exampledb user=postgres password=postgres" Char8.putStrLn $ "connecting to " <> connectionString connection0 <- connectdb connectionString Char8.putStrLn "setting up schema" connection1 <- execPQ (define setup) connection0 connection2 <- execPQ session connection1 Char8.putStrLn "tearing down schema" connection3 <- execPQ (define teardown) connection2 finish connection3 main2 :: IO () main2 = withConnection "host=localhost port=5432 dbname=exampledb user=postgres password=postgres" $ define setup & pqThen session & pqThen (define teardown)
null
https://raw.githubusercontent.com/morphismtech/squeal/bc555d5126b95948d9bc42a604099d37b99f19e2/squeal-postgresql/exe/Example.hs
haskell
# LANGUAGE DataKinds , DeriveGeneric , FlexibleContexts , OverloadedLabels , OverloadedStrings , OverloadedLists , TypeApplications , TypeOperators # DataKinds , DeriveGeneric , FlexibleContexts , OverloadedLabels , OverloadedStrings , OverloadedLists , TypeApplications , TypeOperators #-} module Main (main, main2, upsertUser) where import Control.Monad.IO.Class (MonadIO (..)) import Data.Int (Int16, Int32) import Data.Text (Text) import Data.Vector (Vector) import Squeal.PostgreSQL import qualified Data.ByteString.Char8 as Char8 import qualified Generics.SOP as SOP import qualified GHC.Generics as GHC type UserSchema = '[ "users" ::: 'Table ( '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "name" ::: 'NoDef :=> 'NotNull 'PGtext , "vec" ::: 'NoDef :=> 'NotNull ('PGvararray ('Null 'PGint2)) ]) , "emails" ::: 'Table ( '[ "pk_emails" ::: 'PrimaryKey '["id"] , "fk_user_id" ::: 'ForeignKey '["user_id"] "user" "users" '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4 , "email" ::: 'NoDef :=> 'Null 'PGtext ]) ] type PublicSchema = '[ "positive" ::: 'Typedef 'PGfloat4 ] type OrgSchema = '[ "organizations" ::: 'Table ( '[ "pk_organizations" ::: 'PrimaryKey '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]) , "members" ::: 'Table ( '[ "fk_member" ::: 'ForeignKey '["member"] "user" "users" '["id"] , "fk_organization" ::: 'ForeignKey '["organization"] "org" "organizations" '["id"] ] :=> '[ "member" ::: 'NoDef :=> 'NotNull 'PGint4 , "organization" ::: 'NoDef :=> 'NotNull 'PGint4 ]) ] type Schemas = '[ "public" ::: PublicSchema, "user" ::: UserSchema, "org" ::: OrgSchema ] setup :: Definition (Public '[]) Schemas setup = createDomain #positive real (#value .> 0 .&& (#value & isNotNull)) >>> createSchema #user >>> createSchema #org >>> createTable (#user ! #jokers) ( serial `as` #id :* (text & notNullable) `as` #name :* (vararray int2 & notNullable) `as` #vec ) ( primaryKey #id `as` #pk_users ) >>> alterTableRename (#user ! #jokers) #users >>> createTable (#user ! #emails) ( serial `as` #id :* columntypeFrom @Int32 `as` #user_id :* columntypeFrom @(Maybe Text) `as` #email ) ( primaryKey #id `as` #pk_emails :* foreignKey #user_id (#user ! #users) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_user_id ) >>> createTable (#org ! #organizations) ( serial `as` #id :* (text & notNullable) `as` #name ) ( primaryKey #id `as` #pk_organizations ) >>> createTable (#org ! #members) ( notNullable int4 `as` #member :* notNullable int4 `as` #organization ) ( foreignKey #member (#user ! #users) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_member :* foreignKey #organization (#org ! #organizations) #id (OnDelete Cascade) (OnUpdate Cascade) `as` #fk_organization ) teardown :: Definition Schemas (Public '[]) teardown = dropType #positive >>> dropSchemaCascade #user >>> dropSchemaCascade #org insertUser :: Manipulation_ Schemas (Text, VarArray (Vector (Maybe Int16))) (Only Int32) insertUser = insertInto (#user ! #users) (Values_ (Default `as` #id :* Set (param @1) `as` #name :* Set (param @2) `as` #vec)) (OnConflict (OnConstraint #pk_users) DoNothing) (Returning_ (#id `as` #fromOnly)) insertEmail :: Manipulation_ Schemas (Int32, Maybe Text) () insertEmail = insertInto_ (#user ! #emails) (Values_ (Default `as` #id :* Set (param @1) `as` #user_id :* Set (param @2) `as` #email)) getUsers :: Query_ Schemas () User getUsers = select_ (#u ! #name `as` #userName :* #e ! #email `as` #userEmail :* #u ! #vec `as` #userVec) ( from (table ((#user ! #users) `as` #u) & innerJoin (table ((#user ! #emails) `as` #e)) (#u ! #id .== #e ! #user_id)) ) upsertUser :: Manipulation_ Schemas (Int32, String, VarArray [Maybe Int16]) () upsertUser = insertInto (#user ! #users `as` #u) (Values_ (Set (param @1) `as` #id :* setUser)) (OnConflict (OnConstraint #pk_users) (DoUpdate setUser [#u ! #id .== param @1])) (Returning_ Nil) where setUser = Set (param @2) `as` #name :* Set (param @3) `as` #vec :* Nil data User = User { userName :: Text , userEmail :: Maybe Text , userVec :: VarArray (Vector (Maybe Int16)) } deriving (Show, GHC.Generic) instance SOP.Generic User instance SOP.HasDatatypeInfo User users :: [User] users = [ User "Alice" (Just "") (VarArray [Just 1,Just 2,Nothing]) , User "Bob" Nothing (VarArray [Nothing,Just (-3)]) , User "Carole" (Just "") (VarArray [Just 3,Nothing, Just 4]) ] session :: (MonadIO pq, MonadPQ Schemas pq) => pq () session = do liftIO $ Char8.putStrLn "manipulating" idResults <- traversePrepared insertUser ([(userName user, userVec user) | user <- users]) ids <- traverse (fmap fromOnly . getRow 0) (idResults :: [Result (Only Int32)]) traversePrepared_ insertEmail (zip (ids :: [Int32]) (userEmail <$> users)) liftIO $ Char8.putStrLn "querying" usersResult <- runQuery getUsers usersRows <- getRows usersResult liftIO $ print (usersRows :: [User]) main :: IO () main = do Char8.putStrLn "squeal" connectionString <- pure "host=localhost port=5432 dbname=exampledb user=postgres password=postgres" Char8.putStrLn $ "connecting to " <> connectionString connection0 <- connectdb connectionString Char8.putStrLn "setting up schema" connection1 <- execPQ (define setup) connection0 connection2 <- execPQ session connection1 Char8.putStrLn "tearing down schema" connection3 <- execPQ (define teardown) connection2 finish connection3 main2 :: IO () main2 = withConnection "host=localhost port=5432 dbname=exampledb user=postgres password=postgres" $ define setup & pqThen session & pqThen (define teardown)
2325396818e3c57242ab4f530f1491df74859f6a9dcacf27d8472a0adf50f33d
ocaml-sf/learn-ocaml-corpus
template.ml
(* TO DO: Define [weight] and [height]. *) (* TO DO: Define [naive_trees_of_weight]. *) (* TO DO: Define [trees_of_weights]. *) The function call [ fix ff ] creates and returns a new memoizing function [ f ] of type [ a - > b ] . Its argument [ ff ] is itself a function , whose type is [ ( a - > b ) - > ( a - > b ) ] , and which expects to receive [ f ] as an argument . of type [a -> b]. Its argument [ff] is itself a function, whose type is [(a -> b) -> (a -> b)], and which expects to receive [f] as an argument. *) For example , a memoizing factorial can be defined using [ fix ] as follows : let fact = fix ( fun self - > fun n - > if n = 0 then 1 else n * self(n-1 ) ) Note that the definition of [ fact ] does not involve [ let rec ] . Instead , when we wish to perform a recursive call , we invoke [ self ] , the memoizing function which [ fix ] has constructed for us . follows: let fact = fix (fun self -> fun n -> if n = 0 then 1 else n * self(n-1) ) Note that the definition of [fact] does not involve [let rec]. Instead, when we wish to perform a recursive call, we invoke [self], the memoizing function which [fix] has constructed for us. *) We assume that it is permitted to use values of type [ a ] as keys in a hash table . That is , we assume that 's generic equality and hash functions behave in a sensible way when applied to values of type [ a ] . Thus , we can use the functions [ create ] , [ add ] , [ find ] provided by the module [ ] in 's standard library . table. That is, we assume that OCaml's generic equality and hash functions behave in a sensible way when applied to values of type [a]. Thus, we can use the functions [create], [add], [find] provided by the module [Hashtbl] in OCaml's standard library. *) (* It is now up to you to implement [fix], based on the following skeleton. *) let fix : type a b . ((a -> b) -> (a -> b)) -> (a -> b) = fun ff -> let table = Hashtbl.create 128 in let rec f (x : a) : b = (* TO DO: complete this code. *) raise TODO in f (* TO DO: Define [sigma]. *) TO DO : Define [ split_weight ] . (* TO DO: Define [trees_of_weight]. *) (* TO DO: Define [trees_of_weight_0_19]. *) TO DO : Define [ ] . (* TO DO: Define [wb_trees_of_weight]. *) (* TO DO: Define [wb_trees_of_weight_0_19]. *)
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/counting_trees/template.ml
ocaml
TO DO: Define [weight] and [height]. TO DO: Define [naive_trees_of_weight]. TO DO: Define [trees_of_weights]. It is now up to you to implement [fix], based on the following skeleton. TO DO: complete this code. TO DO: Define [sigma]. TO DO: Define [trees_of_weight]. TO DO: Define [trees_of_weight_0_19]. TO DO: Define [wb_trees_of_weight]. TO DO: Define [wb_trees_of_weight_0_19].
The function call [ fix ff ] creates and returns a new memoizing function [ f ] of type [ a - > b ] . Its argument [ ff ] is itself a function , whose type is [ ( a - > b ) - > ( a - > b ) ] , and which expects to receive [ f ] as an argument . of type [a -> b]. Its argument [ff] is itself a function, whose type is [(a -> b) -> (a -> b)], and which expects to receive [f] as an argument. *) For example , a memoizing factorial can be defined using [ fix ] as follows : let fact = fix ( fun self - > fun n - > if n = 0 then 1 else n * self(n-1 ) ) Note that the definition of [ fact ] does not involve [ let rec ] . Instead , when we wish to perform a recursive call , we invoke [ self ] , the memoizing function which [ fix ] has constructed for us . follows: let fact = fix (fun self -> fun n -> if n = 0 then 1 else n * self(n-1) ) Note that the definition of [fact] does not involve [let rec]. Instead, when we wish to perform a recursive call, we invoke [self], the memoizing function which [fix] has constructed for us. *) We assume that it is permitted to use values of type [ a ] as keys in a hash table . That is , we assume that 's generic equality and hash functions behave in a sensible way when applied to values of type [ a ] . Thus , we can use the functions [ create ] , [ add ] , [ find ] provided by the module [ ] in 's standard library . table. That is, we assume that OCaml's generic equality and hash functions behave in a sensible way when applied to values of type [a]. Thus, we can use the functions [create], [add], [find] provided by the module [Hashtbl] in OCaml's standard library. *) let fix : type a b . ((a -> b) -> (a -> b)) -> (a -> b) = fun ff -> let table = Hashtbl.create 128 in let rec f (x : a) : b = raise TODO in f TO DO : Define [ split_weight ] . TO DO : Define [ ] .
87db3de9af4ef4469c76a6e835253335838abbf85b0d836e9ef8e0aba01dcdb3
sile/ppg
ppg.erl
Copyright ( c ) 2016 , < > %% This software is released under the MIT License . %% See the LICENSE file in the project root for full license information. %% @doc Plumtree based Process Group -module(ppg). %%---------------------------------------------------------------------------------------------------------------------- %% Exported API %%---------------------------------------------------------------------------------------------------------------------- -export([default_join_options/0]). -export([create/1]). -export([delete/1]). -export([which_groups/0]). -export([get_members/1]). -export([get_local_members/1]). -export([get_closest_member/1]). -export([join/2, join/3]). -export([leave/1]). -export([broadcast/2]). -export_type([name/0]). -export_type([member/0]). -export_type([channel/0]). -export_type([message/0]). -export_type([join_options/0, join_option/0]). -export_type([plumtree_option/0]). -export_type([hyparview_option/0]). %%---------------------------------------------------------------------------------------------------------------------- %% Types %%---------------------------------------------------------------------------------------------------------------------- -type name() :: term(). %% Group Name -type member() :: pid(). %% A member process %% %% This process receives messages which are broadcasted to the belonging group -type channel() :: pid(). %% A broadcast channel -type message() :: term(). %% A broadcast message -type join_options() :: [join_option()]. -type join_option() :: {plumtree, [plumtree_option()]} | {hyparview, [hyparview_option()]}. -type plumtree_option() :: {gossip_wait_timeout, timeout()} | {ihave_retention_period, timeout()} | {wehave_retention_period, timeout()} | {ticktime, timeout()}. -type hyparview_option() :: {active_view_size, pos_integer()} | {passive_view_size, pos_integer()} | {active_random_walk_length, pos_integer()} | {passive_random_walk_length, pos_integer()} | {shuffle_count, pos_integer()} | {shuffle_interval, timeout()}. %%---------------------------------------------------------------------------------------------------------------------- %% Exported Functions %%---------------------------------------------------------------------------------------------------------------------- %% @doc Returns the default join options -spec default_join_options() -> join_options(). default_join_options() -> [ {plumtree, ppg_plumtree:default_options()}, {hyparview, ppg_hyparview:default_options()} ]. %% @doc Creates a new group %% %% If the group already exists on the node, nothing happens. %% %% Unlike the pg2 module, every nodes which are interested in the group must call this function. -spec create(name()) -> ok. create(Group) -> case ppg_group_sup:start_child(Group) of {ok, _} -> ok; {error, {already_started, _}} -> ok; Other -> error({badresult, Other}, [Group]) end. %% @doc Deletes the group from the local node -spec delete(name()) -> ok. delete(Group) -> ppg_group_sup:stop_child(Group). %% @doc Returns the list of locally known groups -spec which_groups() -> [name()]. which_groups() -> [Group || {Group, _} <- ppg_group_sup:which_children()]. %% @doc Returns all processes in the group `Group' %% %% This function is provided for debugging purposes only. -spec get_members(name()) -> {ok, [{member(), channel()}]} | {error, {no_such_group, name()}}. get_members(Group) -> case get_closest_member(Group) of {error, Reason} -> {error, Reason}; {ok, {_, Peer0}} -> Members = [{Member, Peer1} || {Peer1, Member, _} <- ppg_peer:get_graph(Peer0, 5000)], {ok, Members} end. %% @doc Returns a process on the local node, if such a process exist. Otherwise, it returns the contact service process. -spec get_closest_member(name()) -> {ok, {member(), channel()}} | {error, Reason} when Reason :: {no_such_group, name()} | {no_reachable_member, name()}. get_closest_member(Group) -> case ppg_group_sup:find_child(Group) of error -> {error, {no_such_group, Group}}; {ok, Sup} -> case ppg_peer_sup:which_children(Sup) of [] -> case ppg_contact_service:find_peer(ppg_contact_service:new(Group)) of error -> {error, {no_reachable_member, Group}}; {ok, Peer} -> {ok, Peer} end; Peers -> Peer = lists:nth(rand:uniform(length(Peers)), Peers), {ok, {ppg_peer:get_member(Peer), Peer}} end end. %% @doc Returns all processes running on the local node in the group `Group' -spec get_local_members(name()) -> {ok, [{member(), channel()}]} | {error, {no_such_group, name()}}. get_local_members(Group) -> case ppg_group_sup:find_child(Group) of error -> {error, {no_such_group, Group}}; {ok, Sup} -> Members = [{ppg_peer:get_member(Peer), Peer} || Peer <- ppg_peer_sup:which_children(Sup)], {ok, Members} end. %% @equiv join(Group, Member, default_join_options()) -spec join(name(), ppg:member()) -> {ok, channel()} | {error, {no_such_group, name()}}. join(Group, Member) -> join(Group, Member, default_join_options()). %% @doc Joins the process `Member' to the group `Group' %% %% After the joining, `Member' can broadcast messages via `Channel'. %% %% If you are interested in the disconnection of the channel, you should apply { @link : monitor/2 } or { @link erlang : link/1 } to the channel . -spec join(name(), ppg:member(), join_options()) -> {ok, Channel::channel()} | {error, {no_such_group, name()}}. join(Group, Member, Options) -> _ = is_list(Options) orelse error(badarg, [Group, Member, Options]), case ppg_peer_sup:start_child(Group, Member, Options) of {ok, Pid} -> {ok, Pid}; {error, {no_such_group, _}} -> {error, {no_such_group, Group}}; Other -> error({badresult, Other}, [Group, Member, Options]) end. %% @doc Leaves the group associated with `Channel' -spec leave(channel()) -> ok. leave(Channel) -> ppg_peer:stop(Channel). %% @doc Broadcasts `Message' to the group associated with `Channel' -spec broadcast(channel(), message()) -> ok. broadcast(Channel, Message) -> ppg_peer:broadcast(Channel, Message).
null
https://raw.githubusercontent.com/sile/ppg/2bf2a6ddb0b21f4661eeb22b04cf5e1ad44f7af9/src/ppg.erl
erlang
See the LICENSE file in the project root for full license information. ---------------------------------------------------------------------------------------------------------------------- Exported API ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- Types ---------------------------------------------------------------------------------------------------------------------- Group Name A member process This process receives messages which are broadcasted to the belonging group A broadcast channel A broadcast message ---------------------------------------------------------------------------------------------------------------------- Exported Functions ---------------------------------------------------------------------------------------------------------------------- @doc Returns the default join options @doc Creates a new group If the group already exists on the node, nothing happens. Unlike the pg2 module, every nodes which are interested in the group must call this function. @doc Deletes the group from the local node @doc Returns the list of locally known groups @doc Returns all processes in the group `Group' This function is provided for debugging purposes only. @doc Returns a process on the local node, if such a process exist. Otherwise, it returns the contact service process. @doc Returns all processes running on the local node in the group `Group' @equiv join(Group, Member, default_join_options()) @doc Joins the process `Member' to the group `Group' After the joining, `Member' can broadcast messages via `Channel'. If you are interested in the disconnection of the channel, @doc Leaves the group associated with `Channel' @doc Broadcasts `Message' to the group associated with `Channel'
Copyright ( c ) 2016 , < > This software is released under the MIT License . @doc Plumtree based Process Group -module(ppg). -export([default_join_options/0]). -export([create/1]). -export([delete/1]). -export([which_groups/0]). -export([get_members/1]). -export([get_local_members/1]). -export([get_closest_member/1]). -export([join/2, join/3]). -export([leave/1]). -export([broadcast/2]). -export_type([name/0]). -export_type([member/0]). -export_type([channel/0]). -export_type([message/0]). -export_type([join_options/0, join_option/0]). -export_type([plumtree_option/0]). -export_type([hyparview_option/0]). -type name() :: term(). -type member() :: pid(). -type channel() :: pid(). -type message() :: term(). -type join_options() :: [join_option()]. -type join_option() :: {plumtree, [plumtree_option()]} | {hyparview, [hyparview_option()]}. -type plumtree_option() :: {gossip_wait_timeout, timeout()} | {ihave_retention_period, timeout()} | {wehave_retention_period, timeout()} | {ticktime, timeout()}. -type hyparview_option() :: {active_view_size, pos_integer()} | {passive_view_size, pos_integer()} | {active_random_walk_length, pos_integer()} | {passive_random_walk_length, pos_integer()} | {shuffle_count, pos_integer()} | {shuffle_interval, timeout()}. -spec default_join_options() -> join_options(). default_join_options() -> [ {plumtree, ppg_plumtree:default_options()}, {hyparview, ppg_hyparview:default_options()} ]. -spec create(name()) -> ok. create(Group) -> case ppg_group_sup:start_child(Group) of {ok, _} -> ok; {error, {already_started, _}} -> ok; Other -> error({badresult, Other}, [Group]) end. -spec delete(name()) -> ok. delete(Group) -> ppg_group_sup:stop_child(Group). -spec which_groups() -> [name()]. which_groups() -> [Group || {Group, _} <- ppg_group_sup:which_children()]. -spec get_members(name()) -> {ok, [{member(), channel()}]} | {error, {no_such_group, name()}}. get_members(Group) -> case get_closest_member(Group) of {error, Reason} -> {error, Reason}; {ok, {_, Peer0}} -> Members = [{Member, Peer1} || {Peer1, Member, _} <- ppg_peer:get_graph(Peer0, 5000)], {ok, Members} end. -spec get_closest_member(name()) -> {ok, {member(), channel()}} | {error, Reason} when Reason :: {no_such_group, name()} | {no_reachable_member, name()}. get_closest_member(Group) -> case ppg_group_sup:find_child(Group) of error -> {error, {no_such_group, Group}}; {ok, Sup} -> case ppg_peer_sup:which_children(Sup) of [] -> case ppg_contact_service:find_peer(ppg_contact_service:new(Group)) of error -> {error, {no_reachable_member, Group}}; {ok, Peer} -> {ok, Peer} end; Peers -> Peer = lists:nth(rand:uniform(length(Peers)), Peers), {ok, {ppg_peer:get_member(Peer), Peer}} end end. -spec get_local_members(name()) -> {ok, [{member(), channel()}]} | {error, {no_such_group, name()}}. get_local_members(Group) -> case ppg_group_sup:find_child(Group) of error -> {error, {no_such_group, Group}}; {ok, Sup} -> Members = [{ppg_peer:get_member(Peer), Peer} || Peer <- ppg_peer_sup:which_children(Sup)], {ok, Members} end. -spec join(name(), ppg:member()) -> {ok, channel()} | {error, {no_such_group, name()}}. join(Group, Member) -> join(Group, Member, default_join_options()). you should apply { @link : monitor/2 } or { @link erlang : link/1 } to the channel . -spec join(name(), ppg:member(), join_options()) -> {ok, Channel::channel()} | {error, {no_such_group, name()}}. join(Group, Member, Options) -> _ = is_list(Options) orelse error(badarg, [Group, Member, Options]), case ppg_peer_sup:start_child(Group, Member, Options) of {ok, Pid} -> {ok, Pid}; {error, {no_such_group, _}} -> {error, {no_such_group, Group}}; Other -> error({badresult, Other}, [Group, Member, Options]) end. -spec leave(channel()) -> ok. leave(Channel) -> ppg_peer:stop(Channel). -spec broadcast(channel(), message()) -> ok. broadcast(Channel, Message) -> ppg_peer:broadcast(Channel, Message).
64fdb606f000f34623f13a02a5d220cefd46c6cd861fa30fea6da7c909edd118
Incanus3/ExiL
misc.lisp
(in-package :exil-utils) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TREES (defun tree-find-all-if (pred tree) (if (listp tree) (mapcan (lambda (subtree) (tree-find-all-if pred subtree)) tree) (when (funcall pred tree) (list tree)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; SETS (defun set-equal-p (set1 set2 &key (test #'eql)) (null (set-exclusive-or set1 set2 :test test))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; PRINTING OUTPUT (defun fresh-format (stream control-string &rest args) (fresh-line stream) (apply #'format stream control-string args)) (defun fresh-princ (object &optional stream) (fresh-line stream) (princ object stream) nil)
null
https://raw.githubusercontent.com/Incanus3/ExiL/de0f7c37538cecb7032cc1f2aa070524b0bc048d/src/utils/misc.lisp
lisp
TREES SETS PRINTING OUTPUT
(in-package :exil-utils) (defun tree-find-all-if (pred tree) (if (listp tree) (mapcan (lambda (subtree) (tree-find-all-if pred subtree)) tree) (when (funcall pred tree) (list tree)))) (defun set-equal-p (set1 set2 &key (test #'eql)) (null (set-exclusive-or set1 set2 :test test))) (defun fresh-format (stream control-string &rest args) (fresh-line stream) (apply #'format stream control-string args)) (defun fresh-princ (object &optional stream) (fresh-line stream) (princ object stream) nil)
6a1038a1cf9948390b08d7f31a745d9ccfc67ed7bc1544e24762a4924a715725
dsabanin/clj-pid
core.clj
(ns clj-pid.test.core (:use [clj-pid.core]) (:use [clojure.test])) (deftest replace-me ;; FIXME: write (is false "No tests have been written."))
null
https://raw.githubusercontent.com/dsabanin/clj-pid/5ce865b97aee94ebff3170f19e3cd2a4394a4e28/test/clj_pid/test/core.clj
clojure
FIXME: write
(ns clj-pid.test.core (:use [clj-pid.core]) (:use [clojure.test])) (is false "No tests have been written."))