_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
|
---|---|---|---|---|---|---|---|---|
d4e3ee527f0d08bd49308a01ac64a904322555f7e892f7c0ef7ef2eb82dd9981 | diku-dk/futhark | GPUMem.hs | # LANGUAGE TypeFamilies #
module Futhark.IR.GPUMem
( GPUMem,
-- * Simplification
simplifyProg,
simplifyStms,
simpleGPUMem,
-- * Module re-exports
module Futhark.IR.Mem,
module Futhark.IR.GPU.Op,
)
where
import Futhark.Analysis.PrimExp.Convert
import Futhark.Analysis.UsageTable qualified as UT
import Futhark.IR.Aliases (Aliases)
import Futhark.IR.GPU.Op
import Futhark.IR.GPU.Simplify (simplifyKernelOp)
import Futhark.IR.Mem
import Futhark.IR.Mem.Simplify
import Futhark.IR.TypeCheck qualified as TC
import Futhark.MonadFreshNames
import Futhark.Optimise.Simplify.Engine qualified as Engine
import Futhark.Pass
import Futhark.Pass.ExplicitAllocations (BuilderOps (..), mkLetNamesB', mkLetNamesB'')
data GPUMem
instance RepTypes GPUMem where
type LetDec GPUMem = LetDecMem
type FParamInfo GPUMem = FParamMem
type LParamInfo GPUMem = LParamMem
type RetType GPUMem = RetTypeMem
type BranchType GPUMem = BranchTypeMem
type OpC GPUMem = MemOp (HostOp NoOp)
instance ASTRep GPUMem where
expTypesFromPat = pure . map snd . bodyReturnsFromPat
instance OpReturns (HostOp NoOp GPUMem) where
opReturns (SegOp op) = segOpReturns op
opReturns k = extReturns <$> opType k
instance OpReturns (HostOp NoOp (Engine.Wise GPUMem)) where
opReturns (SegOp op) = segOpReturns op
opReturns k = extReturns <$> opType k
instance PrettyRep GPUMem
instance TC.Checkable GPUMem where
checkOp = typeCheckMemoryOp Nothing
where
GHC 9.2 goes into an infinite loop without the type annotation .
typeCheckMemoryOp ::
Maybe SegLevel ->
MemOp (HostOp NoOp) (Aliases GPUMem) ->
TC.TypeM GPUMem ()
typeCheckMemoryOp _ (Alloc size _) =
TC.require [Prim int64] size
typeCheckMemoryOp lvl (Inner op) =
typeCheckHostOp (typeCheckMemoryOp . Just) lvl (const $ pure ()) op
checkFParamDec = checkMemInfo
checkLParamDec = checkMemInfo
checkLetBoundDec = checkMemInfo
checkRetType = mapM_ $ TC.checkExtType . declExtTypeOf
primFParam name t = pure $ Param mempty name (MemPrim t)
matchPat = matchPatToExp
matchReturnType = matchFunctionReturnType
matchBranchType = matchBranchReturnType
matchLoopResult = matchLoopResultMem
instance BuilderOps GPUMem where
mkExpDecB _ _ = pure ()
mkBodyB stms res = pure $ Body () stms res
mkLetNamesB = mkLetNamesB' (Space "device") ()
instance BuilderOps (Engine.Wise GPUMem) where
mkExpDecB pat e = pure $ Engine.mkWiseExpDec pat () e
mkBodyB stms res = pure $ Engine.mkWiseBody () stms res
mkLetNamesB = mkLetNamesB'' (Space "device")
instance TraverseOpStms (Engine.Wise GPUMem) where
traverseOpStms = traverseMemOpStms (traverseHostOpStms (const pure))
simplifyProg :: Prog GPUMem -> PassM (Prog GPUMem)
simplifyProg = simplifyProgGeneric simpleGPUMem
simplifyStms ::
(HasScope GPUMem m, MonadFreshNames m) => Stms GPUMem -> m (Stms GPUMem)
simplifyStms = simplifyStmsGeneric simpleGPUMem
simpleGPUMem :: Engine.SimpleOps GPUMem
simpleGPUMem =
simpleGeneric usage $ simplifyKernelOp $ const $ pure (NoOp, mempty)
where
-- Slightly hackily and very inefficiently, we look at the inside
of SegOps to figure out the sizes of local memory allocations ,
-- and add usages for those sizes. This is necessary so the
-- simplifier will hoist those sizes out as far as possible (most
importantly , past the versioning If , but see also # 1569 ) .
usage (SegOp (SegMap _ _ _ kbody)) = localAllocs kbody
usage _ = mempty
localAllocs = foldMap stmLocalAlloc . kernelBodyStms
stmLocalAlloc = expLocalAlloc . stmExp
expLocalAlloc (Op (Alloc (Var v) _)) =
UT.sizeUsage v
expLocalAlloc (Op (Inner (SegOp (SegMap _ _ _ kbody)))) =
localAllocs kbody
expLocalAlloc _ =
mempty
| null | https://raw.githubusercontent.com/diku-dk/futhark/174e8d862def6f52d5c9a36fa3aa6e746049776e/src/Futhark/IR/GPUMem.hs | haskell | * Simplification
* Module re-exports
Slightly hackily and very inefficiently, we look at the inside
and add usages for those sizes. This is necessary so the
simplifier will hoist those sizes out as far as possible (most | # LANGUAGE TypeFamilies #
module Futhark.IR.GPUMem
( GPUMem,
simplifyProg,
simplifyStms,
simpleGPUMem,
module Futhark.IR.Mem,
module Futhark.IR.GPU.Op,
)
where
import Futhark.Analysis.PrimExp.Convert
import Futhark.Analysis.UsageTable qualified as UT
import Futhark.IR.Aliases (Aliases)
import Futhark.IR.GPU.Op
import Futhark.IR.GPU.Simplify (simplifyKernelOp)
import Futhark.IR.Mem
import Futhark.IR.Mem.Simplify
import Futhark.IR.TypeCheck qualified as TC
import Futhark.MonadFreshNames
import Futhark.Optimise.Simplify.Engine qualified as Engine
import Futhark.Pass
import Futhark.Pass.ExplicitAllocations (BuilderOps (..), mkLetNamesB', mkLetNamesB'')
data GPUMem
instance RepTypes GPUMem where
type LetDec GPUMem = LetDecMem
type FParamInfo GPUMem = FParamMem
type LParamInfo GPUMem = LParamMem
type RetType GPUMem = RetTypeMem
type BranchType GPUMem = BranchTypeMem
type OpC GPUMem = MemOp (HostOp NoOp)
instance ASTRep GPUMem where
expTypesFromPat = pure . map snd . bodyReturnsFromPat
instance OpReturns (HostOp NoOp GPUMem) where
opReturns (SegOp op) = segOpReturns op
opReturns k = extReturns <$> opType k
instance OpReturns (HostOp NoOp (Engine.Wise GPUMem)) where
opReturns (SegOp op) = segOpReturns op
opReturns k = extReturns <$> opType k
instance PrettyRep GPUMem
instance TC.Checkable GPUMem where
checkOp = typeCheckMemoryOp Nothing
where
GHC 9.2 goes into an infinite loop without the type annotation .
typeCheckMemoryOp ::
Maybe SegLevel ->
MemOp (HostOp NoOp) (Aliases GPUMem) ->
TC.TypeM GPUMem ()
typeCheckMemoryOp _ (Alloc size _) =
TC.require [Prim int64] size
typeCheckMemoryOp lvl (Inner op) =
typeCheckHostOp (typeCheckMemoryOp . Just) lvl (const $ pure ()) op
checkFParamDec = checkMemInfo
checkLParamDec = checkMemInfo
checkLetBoundDec = checkMemInfo
checkRetType = mapM_ $ TC.checkExtType . declExtTypeOf
primFParam name t = pure $ Param mempty name (MemPrim t)
matchPat = matchPatToExp
matchReturnType = matchFunctionReturnType
matchBranchType = matchBranchReturnType
matchLoopResult = matchLoopResultMem
instance BuilderOps GPUMem where
mkExpDecB _ _ = pure ()
mkBodyB stms res = pure $ Body () stms res
mkLetNamesB = mkLetNamesB' (Space "device") ()
instance BuilderOps (Engine.Wise GPUMem) where
mkExpDecB pat e = pure $ Engine.mkWiseExpDec pat () e
mkBodyB stms res = pure $ Engine.mkWiseBody () stms res
mkLetNamesB = mkLetNamesB'' (Space "device")
instance TraverseOpStms (Engine.Wise GPUMem) where
traverseOpStms = traverseMemOpStms (traverseHostOpStms (const pure))
simplifyProg :: Prog GPUMem -> PassM (Prog GPUMem)
simplifyProg = simplifyProgGeneric simpleGPUMem
simplifyStms ::
(HasScope GPUMem m, MonadFreshNames m) => Stms GPUMem -> m (Stms GPUMem)
simplifyStms = simplifyStmsGeneric simpleGPUMem
simpleGPUMem :: Engine.SimpleOps GPUMem
simpleGPUMem =
simpleGeneric usage $ simplifyKernelOp $ const $ pure (NoOp, mempty)
where
of SegOps to figure out the sizes of local memory allocations ,
importantly , past the versioning If , but see also # 1569 ) .
usage (SegOp (SegMap _ _ _ kbody)) = localAllocs kbody
usage _ = mempty
localAllocs = foldMap stmLocalAlloc . kernelBodyStms
stmLocalAlloc = expLocalAlloc . stmExp
expLocalAlloc (Op (Alloc (Var v) _)) =
UT.sizeUsage v
expLocalAlloc (Op (Inner (SegOp (SegMap _ _ _ kbody)))) =
localAllocs kbody
expLocalAlloc _ =
mempty
|
3a6dd93106154afba0f58110221eb98ad6df1551051122138cda17b5b5c1a518 | mirage/cowabloga | blog.ml |
* Copyright ( c ) 2010 - 2013 Anil Madhavapeddy < >
* Copyright ( c ) 2013 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2013 Anil Madhavapeddy <>
* Copyright (c) 2013 Richard Mortier <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
* Blog management : entries , ATOM feeds , etc .
An Atom feed has metadata plus a way to retrieve entries .
An Atom feed has metadata plus a way to retrieve entries. *)
open Printf
open Lwt.Infix
open Cow
open Atom_feed
* A feed is made up of Entries .
module Entry = struct
(** An entry in a feed: metadata plus a filename [body]. *)
type t = {
updated: Date.date;
authors: Atom.author list;
subject: string;
permalink: string;
body: string;
}
(** [permalink feed entry] returns the permalink URI for [entry] in [feed]. *)
let permalink feed entry =
sprintf "%s%s%s" feed.base_uri feed.id entry.permalink
* Compare two entries .
let compare a b =
compare (Date.atom_date b.updated) (Date.atom_date a.updated)
* [ to_html feed entry ] converts a blog entry in the given feed into an
Html.t fragment .
Html.t fragment. *)
let to_html ~feed ~entry =
feed.read_entry entry.body >|= fun content ->
let authors =
List.map (fun { Atom.name ; uri; _ } ->
let author_uri = match uri with
TODO
| Some uri -> Uri.of_string uri
in
name, author_uri)
entry.authors
in
let date = Date.html_of_date entry.updated in
let title =
let permalink = Uri.of_string (permalink feed entry) in
entry.subject, permalink
in
Foundation.Blog.post ~title ~date ~authors ~content
(** [to_atom feed entry] *)
let to_atom feed entry =
let links = [
Atom.mk_link ~rel:`alternate ~typ:"text/html"
(Uri.of_string (permalink feed entry))
] in
let meta = {
Atom.id = permalink feed entry;
title = entry.subject;
subtitle = None;
author =
( match entry.authors with
| [] -> None | author::_ -> Some author );
updated = Date.atom_date entry.updated;
rights = None;
links;
} in
feed.read_entry entry.body
>|= fun content ->
{
Atom.entry = meta;
summary = None;
base = None;
content
}
end
(** Entries separated by <hr /> tags *)
let default_separator = Html.hr
(** [to_html ?sep feed entries] renders a series of entries in a feed, separated
by [sep], defaulting to [default_separator]. *)
let to_html ?(sep=default_separator) ~feed ~entries =
let rec concat = function
| [] -> Lwt.return Html.empty
| hd::tl ->
Entry.to_html ~feed ~entry:hd >>= fun hd ->
concat tl >|= fun tl ->
Html.list [ hd; sep; tl ]
in
concat (List.sort Entry.compare entries)
* [ to_atom feed entries ] generates a time - ordered ATOM RSS [ feed ] for a
sequence of [ entries ] .
sequence of [entries]. *)
let to_atom ~feed ~entries =
let { title; subtitle; base_uri; id; rights; _ } = feed in
let id = base_uri ^ id in
let mk_uri x = Uri.of_string (id ^ x) in
let entries = List.sort Entry.compare entries in
let updated = Date.atom_date (List.hd entries).Entry.updated in
let links = [
Atom.mk_link (mk_uri "atom.xml");
Atom.mk_link ~rel:`alternate ~typ:"text/html" (mk_uri "")
] in
let atom_feed = { Atom.id; title; subtitle;
author=feed.author; rights; updated; links }
in
Lwt_list.map_s (Entry.to_atom feed) entries >|= fun entries ->
{ Atom.feed=atom_feed; entries }
(** [recent_posts feed entries] . *)
let recent_posts ?(active="") feed entries =
let entries = List.sort Entry.compare entries in
List.map (fun e ->
let link = Entry.(e.subject, Uri.of_string (Entry.permalink feed e)) in
if e.Entry.subject = active then
`active_link link
else
`link link
) entries
| null | https://raw.githubusercontent.com/mirage/cowabloga/2c256a92258f012c095bb72edcb639ad2fe164b3/lib/blog.ml | ocaml | * An entry in a feed: metadata plus a filename [body].
* [permalink feed entry] returns the permalink URI for [entry] in [feed].
* [to_atom feed entry]
* Entries separated by <hr /> tags
* [to_html ?sep feed entries] renders a series of entries in a feed, separated
by [sep], defaulting to [default_separator].
* [recent_posts feed entries] . |
* Copyright ( c ) 2010 - 2013 Anil Madhavapeddy < >
* Copyright ( c ) 2013 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2010-2013 Anil Madhavapeddy <>
* Copyright (c) 2013 Richard Mortier <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
* Blog management : entries , ATOM feeds , etc .
An Atom feed has metadata plus a way to retrieve entries .
An Atom feed has metadata plus a way to retrieve entries. *)
open Printf
open Lwt.Infix
open Cow
open Atom_feed
* A feed is made up of Entries .
module Entry = struct
type t = {
updated: Date.date;
authors: Atom.author list;
subject: string;
permalink: string;
body: string;
}
let permalink feed entry =
sprintf "%s%s%s" feed.base_uri feed.id entry.permalink
* Compare two entries .
let compare a b =
compare (Date.atom_date b.updated) (Date.atom_date a.updated)
* [ to_html feed entry ] converts a blog entry in the given feed into an
Html.t fragment .
Html.t fragment. *)
let to_html ~feed ~entry =
feed.read_entry entry.body >|= fun content ->
let authors =
List.map (fun { Atom.name ; uri; _ } ->
let author_uri = match uri with
TODO
| Some uri -> Uri.of_string uri
in
name, author_uri)
entry.authors
in
let date = Date.html_of_date entry.updated in
let title =
let permalink = Uri.of_string (permalink feed entry) in
entry.subject, permalink
in
Foundation.Blog.post ~title ~date ~authors ~content
let to_atom feed entry =
let links = [
Atom.mk_link ~rel:`alternate ~typ:"text/html"
(Uri.of_string (permalink feed entry))
] in
let meta = {
Atom.id = permalink feed entry;
title = entry.subject;
subtitle = None;
author =
( match entry.authors with
| [] -> None | author::_ -> Some author );
updated = Date.atom_date entry.updated;
rights = None;
links;
} in
feed.read_entry entry.body
>|= fun content ->
{
Atom.entry = meta;
summary = None;
base = None;
content
}
end
let default_separator = Html.hr
let to_html ?(sep=default_separator) ~feed ~entries =
let rec concat = function
| [] -> Lwt.return Html.empty
| hd::tl ->
Entry.to_html ~feed ~entry:hd >>= fun hd ->
concat tl >|= fun tl ->
Html.list [ hd; sep; tl ]
in
concat (List.sort Entry.compare entries)
* [ to_atom feed entries ] generates a time - ordered ATOM RSS [ feed ] for a
sequence of [ entries ] .
sequence of [entries]. *)
let to_atom ~feed ~entries =
let { title; subtitle; base_uri; id; rights; _ } = feed in
let id = base_uri ^ id in
let mk_uri x = Uri.of_string (id ^ x) in
let entries = List.sort Entry.compare entries in
let updated = Date.atom_date (List.hd entries).Entry.updated in
let links = [
Atom.mk_link (mk_uri "atom.xml");
Atom.mk_link ~rel:`alternate ~typ:"text/html" (mk_uri "")
] in
let atom_feed = { Atom.id; title; subtitle;
author=feed.author; rights; updated; links }
in
Lwt_list.map_s (Entry.to_atom feed) entries >|= fun entries ->
{ Atom.feed=atom_feed; entries }
let recent_posts ?(active="") feed entries =
let entries = List.sort Entry.compare entries in
List.map (fun e ->
let link = Entry.(e.subject, Uri.of_string (Entry.permalink feed e)) in
if e.Entry.subject = active then
`active_link link
else
`link link
) entries
|
662db49ce6144275482f3f5d0a915af7a8bad628001153c488cac93ed7b7a0d1 | aengelberg/paren.party | project.clj | (defproject paren.party "0.1.0-SNAPSHOT"
:description "PAREN PARTY"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies
[[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.238"]
[org.clojure/core.async "0.4.474"]
[manifold-cljs "0.1.7-1"]
[reagent "0.7.0"]
[cljsjs/soundjs "0.6.2-0"]]
:plugins
[[lein-figwheel "0.5.16"]
[lein-cljsbuild "1.1.7" :exclusions [[org.clojure/clojure]]]]
:source-paths ["src"]
:cljsbuild
{:builds
[{:id "dev"
:source-paths ["src"]
:figwheel {:on-jsload "paren.party/on-js-reload"}
:compiler {:main paren.party
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/paren.party.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true
:preloads [devtools.preload]}}
{:id "min"
:source-paths ["src"]
:compiler {:output-to "resources/public/js/compiled/paren.party.js"
:main paren.party
:optimizations :advanced
:pretty-print false}}]}
:figwheel
{ ;; :http-server-root "public" ;; default and assumes "resources"
: server - port 3449 ; ; default
: server - ip " 127.0.0.1 "
:css-dirs ["resources/public/css"] ;; watch and update CSS
Start an nREPL server into the running figwheel process
: nrepl - port 7888
Server Ring Handler ( optional )
;; if you want to embed a ring handler into the figwheel http-kit
;; server, this is for simple ring servers, if this
does n't work for you just run your own server :) ( see )
;; :ring-handler hello_world.server/handler
;; To be able to open files in your editor from the heads up display
;; you will need to put a script on your path.
;; that script will have to take a file path and a line number
;; ie. in ~/bin/myfile-opener
;; #! /bin/sh
emacsclient -n + $ 2 $ 1
;;
;; :open-file-command "myfile-opener"
;; if you are using emacsclient you can just use
;; :open-file-command "emacsclient"
;; if you want to disable the REPL
;; :repl false
;; to configure a different figwheel logfile path
;; :server-logfile "tmp/logs/figwheel-logfile.log"
;; to pipe all the output to the repl
;; :server-logfile false
}
;; -figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl
:profiles
{:dev
{:dependencies
[[binaryage/devtools "0.9.9"]
[figwheel-sidecar "0.5.16"]
[cider/piggieback "0.3.1"]]
:source-paths ["dev"]
:repl-options {:nrepl-middleware [cider.piggieback/wrap-cljs-repl]}
:clean-targets ^{:protect false} ["resources/public/js/compiled"
:target-path]}})
| null | https://raw.githubusercontent.com/aengelberg/paren.party/0ecd81b76793bbd9a3a7b8a500ff35325b77d44c/project.clj | clojure | :http-server-root "public" ;; default and assumes "resources"
; default
watch and update CSS
if you want to embed a ring handler into the figwheel http-kit
server, this is for simple ring servers, if this
:ring-handler hello_world.server/handler
To be able to open files in your editor from the heads up display
you will need to put a script on your path.
that script will have to take a file path and a line number
ie. in ~/bin/myfile-opener
#! /bin/sh
:open-file-command "myfile-opener"
if you are using emacsclient you can just use
:open-file-command "emacsclient"
if you want to disable the REPL
:repl false
to configure a different figwheel logfile path
:server-logfile "tmp/logs/figwheel-logfile.log"
to pipe all the output to the repl
:server-logfile false
-figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl | (defproject paren.party "0.1.0-SNAPSHOT"
:description "PAREN PARTY"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies
[[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.238"]
[org.clojure/core.async "0.4.474"]
[manifold-cljs "0.1.7-1"]
[reagent "0.7.0"]
[cljsjs/soundjs "0.6.2-0"]]
:plugins
[[lein-figwheel "0.5.16"]
[lein-cljsbuild "1.1.7" :exclusions [[org.clojure/clojure]]]]
:source-paths ["src"]
:cljsbuild
{:builds
[{:id "dev"
:source-paths ["src"]
:figwheel {:on-jsload "paren.party/on-js-reload"}
:compiler {:main paren.party
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/paren.party.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true
:preloads [devtools.preload]}}
{:id "min"
:source-paths ["src"]
:compiler {:output-to "resources/public/js/compiled/paren.party.js"
:main paren.party
:optimizations :advanced
:pretty-print false}}]}
:figwheel
: server - ip " 127.0.0.1 "
Start an nREPL server into the running figwheel process
: nrepl - port 7888
Server Ring Handler ( optional )
does n't work for you just run your own server :) ( see )
emacsclient -n + $ 2 $ 1
}
:profiles
{:dev
{:dependencies
[[binaryage/devtools "0.9.9"]
[figwheel-sidecar "0.5.16"]
[cider/piggieback "0.3.1"]]
:source-paths ["dev"]
:repl-options {:nrepl-middleware [cider.piggieback/wrap-cljs-repl]}
:clean-targets ^{:protect false} ["resources/public/js/compiled"
:target-path]}})
|
de12ebb821dafa337c065b395743e4f71aa48f99864d2b9871aca2543e5033f9 | TheClimateCorporation/geojson-schema | core.cljc | Copyright 2014 The Climate Corporation
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.
(ns com.climate.geojson-schema.core
(:require
[schema.core :refer [Any optional-key required-key eq one pred both either maybe named conditional Str Num Keyword]]))
(def ^:private position [Num])
(def ^:private geojson-base
{(optional-key :bbox) [Num]
;; GeoJSON objects may contain foreign members
;; #section-6.1
Keyword Any})
(def Point
"For type \"Point\" the :coordinates member must be a single position.
Cf. <#section-3.1.2>."
(merge geojson-base
{:coordinates position
:type (eq "Point")}))
(def MultiPoint
"For type \"MultiPoint\", the :coordinates member must be an array of
positions.
Cf. <#section-3.1.3>."
(merge geojson-base
{:coordinates [position]
:type (eq "MultiPoint")}))
(def ^:private linear-string-coordinates
[(one position "first")
(one position "second")
position])
(def LineString
"For type \"LineString\", the :coordinates member must be an array of
LineString coordinate arrays.
Cf. <#section-3.1.4>."
(merge geojson-base
{:coordinates linear-string-coordinates
:type (eq "LineString")}))
Linear Ring
A Linear ring is a closed loop , so it must have
at least 3 vertices .
;;;
Cord 0 * and * Cord 3
;;; #
;;; @ @
;;; @ @
;;; @ @
;;; @ @
;;; @ @
;;; @ @
;;; @ @
;;; @ @
;;; # #
@'''''''''''''''''''@
Cord 1 Cord 2
(defn- closed-loop
"A loop is closed if it has at least 4 coordinates and the first coordinate
is the last. There is no requirement in the spec that the closed shape not
intersect itself."
[coordinate-seq]
(and (= (first coordinate-seq)
(last coordinate-seq))
(>= (count coordinate-seq)
4)))
(def ^:private linear-ring-coordinates
(both [position] (pred closed-loop 'closed)))
(def LinearRing
"A LinearRing is closed LineString with 4 or more positions. The first and
last positions are equivalent (they represent equivalent points). Though a
LinearRing is not explicitly represented as a GeoJSON geometry type, it is
referred to in the Polygon geometry type definition."
(merge geojson-base
{:coordinates linear-ring-coordinates
:type (eq "LineString")}))
(def MultiLineString
"For type \"MultiLineString\", the :coordinates member must be an array of
LineString coordinate arrays.
Cf. <#section-3.1.5>."
(merge geojson-base
{:coordinates [linear-string-coordinates]
:type (eq "MultiLineString")}))
(def ^:private polygon-coords
[linear-ring-coordinates])
(def Polygon
"For type \"Polygon\", the :coordinates member must be an array of LinearRing
coordinate arrays. For Polygons with multiple rings, the first must be the
exterior ring and any others must be interior rings or holes.
Cf. <#section-3.1.6>."
(merge geojson-base
{:coordinates polygon-coords
:type (eq "Polygon")}))
(def MultiPolygon
"For type \"MultiPolygon\", the :coordinates member must be an array of
Polygon coordinate arrays.
Cf. <#section-3.1.7>."
(merge geojson-base
{:coordinates [polygon-coords]
:type (eq "MultiPolygon")}))
(def Geometry
"A geometry is a GeoJSON object where the type member's value is one of the
following strings: \"Point\", \"MultiPoint\", \"LineString\",
\"MultiLineString\", \"Polygon\", \"MultiPolygon\", or \"GeometryCollection\".
A GeoJSON geometry object of any type other than \"GeometryCollection\" must
have a member with the name \"coordinates\". The value of the coordinates
member is always an array. The structure for the elements in this array is
determined by the type of geometry.
This Geometry schema is everything excluding GeometryCollection.
Cf. <#section-3.1>."
(either Point
MultiPoint
LineString
MultiLineString
Polygon
MultiPolygon))
(def GeometryCollection
"A GeoJSON object with type \"GeometryCollection\" is a geometry object which
represents a collection of geometry objects.
A geometry collection must have a member with the name \"geometries\". The value
corresponding to \"geometries\" is an array. Each element in this array is a
GeoJSON geometry object.
A GeometryCollection should not include other GeometryCollections.
Cf. <#section-3.1.8>."
(merge geojson-base
{:geometries [Geometry]
:type (eq "GeometryCollection")}))
(def Feature
"A GeoJSON object with the type \"Feature\" is a feature object.
- A feature object must have a member with the name \"geometry\". The value of
the geometry member is a geometry object as defined above or a JSON null
value.
- A feature object must have a member with the name \"properties\". The value
of the properties member is an object (any JSON object or a JSON null value).
- If a feature has a commonly used identifier, that identifier should be
included as a member of the feature object with the name \"id\".
Cf. <#section-3.2>."
(merge geojson-base
{:geometry Geometry
:type (eq "Feature")
:properties (maybe Any)
(optional-key :id) (either Str Num)}))
(def FeatureCollection
"A GeoJSON object with the type \"FeatureCollection\" is a feature collection
object.
An object of type \"FeatureCollection\" must have a member with the name
\"features\". The value corresponding to \"features\" is an array. Each
element in the array is a feature object as defined above.
Cf. <#section-3.3>."
(merge geojson-base
{:features [Feature]
:type (eq "FeatureCollection")}))
(def GeoJSON
"This is any valid GeoJSON object.
Cf. <>."
(either Geometry
GeometryCollection
Feature
FeatureCollection))
| null | https://raw.githubusercontent.com/TheClimateCorporation/geojson-schema/6571958391b0a41b5d53e4b1d14da1eeae6d6283/src/com/climate/geojson_schema/core.cljc | clojure |
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.
GeoJSON objects may contain foreign members
#section-6.1
#
@ @
@ @
@ @
@ @
@ @
@ @
@ @
@ @
# # | Copyright 2014 The Climate Corporation
distributed under the License is distributed on an " AS IS " BASIS ,
(ns com.climate.geojson-schema.core
(:require
[schema.core :refer [Any optional-key required-key eq one pred both either maybe named conditional Str Num Keyword]]))
(def ^:private position [Num])
(def ^:private geojson-base
{(optional-key :bbox) [Num]
Keyword Any})
(def Point
"For type \"Point\" the :coordinates member must be a single position.
Cf. <#section-3.1.2>."
(merge geojson-base
{:coordinates position
:type (eq "Point")}))
(def MultiPoint
"For type \"MultiPoint\", the :coordinates member must be an array of
positions.
Cf. <#section-3.1.3>."
(merge geojson-base
{:coordinates [position]
:type (eq "MultiPoint")}))
(def ^:private linear-string-coordinates
[(one position "first")
(one position "second")
position])
(def LineString
"For type \"LineString\", the :coordinates member must be an array of
LineString coordinate arrays.
Cf. <#section-3.1.4>."
(merge geojson-base
{:coordinates linear-string-coordinates
:type (eq "LineString")}))
Linear Ring
A Linear ring is a closed loop , so it must have
at least 3 vertices .
Cord 0 * and * Cord 3
@'''''''''''''''''''@
Cord 1 Cord 2
(defn- closed-loop
"A loop is closed if it has at least 4 coordinates and the first coordinate
is the last. There is no requirement in the spec that the closed shape not
intersect itself."
[coordinate-seq]
(and (= (first coordinate-seq)
(last coordinate-seq))
(>= (count coordinate-seq)
4)))
(def ^:private linear-ring-coordinates
(both [position] (pred closed-loop 'closed)))
(def LinearRing
"A LinearRing is closed LineString with 4 or more positions. The first and
last positions are equivalent (they represent equivalent points). Though a
LinearRing is not explicitly represented as a GeoJSON geometry type, it is
referred to in the Polygon geometry type definition."
(merge geojson-base
{:coordinates linear-ring-coordinates
:type (eq "LineString")}))
(def MultiLineString
"For type \"MultiLineString\", the :coordinates member must be an array of
LineString coordinate arrays.
Cf. <#section-3.1.5>."
(merge geojson-base
{:coordinates [linear-string-coordinates]
:type (eq "MultiLineString")}))
(def ^:private polygon-coords
[linear-ring-coordinates])
(def Polygon
"For type \"Polygon\", the :coordinates member must be an array of LinearRing
coordinate arrays. For Polygons with multiple rings, the first must be the
exterior ring and any others must be interior rings or holes.
Cf. <#section-3.1.6>."
(merge geojson-base
{:coordinates polygon-coords
:type (eq "Polygon")}))
(def MultiPolygon
"For type \"MultiPolygon\", the :coordinates member must be an array of
Polygon coordinate arrays.
Cf. <#section-3.1.7>."
(merge geojson-base
{:coordinates [polygon-coords]
:type (eq "MultiPolygon")}))
(def Geometry
"A geometry is a GeoJSON object where the type member's value is one of the
following strings: \"Point\", \"MultiPoint\", \"LineString\",
\"MultiLineString\", \"Polygon\", \"MultiPolygon\", or \"GeometryCollection\".
A GeoJSON geometry object of any type other than \"GeometryCollection\" must
have a member with the name \"coordinates\". The value of the coordinates
member is always an array. The structure for the elements in this array is
determined by the type of geometry.
This Geometry schema is everything excluding GeometryCollection.
Cf. <#section-3.1>."
(either Point
MultiPoint
LineString
MultiLineString
Polygon
MultiPolygon))
(def GeometryCollection
"A GeoJSON object with type \"GeometryCollection\" is a geometry object which
represents a collection of geometry objects.
A geometry collection must have a member with the name \"geometries\". The value
corresponding to \"geometries\" is an array. Each element in this array is a
GeoJSON geometry object.
A GeometryCollection should not include other GeometryCollections.
Cf. <#section-3.1.8>."
(merge geojson-base
{:geometries [Geometry]
:type (eq "GeometryCollection")}))
(def Feature
"A GeoJSON object with the type \"Feature\" is a feature object.
- A feature object must have a member with the name \"geometry\". The value of
the geometry member is a geometry object as defined above or a JSON null
value.
- A feature object must have a member with the name \"properties\". The value
of the properties member is an object (any JSON object or a JSON null value).
- If a feature has a commonly used identifier, that identifier should be
included as a member of the feature object with the name \"id\".
Cf. <#section-3.2>."
(merge geojson-base
{:geometry Geometry
:type (eq "Feature")
:properties (maybe Any)
(optional-key :id) (either Str Num)}))
(def FeatureCollection
"A GeoJSON object with the type \"FeatureCollection\" is a feature collection
object.
An object of type \"FeatureCollection\" must have a member with the name
\"features\". The value corresponding to \"features\" is an array. Each
element in the array is a feature object as defined above.
Cf. <#section-3.3>."
(merge geojson-base
{:features [Feature]
:type (eq "FeatureCollection")}))
(def GeoJSON
"This is any valid GeoJSON object.
Cf. <>."
(either Geometry
GeometryCollection
Feature
FeatureCollection))
|
dc57c0bf678f36de1dac5de18a163daa07ff5f4d738a0c10793e79b749501882 | chrisdone/ircbrowse | Extra.hs | module Data.String.Extra where
import Data.Char
trim :: String -> String
trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse
limitLen :: Int -> [Char] -> [Char]
limitLen n xs | length xs > n = take (max 1 (n-2)) xs ++ "…"
| otherwise = xs
| null | https://raw.githubusercontent.com/chrisdone/ircbrowse/d956aaf185500792224b6b0c209eb67c179322a4/src/Data/String/Extra.hs | haskell | module Data.String.Extra where
import Data.Char
trim :: String -> String
trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse
limitLen :: Int -> [Char] -> [Char]
limitLen n xs | length xs > n = take (max 1 (n-2)) xs ++ "…"
| otherwise = xs
|
|
962b76ae0b47c39e29d0383f04337748e456d9ab0d3bf58899e765b5e3e8455e | hpyhacking/openpoker | ranking.erl | -module(ranking).
-behaviour(op_exch_mod).
-export([start/2, dispatch/2]).
-export([rank/1, notify/1]).
-include("openpoker.hrl").
%%%
%%% callback
%%%
start([], Ctx) ->
notify(Ctx),
{stop, Ctx}.
dispatch(_R, _Ctx) ->
ok.
%%%
%%% client
%%%
rank(#texas{seats = S, board = Cards}) ->
Seats = seat:lookup(?PS_STANDING, S),
rank(Seats, Cards, []).
notify(Ctx) ->
notify(rank(Ctx), Ctx).
%%%
%%% private
%%%
rank([], _Cards, Acc) -> Acc;
rank([H = #seat{hand = Hand}|T], Cards, Acc) ->
RH = hand:rank(hand:merge(Hand, Cards)),
rank(T, Cards, [H#seat{hand = RH}|Acc]).
notify([], _Ctx) -> ok;
notify([#seat{pid = PId, process = P, hand = Hand, sn = SN}|T], Ctx = #texas{gid = Id}) ->
#player_hand{rank = Rank, high1 = H1, high2 = H2, suit = Suit} = hand:player_hand(Hand),
player:notify(P, #notify_hand{ game = Id, player = PId, sn = SN, rank = Rank, high1 = H1, high2 = H2, suit = Suit}),
notify(T, Ctx).
| null | https://raw.githubusercontent.com/hpyhacking/openpoker/643193c94f34096cdcfcd610bdb1f18e7bf1e45e/src/mods/ranking.erl | erlang |
callback
client
private
| -module(ranking).
-behaviour(op_exch_mod).
-export([start/2, dispatch/2]).
-export([rank/1, notify/1]).
-include("openpoker.hrl").
start([], Ctx) ->
notify(Ctx),
{stop, Ctx}.
dispatch(_R, _Ctx) ->
ok.
rank(#texas{seats = S, board = Cards}) ->
Seats = seat:lookup(?PS_STANDING, S),
rank(Seats, Cards, []).
notify(Ctx) ->
notify(rank(Ctx), Ctx).
rank([], _Cards, Acc) -> Acc;
rank([H = #seat{hand = Hand}|T], Cards, Acc) ->
RH = hand:rank(hand:merge(Hand, Cards)),
rank(T, Cards, [H#seat{hand = RH}|Acc]).
notify([], _Ctx) -> ok;
notify([#seat{pid = PId, process = P, hand = Hand, sn = SN}|T], Ctx = #texas{gid = Id}) ->
#player_hand{rank = Rank, high1 = H1, high2 = H2, suit = Suit} = hand:player_hand(Hand),
player:notify(P, #notify_hand{ game = Id, player = PId, sn = SN, rank = Rank, high1 = H1, high2 = H2, suit = Suit}),
notify(T, Ctx).
|
cae6a8139755dfad9f575f133733478d1cd8d30cd9879097566740488231927e | infinitelives/infinitelives.pixi | core.cljs | (ns pixelfont.core
(:require [infinitelives.pixi.canvas :as c]
[infinitelives.pixi.events :as e]
[infinitelives.pixi.resources :as r]
[infinitelives.pixi.texture :as t]
[infinitelives.pixi.sprite :as s]
[infinitelives.pixi.pixelfont :as pf]
[cljs.core.async :refer [<!]])
(:require-macros [cljs.core.async.macros :refer [go]]
[infinitelives.pixi.pixelfont :as pf]))
(defonce canvas
(c/init {:layers [:bg]
:background 0x404070
:expand true
:engine :webgl}))
(defonce main-thread
(go
(<! (r/load-resources canvas :bg ["img/fonts.png"]))
(pf/pixel-font :big "img/fonts.png" [127 84] [500 128]
:chars ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789!?#`'.,"]
:kerning {"fo" -2 "ro" -1 "la" -1 }
:space 5)
(c/with-sprite canvas :bg
[text (pf/make-text :big "The quick brown fox jumped over the lazy sequence!"
:tint 0xff0000
:scale 3
:rotation 0
:engine :canvas
)]
(loop [f 0]
(s/set-rotation! text (* 0.002 f))
(s/set-scale! text (+ 2 (* 2 (Math/abs (Math/sin (* f 0.02))))))
(<! (e/next-frame))
(recur (inc f))))))
| null | https://raw.githubusercontent.com/infinitelives/infinitelives.pixi/877bd247f2bae327bc3a3bd70162a7880de9a0c7/examples/pixelfont/src/pixelfont/core.cljs | clojure | (ns pixelfont.core
(:require [infinitelives.pixi.canvas :as c]
[infinitelives.pixi.events :as e]
[infinitelives.pixi.resources :as r]
[infinitelives.pixi.texture :as t]
[infinitelives.pixi.sprite :as s]
[infinitelives.pixi.pixelfont :as pf]
[cljs.core.async :refer [<!]])
(:require-macros [cljs.core.async.macros :refer [go]]
[infinitelives.pixi.pixelfont :as pf]))
(defonce canvas
(c/init {:layers [:bg]
:background 0x404070
:expand true
:engine :webgl}))
(defonce main-thread
(go
(<! (r/load-resources canvas :bg ["img/fonts.png"]))
(pf/pixel-font :big "img/fonts.png" [127 84] [500 128]
:chars ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789!?#`'.,"]
:kerning {"fo" -2 "ro" -1 "la" -1 }
:space 5)
(c/with-sprite canvas :bg
[text (pf/make-text :big "The quick brown fox jumped over the lazy sequence!"
:tint 0xff0000
:scale 3
:rotation 0
:engine :canvas
)]
(loop [f 0]
(s/set-rotation! text (* 0.002 f))
(s/set-scale! text (+ 2 (* 2 (Math/abs (Math/sin (* f 0.02))))))
(<! (e/next-frame))
(recur (inc f))))))
|
|
7efac62a0308f9c1a4e7fbcb8f6cca9ab722b0c4c6ff9246ad4480989a66646d | diku-dk/futhark | CUDA.hs | -- | Code generation for ImpCode with CUDA kernels.
module Futhark.CodeGen.ImpGen.CUDA
( compileProg,
Warnings,
)
where
import Data.Bifunctor (second)
import Futhark.CodeGen.ImpCode.OpenCL
import Futhark.CodeGen.ImpGen.GPU
import Futhark.CodeGen.ImpGen.GPU.ToOpenCL
import Futhark.IR.GPUMem
import Futhark.MonadFreshNames
-- | Compile the program to ImpCode with CUDA kernels.
compileProg :: MonadFreshNames m => Prog GPUMem -> m (Warnings, Program)
compileProg prog = second kernelsToCUDA <$> compileProgCUDA prog
| null | https://raw.githubusercontent.com/diku-dk/futhark/7c8494f809dbb1e41775471e88270068d8632407/src/Futhark/CodeGen/ImpGen/CUDA.hs | haskell | | Code generation for ImpCode with CUDA kernels.
| Compile the program to ImpCode with CUDA kernels. | module Futhark.CodeGen.ImpGen.CUDA
( compileProg,
Warnings,
)
where
import Data.Bifunctor (second)
import Futhark.CodeGen.ImpCode.OpenCL
import Futhark.CodeGen.ImpGen.GPU
import Futhark.CodeGen.ImpGen.GPU.ToOpenCL
import Futhark.IR.GPUMem
import Futhark.MonadFreshNames
compileProg :: MonadFreshNames m => Prog GPUMem -> m (Warnings, Program)
compileProg prog = second kernelsToCUDA <$> compileProgCUDA prog
|
15f1e95712e77a52661074121c28a75ad4dc2bb76f80cf3ac9879fd0527bb81e | racket/math | matrix-subspace.rkt | #lang typed/racket/base
(require racket/fixnum
racket/list
"matrix-types.rkt"
"matrix-basic.rkt"
"matrix-gauss-elim.rkt"
"utils.rkt"
"../array/array-indexing.rkt"
"../array/array-constructors.rkt"
"../array/array-struct.rkt")
(provide
matrix-rank
matrix-nullity
matrix-col-space)
(: matrix-rank : (Matrix Number) -> Index)
;; Returns the dimension of the column space (equiv. row space) of M
(define (matrix-rank M)
(define n (matrix-num-cols M))
(define-values (_ cols-without-pivot) (matrix-gauss-elim M))
(assert (- n (length cols-without-pivot)) index?))
(: matrix-nullity : (Matrix Number) -> Index)
;; Returns the dimension of the null space of M
(define (matrix-nullity M)
(define-values (_ cols-without-pivot)
(matrix-gauss-elim (ensure-matrix 'matrix-nullity M)))
(length cols-without-pivot))
(: maybe-cons-submatrix (All (A) ((Matrix A) Nonnegative-Fixnum Nonnegative-Fixnum (Listof (Matrix A))
-> (Listof (Matrix A)))))
(define (maybe-cons-submatrix M j0 j1 Bs)
(cond [(= j0 j1) Bs]
[else (cons (submatrix M (::) (:: j0 j1)) Bs)]))
(: matrix-col-space/ns (All (A) (case-> ((Matrix Flonum) -> (U #f (Matrix Flonum)))
((Matrix Real) -> (U #f (Matrix Real)))
((Matrix Float-Complex) -> (U #f (Matrix Float-Complex)))
((Matrix Number) -> (U #f (Matrix Number))))))
(define (matrix-col-space/ns M)
(define n (matrix-num-cols M))
(define-values (_ wps) (matrix-gauss-elim M))
(cond [(empty? wps) M]
[(= (length wps) n) #f]
[else
(define next-j (first wps))
(define Bs (maybe-cons-submatrix M 0 next-j empty))
(let loop ([#{j : Index} next-j] [wps (rest wps)] [Bs Bs])
(cond [(empty? wps)
(matrix-augment (reverse (maybe-cons-submatrix M (fx+ j 1) n Bs)))]
[else
(define next-j (first wps))
(loop next-j (rest wps) (maybe-cons-submatrix M (fx+ j 1) next-j Bs))]))]))
(: matrix-col-space (All (A) (case-> ((Matrix Flonum) -> (Array Flonum))
((Matrix Flonum) (-> A) -> (U A (Matrix Flonum)))
((Matrix Real) -> (Array Real))
((Matrix Real) (-> A) -> (U A (Matrix Real)))
((Matrix Float-Complex) -> (Array Float-Complex))
((Matrix Float-Complex) (-> A) -> (U A (Matrix Float-Complex)))
((Matrix Number) -> (Array Number))
((Matrix Number) (-> A) -> (U A (Matrix Number))))))
(define matrix-col-space
(case-lambda
[(M) (matrix-col-space M (λ ()
(define x00 (matrix-ref M 0 0))
(make-array (vector 0 (matrix-num-cols M)) (zero* x00))))]
[(M fail)
(define S (parameterize ([array-strictness #f])
(matrix-col-space/ns M)))
(if S (array-default-strict S) (fail))]))
| null | https://raw.githubusercontent.com/racket/math/dcd2ea1893dc5b45b26c8312997917a15fcd1c4a/math-lib/math/private/matrix/matrix-subspace.rkt | racket | Returns the dimension of the column space (equiv. row space) of M
Returns the dimension of the null space of M | #lang typed/racket/base
(require racket/fixnum
racket/list
"matrix-types.rkt"
"matrix-basic.rkt"
"matrix-gauss-elim.rkt"
"utils.rkt"
"../array/array-indexing.rkt"
"../array/array-constructors.rkt"
"../array/array-struct.rkt")
(provide
matrix-rank
matrix-nullity
matrix-col-space)
(: matrix-rank : (Matrix Number) -> Index)
(define (matrix-rank M)
(define n (matrix-num-cols M))
(define-values (_ cols-without-pivot) (matrix-gauss-elim M))
(assert (- n (length cols-without-pivot)) index?))
(: matrix-nullity : (Matrix Number) -> Index)
(define (matrix-nullity M)
(define-values (_ cols-without-pivot)
(matrix-gauss-elim (ensure-matrix 'matrix-nullity M)))
(length cols-without-pivot))
(: maybe-cons-submatrix (All (A) ((Matrix A) Nonnegative-Fixnum Nonnegative-Fixnum (Listof (Matrix A))
-> (Listof (Matrix A)))))
(define (maybe-cons-submatrix M j0 j1 Bs)
(cond [(= j0 j1) Bs]
[else (cons (submatrix M (::) (:: j0 j1)) Bs)]))
(: matrix-col-space/ns (All (A) (case-> ((Matrix Flonum) -> (U #f (Matrix Flonum)))
((Matrix Real) -> (U #f (Matrix Real)))
((Matrix Float-Complex) -> (U #f (Matrix Float-Complex)))
((Matrix Number) -> (U #f (Matrix Number))))))
(define (matrix-col-space/ns M)
(define n (matrix-num-cols M))
(define-values (_ wps) (matrix-gauss-elim M))
(cond [(empty? wps) M]
[(= (length wps) n) #f]
[else
(define next-j (first wps))
(define Bs (maybe-cons-submatrix M 0 next-j empty))
(let loop ([#{j : Index} next-j] [wps (rest wps)] [Bs Bs])
(cond [(empty? wps)
(matrix-augment (reverse (maybe-cons-submatrix M (fx+ j 1) n Bs)))]
[else
(define next-j (first wps))
(loop next-j (rest wps) (maybe-cons-submatrix M (fx+ j 1) next-j Bs))]))]))
(: matrix-col-space (All (A) (case-> ((Matrix Flonum) -> (Array Flonum))
((Matrix Flonum) (-> A) -> (U A (Matrix Flonum)))
((Matrix Real) -> (Array Real))
((Matrix Real) (-> A) -> (U A (Matrix Real)))
((Matrix Float-Complex) -> (Array Float-Complex))
((Matrix Float-Complex) (-> A) -> (U A (Matrix Float-Complex)))
((Matrix Number) -> (Array Number))
((Matrix Number) (-> A) -> (U A (Matrix Number))))))
(define matrix-col-space
(case-lambda
[(M) (matrix-col-space M (λ ()
(define x00 (matrix-ref M 0 0))
(make-array (vector 0 (matrix-num-cols M)) (zero* x00))))]
[(M fail)
(define S (parameterize ([array-strictness #f])
(matrix-col-space/ns M)))
(if S (array-default-strict S) (fail))]))
|
2ddcc290ed9cfaf3332f850d6a3cd654e2c794a3e9e34e5fd89fb715d39fa049 | jumper149/go | Game.hs | module Go.Game.Game ( Game (..)
, AssociatedPlayer
, AssociatedStone
, updateBoard
, GameCoord (..)
, Stone (..)
) where
import Data.Aeson (FromJSON, ToJSON)
import qualified Data.Set as S
import GHC.Generics
import GHC.TypeLits
import Go.Game.Player
-- | The states of a spot for a stone are represented by this data type.
data Stone p = Free
| Stone p
deriving (Eq, Ord, Generic, Read, Show)
instance (Generic p, FromJSON p) => FromJSON (Stone p)
instance (Generic p, ToJSON p) => ToJSON (Stone p)
-- | Stones placed on coordinates can form chains which are represented by this data type.
data Chain p c = Chain (Stone p) (S.Set c)
deriving (Eq, Ord, Generic, Read, Show)
-- | Check if a coordinate is part of chain. Does not check if stones are matching.
partOfChain :: (Ord c, KnownNat n) => c -> Chain (PlayerN n) c -> Bool
partOfChain c (Chain _ cs) = c `S.member` cs
-- | Remove chains of free stones and put them in an ordered list, that is cycled, so that the
-- chains of the given player are last.
prepChains :: KnownNat n => PlayerN n -> S.Set (Chain (PlayerN n) c) -> [Chain (PlayerN n) c]
prepChains player = swapJoin . split . removeFrees
where removeFrees = S.filter $ \ (Chain stone _) -> stone /= Free
split = S.spanAntitone (\ (Chain stone _) -> stone <= Stone player)
swapJoin (a,b) = S.toAscList b <> S.toAscList a
-- | A class representing coordinates. All coordinates should be enumerable with
' [ minBound .. maxBound ] ' , so ' Bounded ' and ' ' should be declared carefully . The ordering for
' ' can be arbitrary .
class (Bounded c, Enum c, Eq c, Ord c) => GameCoord c where
-- | Return a list of all coordinates covering the board.
coords :: [c]
coords = [ minBound .. maxBound ]
-- | Return a list of all adjacent coordinates.
libertyCoords :: c -> [c]
class (Eq b, GameCoord (AssociatedCoord b), KnownNat (AssociatedPlayerCount b)) => Game b where
type AssociatedCoord b
type AssociatedPlayerCount b :: Nat
-- | Return an empty board.
empty :: b
-- | Returns the stone.
getStone :: b -> AssociatedCoord b -> Stone (PlayerN (AssociatedPlayerCount b))
-- | Places a stone on a coordinate and returns the board.
putStone :: b -> AssociatedCoord b -> Stone (PlayerN (AssociatedPlayerCount b)) -> b
type AssociatedPlayer b = PlayerN (AssociatedPlayerCount b)
type AssociatedStone b = Stone (AssociatedPlayer b)
accChain :: forall b. Game b => b -> AssociatedStone b -> AssociatedCoord b -> S.Set (AssociatedCoord b) -> S.Set (AssociatedCoord b)
accChain board stone coord acc = foldr (accChain board stone) newAcc neededSames
where newAcc = acc `S.union` sames
neededSames = sames `S.difference` acc
sames = S.filter ((== stone) . getStone board) libs
libs = S.fromList $ libertyCoords coord
chain :: forall b. Game b => b -> AssociatedCoord b -> Chain (AssociatedPlayer b) (AssociatedCoord b)
chain board coord = Chain stone crds
where stone = getStone board coord
crds = accChain board stone coord acc
acc = S.singleton coord
accChains :: forall b. Game b => b -> S.Set (Chain (AssociatedPlayer b) (AssociatedCoord b))
accChains board = foldr addCoord S.empty coords -- TODO: only occurence of 'coords', maybe remove that method completely?
where addCoord crd chns = if any (partOfChain crd) chns
then chns
else chain board crd `S.insert` chns
hasLiberty :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> Bool
hasLiberty board (Chain _ crds) = or bools
where bools = S.map ((== Free) . (getStone board :: (AssociatedCoord b -> AssociatedStone b))) libs
libs = S.unions $ S.map (S.fromList . libertyCoords) crds
removeChain :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> b
removeChain board (Chain _ crds) = foldl putFree board crds
where putFree brd crd = putStone brd crd Free
removeSurrounded :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> b
removeSurrounded brd chn = if hasLiberty brd chn
then brd
else removeChain brd chn
-- | Remove chains without liberties. Give player as an argument to solve atari. Return board.
updateBoard :: forall b. Game b => b -> AssociatedPlayer b -> b
updateBoard board player = foldl removeSurrounded board chains
where chains = prepChains player $ accChains board
| null | https://raw.githubusercontent.com/jumper149/go/603e61f64e8e7c890bbc914fef6033b5ed7dd005/src/Go/Game/Game.hs | haskell | | The states of a spot for a stone are represented by this data type.
| Stones placed on coordinates can form chains which are represented by this data type.
| Check if a coordinate is part of chain. Does not check if stones are matching.
| Remove chains of free stones and put them in an ordered list, that is cycled, so that the
chains of the given player are last.
| A class representing coordinates. All coordinates should be enumerable with
| Return a list of all coordinates covering the board.
| Return a list of all adjacent coordinates.
| Return an empty board.
| Returns the stone.
| Places a stone on a coordinate and returns the board.
TODO: only occurence of 'coords', maybe remove that method completely?
| Remove chains without liberties. Give player as an argument to solve atari. Return board. | module Go.Game.Game ( Game (..)
, AssociatedPlayer
, AssociatedStone
, updateBoard
, GameCoord (..)
, Stone (..)
) where
import Data.Aeson (FromJSON, ToJSON)
import qualified Data.Set as S
import GHC.Generics
import GHC.TypeLits
import Go.Game.Player
data Stone p = Free
| Stone p
deriving (Eq, Ord, Generic, Read, Show)
instance (Generic p, FromJSON p) => FromJSON (Stone p)
instance (Generic p, ToJSON p) => ToJSON (Stone p)
data Chain p c = Chain (Stone p) (S.Set c)
deriving (Eq, Ord, Generic, Read, Show)
partOfChain :: (Ord c, KnownNat n) => c -> Chain (PlayerN n) c -> Bool
partOfChain c (Chain _ cs) = c `S.member` cs
prepChains :: KnownNat n => PlayerN n -> S.Set (Chain (PlayerN n) c) -> [Chain (PlayerN n) c]
prepChains player = swapJoin . split . removeFrees
where removeFrees = S.filter $ \ (Chain stone _) -> stone /= Free
split = S.spanAntitone (\ (Chain stone _) -> stone <= Stone player)
swapJoin (a,b) = S.toAscList b <> S.toAscList a
' [ minBound .. maxBound ] ' , so ' Bounded ' and ' ' should be declared carefully . The ordering for
' ' can be arbitrary .
class (Bounded c, Enum c, Eq c, Ord c) => GameCoord c where
coords :: [c]
coords = [ minBound .. maxBound ]
libertyCoords :: c -> [c]
class (Eq b, GameCoord (AssociatedCoord b), KnownNat (AssociatedPlayerCount b)) => Game b where
type AssociatedCoord b
type AssociatedPlayerCount b :: Nat
empty :: b
getStone :: b -> AssociatedCoord b -> Stone (PlayerN (AssociatedPlayerCount b))
putStone :: b -> AssociatedCoord b -> Stone (PlayerN (AssociatedPlayerCount b)) -> b
type AssociatedPlayer b = PlayerN (AssociatedPlayerCount b)
type AssociatedStone b = Stone (AssociatedPlayer b)
accChain :: forall b. Game b => b -> AssociatedStone b -> AssociatedCoord b -> S.Set (AssociatedCoord b) -> S.Set (AssociatedCoord b)
accChain board stone coord acc = foldr (accChain board stone) newAcc neededSames
where newAcc = acc `S.union` sames
neededSames = sames `S.difference` acc
sames = S.filter ((== stone) . getStone board) libs
libs = S.fromList $ libertyCoords coord
chain :: forall b. Game b => b -> AssociatedCoord b -> Chain (AssociatedPlayer b) (AssociatedCoord b)
chain board coord = Chain stone crds
where stone = getStone board coord
crds = accChain board stone coord acc
acc = S.singleton coord
accChains :: forall b. Game b => b -> S.Set (Chain (AssociatedPlayer b) (AssociatedCoord b))
where addCoord crd chns = if any (partOfChain crd) chns
then chns
else chain board crd `S.insert` chns
hasLiberty :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> Bool
hasLiberty board (Chain _ crds) = or bools
where bools = S.map ((== Free) . (getStone board :: (AssociatedCoord b -> AssociatedStone b))) libs
libs = S.unions $ S.map (S.fromList . libertyCoords) crds
removeChain :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> b
removeChain board (Chain _ crds) = foldl putFree board crds
where putFree brd crd = putStone brd crd Free
removeSurrounded :: forall b. Game b => b -> Chain (AssociatedPlayer b) (AssociatedCoord b) -> b
removeSurrounded brd chn = if hasLiberty brd chn
then brd
else removeChain brd chn
updateBoard :: forall b. Game b => b -> AssociatedPlayer b -> b
updateBoard board player = foldl removeSurrounded board chains
where chains = prepChains player $ accChains board
|
c0e17253793685a762a2ce5ad7e1115a79f2db84d1ace3eda03d7f87eff16d9d | arekinath/esaml | sp_handler.erl | esaml - SAML for erlang
%%
Copyright ( c ) 2013 , and the University of Queensland
%% All rights reserved.
%%
Distributed subject to the terms of the 2 - clause BSD license , see
%% the LICENSE file in the root of the distribution.
-module(sp_handler).
-include_lib("esaml/include/esaml.hrl").
-record(state, {sp, idp}).
-export([init/3, handle/2, terminate/3]).
init(_Transport, Req, _Args) ->
Load the certificate and private key for the SP
PrivKey = esaml_util:load_private_key("test.key"),
Cert = esaml_util:load_certificate("test.crt"),
% We build all of our URLs (in metadata, and in requests) based on this
Base = "",
Certificate fingerprints to accept from our IDP
FPs = ["6b:d1:24:4b:38:cf:6c:1f:4e:53:56:c5:c8:90:63:68:55:5e:27:28"],
SP = esaml_sp:setup(#esaml_sp{
key = PrivKey,
certificate = Cert,
trusted_fingerprints = FPs,
consume_uri = Base ++ "/consume",
metadata_uri = Base ++ "/metadata",
org = #esaml_org{
name = "Foo Bar",
displayname = "Foo Bar",
url = ""
},
tech = #esaml_contact{
name = "Foo Bar",
email = ""
}
}),
Rather than copying the IDP 's metadata into our code , we 'll just fetch it
( this call will cache after the first time around , so it will be fast )
IdpMeta = esaml_util:load_metadata(""),
{ok, Req, #state{sp = SP, idp = IdpMeta}}.
handle(Req, S = #state{}) ->
{Operation, Req2} = cowboy_req:binding(operation, Req),
{Method, Req3} = cowboy_req:method(Req2),
handle(Method, Operation, Req3, S).
Return our SP metadata as signed XML
handle(<<"GET">>, <<"metadata">>, Req, S = #state{sp = SP}) ->
{ok, Req2} = esaml_cowboy:reply_with_metadata(SP, Req),
{ok, Req2, S};
Visit /saml / auth to start the authentication process -- we will make an AuthnRequest
and send it to our IDP
handle(<<"GET">>, <<"auth">>, Req, S = #state{sp = SP,
idp = #esaml_idp_metadata{login_location = IDP}}) ->
{ok, Req2} = esaml_cowboy:reply_with_authnreq(SP, IDP, <<"foo">>, Req),
{ok, Req2, S};
Handles HTTP - POST bound assertions coming back from the IDP .
handle(<<"POST">>, <<"consume">>, Req, S = #state{sp = SP}) ->
case esaml_cowboy:validate_assertion(SP, fun esaml_util:check_dupe_ets/2, Req) of
{ok, Assertion, RelayState, Req2} ->
Attrs = Assertion#esaml_assertion.attributes,
Uid = proplists:get_value(uid, Attrs),
Output = io_lib:format("<html><head><title>SAML SP demo</title></head><body><h1>Hi there!</h1><p>This is the <code>esaml_sp_default</code> demo SP callback module from eSAML.</p><table><tr><td>Your name:</td><td>\n~p\n</td></tr><tr><td>Your UID:</td><td>\n~p\n</td></tr></table><hr /><p>RelayState:</p><pre>\n~p\n</pre><p>The assertion I got was:</p><pre>\n~p\n</pre></body></html>", [Assertion#esaml_assertion.subject#esaml_subject.name, Uid, RelayState, Assertion]),
{ok, Req3} = cowboy_req:reply(200, [{<<"Content-Type">>, <<"text/html">>}], Output, Req2),
{ok, Req3, S};
{error, Reason, Req2} ->
{ok, Req3} = cowboy_req:reply(403, [{<<"content-type">>, <<"text/plain">>}],
["Access denied, assertion failed validation:\n", io_lib:format("~p\n", [Reason])],
Req2),
{ok, Req3, S}
end;
handle(_, _, Req, S = #state{}) ->
{ok, Req2} = cowboy_req:reply(404, [], <<"Not found">>, Req),
{ok, Req2, S}.
terminate(_Reason, _Req, _State) -> ok.
| null | https://raw.githubusercontent.com/arekinath/esaml/bf52dcb449184dc94e4fb1ff8820b08cc1ceab09/examples/sp/src/sp_handler.erl | erlang |
All rights reserved.
the LICENSE file in the root of the distribution.
We build all of our URLs (in metadata, and in requests) based on this | esaml - SAML for erlang
Copyright ( c ) 2013 , and the University of Queensland
Distributed subject to the terms of the 2 - clause BSD license , see
-module(sp_handler).
-include_lib("esaml/include/esaml.hrl").
-record(state, {sp, idp}).
-export([init/3, handle/2, terminate/3]).
init(_Transport, Req, _Args) ->
Load the certificate and private key for the SP
PrivKey = esaml_util:load_private_key("test.key"),
Cert = esaml_util:load_certificate("test.crt"),
Base = "",
Certificate fingerprints to accept from our IDP
FPs = ["6b:d1:24:4b:38:cf:6c:1f:4e:53:56:c5:c8:90:63:68:55:5e:27:28"],
SP = esaml_sp:setup(#esaml_sp{
key = PrivKey,
certificate = Cert,
trusted_fingerprints = FPs,
consume_uri = Base ++ "/consume",
metadata_uri = Base ++ "/metadata",
org = #esaml_org{
name = "Foo Bar",
displayname = "Foo Bar",
url = ""
},
tech = #esaml_contact{
name = "Foo Bar",
email = ""
}
}),
Rather than copying the IDP 's metadata into our code , we 'll just fetch it
( this call will cache after the first time around , so it will be fast )
IdpMeta = esaml_util:load_metadata(""),
{ok, Req, #state{sp = SP, idp = IdpMeta}}.
handle(Req, S = #state{}) ->
{Operation, Req2} = cowboy_req:binding(operation, Req),
{Method, Req3} = cowboy_req:method(Req2),
handle(Method, Operation, Req3, S).
Return our SP metadata as signed XML
handle(<<"GET">>, <<"metadata">>, Req, S = #state{sp = SP}) ->
{ok, Req2} = esaml_cowboy:reply_with_metadata(SP, Req),
{ok, Req2, S};
Visit /saml / auth to start the authentication process -- we will make an AuthnRequest
and send it to our IDP
handle(<<"GET">>, <<"auth">>, Req, S = #state{sp = SP,
idp = #esaml_idp_metadata{login_location = IDP}}) ->
{ok, Req2} = esaml_cowboy:reply_with_authnreq(SP, IDP, <<"foo">>, Req),
{ok, Req2, S};
Handles HTTP - POST bound assertions coming back from the IDP .
handle(<<"POST">>, <<"consume">>, Req, S = #state{sp = SP}) ->
case esaml_cowboy:validate_assertion(SP, fun esaml_util:check_dupe_ets/2, Req) of
{ok, Assertion, RelayState, Req2} ->
Attrs = Assertion#esaml_assertion.attributes,
Uid = proplists:get_value(uid, Attrs),
Output = io_lib:format("<html><head><title>SAML SP demo</title></head><body><h1>Hi there!</h1><p>This is the <code>esaml_sp_default</code> demo SP callback module from eSAML.</p><table><tr><td>Your name:</td><td>\n~p\n</td></tr><tr><td>Your UID:</td><td>\n~p\n</td></tr></table><hr /><p>RelayState:</p><pre>\n~p\n</pre><p>The assertion I got was:</p><pre>\n~p\n</pre></body></html>", [Assertion#esaml_assertion.subject#esaml_subject.name, Uid, RelayState, Assertion]),
{ok, Req3} = cowboy_req:reply(200, [{<<"Content-Type">>, <<"text/html">>}], Output, Req2),
{ok, Req3, S};
{error, Reason, Req2} ->
{ok, Req3} = cowboy_req:reply(403, [{<<"content-type">>, <<"text/plain">>}],
["Access denied, assertion failed validation:\n", io_lib:format("~p\n", [Reason])],
Req2),
{ok, Req3, S}
end;
handle(_, _, Req, S = #state{}) ->
{ok, Req2} = cowboy_req:reply(404, [], <<"Not found">>, Req),
{ok, Req2, S}.
terminate(_Reason, _Req, _State) -> ok.
|
07ead5bf9524bf5088e6ff89536dbc841d5038e58f45639c81882a92c55b1898 | venantius/photon | core.cljs | (ns photon.core
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)])
(:require
;; <other stuff>
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[photon.config :as config]
[photon.messages :as messages]
[taoensso.encore :as encore :refer-macros (have have?)]
[taoensso.sente :as sente :refer (cb-success?)] ; <--- Add this
))
(enable-console-print!)
;;; Add this: --->
(let [{:keys [chsk ch-recv send-fn state]}
(sente/make-channel-socket! config/photon-endpoint ; Note the same path as before
e / o # { : auto : : ws }
})]
(def chsk chsk)
ChannelSocket 's receive channel
ChannelSocket 's send API fn
, read - only atom
)
(.log js/console "Photon JS loaded!")
(defonce router (atom nil))
(defn stop-router!
[]
(when-let [stop-f @router]
(stop-f)))
;; Subscribe to a change feed on the server.
(defn subscribe
"Subscribe to a changefeed on the Photon server."
[changefeed-name local-atom]
(chsk-send! [messages/subscribe {:name :feed}]
8000
)
)
(defmulti recv-event-handler
"Multimethod to handle the `?data` from `:chsk/recv` messages."
first
)
(defmethod recv-event-handler
:default
[data]
(println "Called!")
(println data))
(defmethod recv-event-handler
:photon.server.db/change
[data]
(println "DB CHANGE!!"))
(defmulti -event-msg-handler
"Multimethod to handle Sente `event-msg`s"
:id ; Dispatch on event-id
)
(defn event-msg-handler
"Wraps `-event-msg-handler` with logging, error catching, etc."
[{:as ev-msg :keys [id ?data event]}]
(-event-msg-handler ev-msg))
(defmethod -event-msg-handler
:default ; Default/fallback case (no other matching handler)
[{:as ev-msg :keys [event]}]
(println "Unhandled event: %s" event))
(defmethod -event-msg-handler :chsk/state
[{:as ev-msg :keys [?data]}]
(let [[old-state-map new-state-map] (have vector? ?data)]
(if (:first-open? new-state-map)
(println "Channel socket successfully established!: %s" new-state-map)
(println "Channel socket state change: %s" new-state-map))))
(defmethod -event-msg-handler :chsk/recv
[{:as ev-msg :keys [?data]}]
(recv-event-handler ?data)
(println "Push event from server: " ?data))
(defmethod -event-msg-handler :chsk/handshake
[{:as ev-msg :keys [?data]}]
(let [[?uid ?csrf-token ?handshake-data] ?data]
(println "Handshake: " ?data)))
(defn start-router! []
(stop-router!)
(reset! router
(sente/start-client-chsk-router!
ch-chsk event-msg-handler)))
Init stuff
(defn start! [] (start-router!))
(defonce _start-once (start!))
| null | https://raw.githubusercontent.com/venantius/photon/95097d155526abb719948b5aa5a7fd12de9615a6/src/photon/core.cljs | clojure | <other stuff>
<--- Add this
Add this: --->
Note the same path as before
Subscribe to a change feed on the server.
Dispatch on event-id
Default/fallback case (no other matching handler) | (ns photon.core
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)])
(:require
[clojure.string :as str]
[cljs.core.async :as async :refer (<! >! put! chan)]
[photon.config :as config]
[photon.messages :as messages]
[taoensso.encore :as encore :refer-macros (have have?)]
))
(enable-console-print!)
(let [{:keys [chsk ch-recv send-fn state]}
e / o # { : auto : : ws }
})]
(def chsk chsk)
ChannelSocket 's receive channel
ChannelSocket 's send API fn
, read - only atom
)
(.log js/console "Photon JS loaded!")
(defonce router (atom nil))
(defn stop-router!
[]
(when-let [stop-f @router]
(stop-f)))
(defn subscribe
"Subscribe to a changefeed on the Photon server."
[changefeed-name local-atom]
(chsk-send! [messages/subscribe {:name :feed}]
8000
)
)
(defmulti recv-event-handler
"Multimethod to handle the `?data` from `:chsk/recv` messages."
first
)
(defmethod recv-event-handler
:default
[data]
(println "Called!")
(println data))
(defmethod recv-event-handler
:photon.server.db/change
[data]
(println "DB CHANGE!!"))
(defmulti -event-msg-handler
"Multimethod to handle Sente `event-msg`s"
)
(defn event-msg-handler
"Wraps `-event-msg-handler` with logging, error catching, etc."
[{:as ev-msg :keys [id ?data event]}]
(-event-msg-handler ev-msg))
(defmethod -event-msg-handler
[{:as ev-msg :keys [event]}]
(println "Unhandled event: %s" event))
(defmethod -event-msg-handler :chsk/state
[{:as ev-msg :keys [?data]}]
(let [[old-state-map new-state-map] (have vector? ?data)]
(if (:first-open? new-state-map)
(println "Channel socket successfully established!: %s" new-state-map)
(println "Channel socket state change: %s" new-state-map))))
(defmethod -event-msg-handler :chsk/recv
[{:as ev-msg :keys [?data]}]
(recv-event-handler ?data)
(println "Push event from server: " ?data))
(defmethod -event-msg-handler :chsk/handshake
[{:as ev-msg :keys [?data]}]
(let [[?uid ?csrf-token ?handshake-data] ?data]
(println "Handshake: " ?data)))
(defn start-router! []
(stop-router!)
(reset! router
(sente/start-client-chsk-router!
ch-chsk event-msg-handler)))
Init stuff
(defn start! [] (start-router!))
(defonce _start-once (start!))
|
a7f77fc96c29fb311b5a3c68af8cebd6b8e81aba2fddd6be5096b5b34c764ac0 | NetComposer/nkpacket | nkpacket_transport_tcp.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2019 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
@private TCP / TLS Transport .
This module is used for both inbound and outbound TCP and TLS connections .
-module(nkpacket_transport_tcp).
-author('Carlos Gonzalez <>').
-behaviour(ranch_protocol).
-export([get_listener/1, connect/1, start_link/1]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-export([start_link/4]).
-include("nkpacket.hrl").
%% To get debug info, start with debug=>true
-define(DEBUG(Txt, Args),
case get(nkpacket_debug) of
true -> ?LLOG(debug, Txt, Args);
_ -> ok
end).
-define(LLOG(Type, Txt, Args), lager:Type("NkPACKET TCP "++Txt, Args)).
%% ===================================================================
%% Private
%% ===================================================================
%% @private Starts a new listening server
-spec get_listener(nkpacket:nkport()) ->
supervisor:child_spec().
get_listener(#nkport{id=Id, listen_ip=Ip, listen_port=Port, transp=Transp}=NkPort)
when Transp==tcp; Transp==tls ->
Str = nkpacket_util:conn_string(Transp, Ip, Port),
#{
id => {Id, Str},
start => {?MODULE, start_link, [NkPort]},
restart => transient,
shutdown => 5000,
type => worker,
modules => [?MODULE]
}.
%% @private Starts a new connection to a remote server
-spec connect(nkpacket:nkport()) ->
{ok, nkpacket:nkport()} | {error, term()}.
connect(NkPort) ->
#nkport{opts=Meta} = NkPort,
Debug = maps:get(debug, Meta, false),
put(nkpacket_debug, Debug),
case connect_outbound(NkPort) of
{ok, InetMod, Socket} ->
{ok, {LocalIp, LocalPort}} = InetMod:sockname(Socket),
NkPort2 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
socket = Socket
},
InetMod:setopts(Socket, [{active, once}]),
{ok, NkPort2};
{error, Error} ->
{error, Error}
end.
%% ===================================================================
%% gen_server
%% ===================================================================
@private
start_link(NkPort) ->
gen_server:start_link(?MODULE, [NkPort], []).
-record(state, {
nkport :: nkpacket:nkport(),
ranch_id :: term(),
ranch_pid :: pid(),
protocol :: nkpacket:protocol(),
proto_state :: term(),
monitor_ref :: reference()
}).
@private
-spec init(term()) ->
{ok, #state{}} | {stop, term()}.
init([NkPort]) ->
#nkport{
class = Class,
protocol = Protocol,
transp = Transp,
listen_ip = ListenIp,
listen_port = ListenPort,
opts = Meta
} = NkPort,
process_flag(trap_exit, true), %% Allow calls to terminate
Debug = maps:get(debug, Meta, false),
put(nkpacket_debug, Debug),
ListenOpts = listen_opts(NkPort),
case nkpacket_transport:open_port(NkPort, ListenOpts) of
{ok, Socket} ->
{InetMod, _, RanchMod} = get_modules(Transp),
{ok, {LocalIp, LocalPort}} = InetMod:sockname(Socket),
NkPort1 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
listen_ip = ListenIp,
listen_port = LocalPort,
pid = self(),
socket = Socket
},
RanchId = {Transp, ListenIp, LocalPort},
RanchPort = NkPort1#nkport{opts=maps:with(?CONN_LISTEN_OPTS, Meta)},
Listeners = maps:get(tcp_listeners, Meta, 100),
?DEBUG("active listeners: ~p", [Listeners]),
{ok, RanchPid} = ranch_listener_sup:start_link(
RanchId,
RanchMod,
#{
socket => Socket,
max_connections => maps:get(tcp_max_connections, Meta, 1024)
},
?MODULE,
[RanchPort]),
% We take the 'real' port (in case it is '0')
nkpacket_util:register_listener(NkPort),
ConnMetaOpts = [
tcp_packet, send_timeout, send_timeout_close,
tls_certfile, tls_keyfile, tls_cacertfile
| ?CONN_LISTEN_OPTS
],
% ConnMetaOpts = [tcp_packet, tls_opts | ?CONN_LISTEN_OPTS],
ConnMeta = maps:with(ConnMetaOpts, Meta),
ConnPort = NkPort1#nkport{opts=ConnMeta},
ListenType = case size(ListenIp) of
4 -> nkpacket_listen4;
8 -> nkpacket_listen6
end,
nklib_proc:put({ListenType, Class, Protocol, Transp}, ConnPort),
{ok, ProtoState} = nkpacket_util:init_protocol(Protocol, listen_init, NkPort1),
MonRef = case Meta of
#{monitor:=UserRef} -> erlang:monitor(process, UserRef);
_ -> undefined
end,
State = #state{
nkport = ConnPort,
ranch_id = RanchId,
ranch_pid = RanchPid,
protocol = Protocol,
proto_state = ProtoState,
monitor_ref = MonRef
},
{ok, State};
{error, Error} ->
?LLOG(error, "could not start ~p transport on ~p:~p (~p)",
[Transp, ListenIp, ListenPort, Error]),
{stop, Error}
end.
@private
-spec handle_call(term(), {pid(), term()}, #state{}) ->
{reply, term(), #state{}} | {noreply, #state{}} |
{stop, term(), #state{}} | {stop, term(), term(), #state{}}.
handle_call({nkpacket_apply_nkport, Fun}, _From, #state{nkport=NkPort}=State) ->
{reply, Fun(NkPort), State};
handle_call(nkpacket_stop, _From, State) ->
{stop, normal, ok, State};
handle_call(Msg, From, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_call, [Msg, From, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec handle_cast(term(), #state{}) ->
{noreply, #state{}} | {stop, term(), #state{}}.
handle_cast(nkpacket_stop, State) ->
{stop, normal, State};
handle_cast(Msg, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_cast, [Msg, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec handle_info(term(), #state{}) ->
{noreply, #state{}} | {stop, term(), #state{}}.
handle_info({'DOWN', MRef, process, _Pid, _Reason}, #state{monitor_ref=MRef}=State) ->
{stop, normal, State};
handle_info({'EXIT', Pid, Reason}, #state{ranch_pid=Pid}=State) ->
{stop, {ranch_stop, Reason}, State};
handle_info(Msg, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_info, [Msg, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec code_change(term(), #state{}, term()) ->
{ok, #state{}}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
@private
-spec terminate(term(), #state{}) ->
ok.
terminate(Reason, State) ->
#state{
ranch_id = RanchId,
ranch_pid = RanchPid,
nkport = #nkport{transp=Transp, socket=Socket} = NkPort
} = State,
?DEBUG("listener stop: ~p", [Reason]),
catch call_protocol(listen_stop, [Reason, NkPort], State),
exit(RanchPid, shutdown),
timer:sleep(100), %% Give time to ranch to close acceptors
catch ranch_server:cleanup_listener_opts(RanchId),
{_, TranspMod, _} = get_modules(Transp),
TranspMod:close(Socket),
ok.
%% ===================================================================
%% Ranch Callbacks
%% ===================================================================
@private Ranch 's callback , called for every new inbound connection
%% to create a new process to manage it
-spec start_link(term(), term(), atom(), term()) ->
{ok, pid()}.
start_link(Ref, Socket, TranspModule, [#nkport{opts=Meta} = NkPort]) ->
{ok, {LocalIp, LocalPort}} = TranspModule:sockname(Socket),
{ok, {RemoteIp, RemotePort}} = TranspModule:peername(Socket),
NkPort1 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
remote_ip = RemoteIp,
remote_port = RemotePort,
socket = Socket
},
case TranspModule of
ranch_ssl ->
ok;
ranch_tcp ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Meta)),
Opts2 = [{keepalive, true}, {active, once} | Opts1],
Opts3 = case Meta of
#{tcp_packet:=Packet} ->
[{packet, Packet}|Opts2];
_ ->
Opts2
end,
TranspModule:setopts(Socket, Opts3)
end,
nkpacket_connection:ranch_start_link(NkPort1, Ref).
%% ===================================================================
Internal
%% ===================================================================
@private Gets socket options for outbound connections
-spec connect_outbound(#nkport{}) ->
{ok, inet|ssl, inet:socket()} | {error, term()}.
connect_outbound(#nkport{remote_ip=Ip, remote_port=Port, opts=Opts, transp=tcp}=NkPort) ->
SocketOpts = outbound_opts(NkPort),
ConnTimeout = case maps:get(connect_timeout, Opts, undefined) of
undefined ->
nkpacket_config:connect_timeout();
Timeout0 ->
Timeout0
end,
?DEBUG("connect to: tcp:~p:~p (~p)", [ Ip, Port, SocketOpts]),
case gen_tcp:connect(Ip, Port, SocketOpts, ConnTimeout) of
{ok, Socket} ->
{ok, inet, Socket};
{error, Error} ->
{error, Error}
end;
connect_outbound(#nkport{remote_ip=Ip, remote_port=Port, opts=Opts, transp=tls}=NkPort) ->
SocketOpts = outbound_opts(NkPort) ++ nkpacket_tls:make_outbound_opts(Opts),
ConnTimeout = case maps:get(connect_timeout, Opts, undefined) of
undefined ->
nkpacket_config:connect_timeout();
Timeout0 ->
Timeout0
end,
Host = case Opts of
#{tls_verify:=host, host:=Host0} ->
binary_to_list(Host0);
_ ->
Ip
end,
?DEBUG("connect to: tls:~p:~p (~p)", [Host, Port, SocketOpts]),
case ssl:connect(Host, Port, SocketOpts, ConnTimeout) of
{ok, Socket} ->
{ok, ssl, Socket};
{error, Error} ->
{error, Error}
end.
@private Gets socket options for outbound connections
-spec outbound_opts(#nkport{}) ->
list().
outbound_opts(#nkport{opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
binary,
{active, false},
{nodelay, true},
{keepalive, true},
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end}
| Opts1
].
@private Gets socket options for listening connections
-spec listen_opts(#nkport{}) ->
list().
listen_opts(#nkport{transp=tcp, listen_ip=Ip, opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end},
binary,
{ip, Ip},
{active, false},
{nodelay, true},
{keepalive, true},
{reuseaddr, true},
{backlog, 1024}
| Opts1
];
listen_opts(#nkport{transp=tls, listen_ip=Ip, opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
% From Cowboy 2.0:
%{next_protocols_advertised, [<<"h2">>, <<"http/1.1">>]},
%{alpn_preferred_protocols, [<<"h2">>, <<"http/1.1">>]},
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end},
{ip, Ip}, {active, once}, binary,
{nodelay, true}, {keepalive, true},
{reuseaddr, true}, {backlog, 1024}
| Opts1
]
++nkpacket_tls:make_inbound_opts(Opts).
@private
call_protocol(Fun, Args, State) ->
nkpacket_util:call_protocol(Fun, Args, State, #state.protocol).
@private
get_modules(tcp) -> {inet, gen_tcp, ranch_tcp};
get_modules(tls) -> {ssl, ssl, ranch_ssl}.
| null | https://raw.githubusercontent.com/NetComposer/nkpacket/4d74ab31b20ba7a1449f1f72c1c51829f18d2d5c/src/nkpacket_transport_tcp.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
To get debug info, start with debug=>true
===================================================================
Private
===================================================================
@private Starts a new listening server
@private Starts a new connection to a remote server
===================================================================
gen_server
===================================================================
Allow calls to terminate
We take the 'real' port (in case it is '0')
ConnMetaOpts = [tcp_packet, tls_opts | ?CONN_LISTEN_OPTS],
Give time to ranch to close acceptors
===================================================================
Ranch Callbacks
===================================================================
to create a new process to manage it
===================================================================
===================================================================
From Cowboy 2.0:
{next_protocols_advertised, [<<"h2">>, <<"http/1.1">>]},
{alpn_preferred_protocols, [<<"h2">>, <<"http/1.1">>]}, | Copyright ( c ) 2019 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@private TCP / TLS Transport .
This module is used for both inbound and outbound TCP and TLS connections .
-module(nkpacket_transport_tcp).
-author('Carlos Gonzalez <>').
-behaviour(ranch_protocol).
-export([get_listener/1, connect/1, start_link/1]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-export([start_link/4]).
-include("nkpacket.hrl").
-define(DEBUG(Txt, Args),
case get(nkpacket_debug) of
true -> ?LLOG(debug, Txt, Args);
_ -> ok
end).
-define(LLOG(Type, Txt, Args), lager:Type("NkPACKET TCP "++Txt, Args)).
-spec get_listener(nkpacket:nkport()) ->
supervisor:child_spec().
get_listener(#nkport{id=Id, listen_ip=Ip, listen_port=Port, transp=Transp}=NkPort)
when Transp==tcp; Transp==tls ->
Str = nkpacket_util:conn_string(Transp, Ip, Port),
#{
id => {Id, Str},
start => {?MODULE, start_link, [NkPort]},
restart => transient,
shutdown => 5000,
type => worker,
modules => [?MODULE]
}.
-spec connect(nkpacket:nkport()) ->
{ok, nkpacket:nkport()} | {error, term()}.
connect(NkPort) ->
#nkport{opts=Meta} = NkPort,
Debug = maps:get(debug, Meta, false),
put(nkpacket_debug, Debug),
case connect_outbound(NkPort) of
{ok, InetMod, Socket} ->
{ok, {LocalIp, LocalPort}} = InetMod:sockname(Socket),
NkPort2 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
socket = Socket
},
InetMod:setopts(Socket, [{active, once}]),
{ok, NkPort2};
{error, Error} ->
{error, Error}
end.
@private
start_link(NkPort) ->
gen_server:start_link(?MODULE, [NkPort], []).
-record(state, {
nkport :: nkpacket:nkport(),
ranch_id :: term(),
ranch_pid :: pid(),
protocol :: nkpacket:protocol(),
proto_state :: term(),
monitor_ref :: reference()
}).
@private
-spec init(term()) ->
{ok, #state{}} | {stop, term()}.
init([NkPort]) ->
#nkport{
class = Class,
protocol = Protocol,
transp = Transp,
listen_ip = ListenIp,
listen_port = ListenPort,
opts = Meta
} = NkPort,
Debug = maps:get(debug, Meta, false),
put(nkpacket_debug, Debug),
ListenOpts = listen_opts(NkPort),
case nkpacket_transport:open_port(NkPort, ListenOpts) of
{ok, Socket} ->
{InetMod, _, RanchMod} = get_modules(Transp),
{ok, {LocalIp, LocalPort}} = InetMod:sockname(Socket),
NkPort1 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
listen_ip = ListenIp,
listen_port = LocalPort,
pid = self(),
socket = Socket
},
RanchId = {Transp, ListenIp, LocalPort},
RanchPort = NkPort1#nkport{opts=maps:with(?CONN_LISTEN_OPTS, Meta)},
Listeners = maps:get(tcp_listeners, Meta, 100),
?DEBUG("active listeners: ~p", [Listeners]),
{ok, RanchPid} = ranch_listener_sup:start_link(
RanchId,
RanchMod,
#{
socket => Socket,
max_connections => maps:get(tcp_max_connections, Meta, 1024)
},
?MODULE,
[RanchPort]),
nkpacket_util:register_listener(NkPort),
ConnMetaOpts = [
tcp_packet, send_timeout, send_timeout_close,
tls_certfile, tls_keyfile, tls_cacertfile
| ?CONN_LISTEN_OPTS
],
ConnMeta = maps:with(ConnMetaOpts, Meta),
ConnPort = NkPort1#nkport{opts=ConnMeta},
ListenType = case size(ListenIp) of
4 -> nkpacket_listen4;
8 -> nkpacket_listen6
end,
nklib_proc:put({ListenType, Class, Protocol, Transp}, ConnPort),
{ok, ProtoState} = nkpacket_util:init_protocol(Protocol, listen_init, NkPort1),
MonRef = case Meta of
#{monitor:=UserRef} -> erlang:monitor(process, UserRef);
_ -> undefined
end,
State = #state{
nkport = ConnPort,
ranch_id = RanchId,
ranch_pid = RanchPid,
protocol = Protocol,
proto_state = ProtoState,
monitor_ref = MonRef
},
{ok, State};
{error, Error} ->
?LLOG(error, "could not start ~p transport on ~p:~p (~p)",
[Transp, ListenIp, ListenPort, Error]),
{stop, Error}
end.
@private
-spec handle_call(term(), {pid(), term()}, #state{}) ->
{reply, term(), #state{}} | {noreply, #state{}} |
{stop, term(), #state{}} | {stop, term(), term(), #state{}}.
handle_call({nkpacket_apply_nkport, Fun}, _From, #state{nkport=NkPort}=State) ->
{reply, Fun(NkPort), State};
handle_call(nkpacket_stop, _From, State) ->
{stop, normal, ok, State};
handle_call(Msg, From, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_call, [Msg, From, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec handle_cast(term(), #state{}) ->
{noreply, #state{}} | {stop, term(), #state{}}.
handle_cast(nkpacket_stop, State) ->
{stop, normal, State};
handle_cast(Msg, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_cast, [Msg, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec handle_info(term(), #state{}) ->
{noreply, #state{}} | {stop, term(), #state{}}.
handle_info({'DOWN', MRef, process, _Pid, _Reason}, #state{monitor_ref=MRef}=State) ->
{stop, normal, State};
handle_info({'EXIT', Pid, Reason}, #state{ranch_pid=Pid}=State) ->
{stop, {ranch_stop, Reason}, State};
handle_info(Msg, #state{nkport=NkPort}=State) ->
case call_protocol(listen_handle_info, [Msg, NkPort], State) of
undefined -> {noreply, State};
{ok, State1} -> {noreply, State1};
{stop, Reason, State1} -> {stop, Reason, State1}
end.
@private
-spec code_change(term(), #state{}, term()) ->
{ok, #state{}}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
@private
-spec terminate(term(), #state{}) ->
ok.
terminate(Reason, State) ->
#state{
ranch_id = RanchId,
ranch_pid = RanchPid,
nkport = #nkport{transp=Transp, socket=Socket} = NkPort
} = State,
?DEBUG("listener stop: ~p", [Reason]),
catch call_protocol(listen_stop, [Reason, NkPort], State),
exit(RanchPid, shutdown),
catch ranch_server:cleanup_listener_opts(RanchId),
{_, TranspMod, _} = get_modules(Transp),
TranspMod:close(Socket),
ok.
@private Ranch 's callback , called for every new inbound connection
-spec start_link(term(), term(), atom(), term()) ->
{ok, pid()}.
start_link(Ref, Socket, TranspModule, [#nkport{opts=Meta} = NkPort]) ->
{ok, {LocalIp, LocalPort}} = TranspModule:sockname(Socket),
{ok, {RemoteIp, RemotePort}} = TranspModule:peername(Socket),
NkPort1 = NkPort#nkport{
local_ip = LocalIp,
local_port = LocalPort,
remote_ip = RemoteIp,
remote_port = RemotePort,
socket = Socket
},
case TranspModule of
ranch_ssl ->
ok;
ranch_tcp ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Meta)),
Opts2 = [{keepalive, true}, {active, once} | Opts1],
Opts3 = case Meta of
#{tcp_packet:=Packet} ->
[{packet, Packet}|Opts2];
_ ->
Opts2
end,
TranspModule:setopts(Socket, Opts3)
end,
nkpacket_connection:ranch_start_link(NkPort1, Ref).
Internal
@private Gets socket options for outbound connections
-spec connect_outbound(#nkport{}) ->
{ok, inet|ssl, inet:socket()} | {error, term()}.
connect_outbound(#nkport{remote_ip=Ip, remote_port=Port, opts=Opts, transp=tcp}=NkPort) ->
SocketOpts = outbound_opts(NkPort),
ConnTimeout = case maps:get(connect_timeout, Opts, undefined) of
undefined ->
nkpacket_config:connect_timeout();
Timeout0 ->
Timeout0
end,
?DEBUG("connect to: tcp:~p:~p (~p)", [ Ip, Port, SocketOpts]),
case gen_tcp:connect(Ip, Port, SocketOpts, ConnTimeout) of
{ok, Socket} ->
{ok, inet, Socket};
{error, Error} ->
{error, Error}
end;
connect_outbound(#nkport{remote_ip=Ip, remote_port=Port, opts=Opts, transp=tls}=NkPort) ->
SocketOpts = outbound_opts(NkPort) ++ nkpacket_tls:make_outbound_opts(Opts),
ConnTimeout = case maps:get(connect_timeout, Opts, undefined) of
undefined ->
nkpacket_config:connect_timeout();
Timeout0 ->
Timeout0
end,
Host = case Opts of
#{tls_verify:=host, host:=Host0} ->
binary_to_list(Host0);
_ ->
Ip
end,
?DEBUG("connect to: tls:~p:~p (~p)", [Host, Port, SocketOpts]),
case ssl:connect(Host, Port, SocketOpts, ConnTimeout) of
{ok, Socket} ->
{ok, ssl, Socket};
{error, Error} ->
{error, Error}
end.
@private Gets socket options for outbound connections
-spec outbound_opts(#nkport{}) ->
list().
outbound_opts(#nkport{opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
binary,
{active, false},
{nodelay, true},
{keepalive, true},
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end}
| Opts1
].
@private Gets socket options for listening connections
-spec listen_opts(#nkport{}) ->
list().
listen_opts(#nkport{transp=tcp, listen_ip=Ip, opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end},
binary,
{ip, Ip},
{active, false},
{nodelay, true},
{keepalive, true},
{reuseaddr, true},
{backlog, 1024}
| Opts1
];
listen_opts(#nkport{transp=tls, listen_ip=Ip, opts=Opts}) ->
Opts1 = maps:to_list(maps:with([send_timeout, send_timeout_close], Opts)),
[
{packet, case Opts of #{tcp_packet:=Packet} -> Packet; _ -> raw end},
{ip, Ip}, {active, once}, binary,
{nodelay, true}, {keepalive, true},
{reuseaddr, true}, {backlog, 1024}
| Opts1
]
++nkpacket_tls:make_inbound_opts(Opts).
@private
call_protocol(Fun, Args, State) ->
nkpacket_util:call_protocol(Fun, Args, State, #state.protocol).
@private
get_modules(tcp) -> {inet, gen_tcp, ranch_tcp};
get_modules(tls) -> {ssl, ssl, ranch_ssl}.
|
0e7148c15237669d48c61b0e19f97bb28b4138a4fdd4b77eba155e6438209e6c | ucsd-progsys/dsolve | tests_rec_heap.ml | type 'a t =
| Empty
| Same of 'a * 'a t * 'a t (* same number of elements on both sides *)
| Diff of 'a * 'a t * 'a t (* left has [n+1] nodes and right has [n] *)
let rec set_of t = match t with
Empty - > Myaset.empty
| Same ( x , l , r ) - > Myaset.cup ( x ) ( Myaset.cup ( set_of l ) ( set_of r ) )
| Diff ( x , l , r ) - > Myaset.cup ( x ) ( Myaset.cup ( set_of l ) ( set_of r ) )
let rec sz t = match t with
Empty - > 0
| Same ( _ , l , r ) - > 1 + sz l + sz r
| Diff ( _ , l , r ) - > 1 + sz l + sz r
let h = match h with
Empty - > assert false
| Same ( x , _ , _ ) - > x
| Diff ( x , _ , _ ) - > x
Empty -> Myaset.empty
| Same (x, l, r) -> Myaset.cup (Myaset.sng x) (Myaset.cup (set_of l) (set_of r))
| Diff (x, l, r) -> Myaset.cup (Myaset.sng x) (Myaset.cup (set_of l) (set_of r))
let rec sz t = match t with
Empty -> 0
| Same (_, l, r) -> 1 + sz l + sz r
| Diff (_, l, r) -> 1 + sz l + sz r
let max h = match h with
Empty -> assert false
| Same (x, _, _) -> x
| Diff (x, _, _) -> x*)
let empty = Empty
let rec add x h = match h with
| Empty ->
Same (x, Empty, Empty)
| Same (y, l, r) ->
if x > y then Diff (x, add y l, r) else Diff (y, add x l, r)
| Diff (y, l, r) ->
if x > y then Same (x, l, add y r) else Same (y, l, add x r)
let maximum h = match h with
| Empty -> let _ = assert (1 = 0) in assert false (* raise EmptyHeap *)
| Same (x, l, r) -> (x, Same (x, l, r)) | Diff (x, l, r) -> (x, Diff (x, l, r))
let rec extract_last h = match h with
| Empty -> let _ = assert (1 = 0) in assert false (* raise EmptyHeap *)
| Same (x, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (x, Empty)
| Same (_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff (_, _, _) -> let _ = assert (1 = 0) in assert false)
| Same (_, _, _) ->
let y,r' = extract_last r in y, Diff (x, l, r')
| Diff (_, _, _) ->
let y,r' = extract_last r in y, Diff (x, l, r'))
| Diff (x, l, r) -> let y,l' = extract_last l in y, Same (x, l', r)
(* * *)let ck_assume_empty h = match h with | Empty -> h | Same(_, _, _) -> let _ = assert (1=0) in assert false | Diff(_, _, _) -> let _ = assert (1 = 0) in assert false
let rec descent x h = match h with
| Empty ->
let _ = assert (1 = 0) in assert false
| Diff (y, l, r) ->
(match r with
| Empty ->
(match l with
| Same (z, ll', lr') ->
let ll = ck_assume_empty ll' in let _ = assert (ll = ll') in (* * *)
let lr = ck_assume_empty lr' in let _ = assert (lr = lr') in (* * *)
if x > z then (y, Diff (x, Same (z, ll, lr), Empty))
else (y, Diff (z, Same (x, Empty, Empty), Empty))
| Diff (_, _, _) -> let _ = assert (1=0) in assert false
| Empty -> let _ = assert (1=0) in assert false)
| Diff (_, _, _) -> (* same code (and proof) for Same and Diff. the only purpose of matching a pattern is to assert !Empty *)
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Diff (x, l, r))
else if ml > mr then
let (z, l') = descent x l in
(y, Diff (ml, l', r))
else
let (z, r') = descent x r in
(y, Diff (mr, l, r'))
| Same (_, _, _) ->
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Diff (x, l, r))
else if ml > mr then
let (z, l') = descent x l in
(y, Diff (ml, l', r))
else
let (z, r') = descent x r in
(y, Diff (mr, l, r')))
| Same (y, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (y, Same(x, Empty, Empty))
| Same(_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff(_, _, _) -> let _ = assert (1 = 0) in assert false)
| Diff (_, _, _) -> (* same symmetry as above *)
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Same (x, l, r))
else if ml > mr then
let (z, l) = descent x l in
(y, Same(ml, l, r))
else
let (z, r) = descent x r in
(y, Same (mr, l, r))
| Same (_, _, _) ->
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Same (x, l, r))
else if ml > mr then
let (z, l) = descent x l in
(y, Same(ml, l, r))
else
let (z, r) = descent x r in
(y, Same (mr, l, r)))
let remove h = match h with
| Empty -> let _ = assert (1 = 0) in assert false (* raise EmptyHeap *)
| Same (x, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (x, Empty)
| Same (_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff (_, _, _) -> let _ = assert (1 = 0) in assert false)
| Diff (_, _, _) -> let y,h' = extract_last h in descent y h'
| Same (_, _, _) -> let y,h' = extract_last h in descent y h')
| Diff (x, l, r) -> let y,h' = extract_last h in let _ = (fun x -> x) h' in descent y h'
let rec iter f = function
| Empty -> ()
| Same (x, l, r) -> iter f l; f x; iter f r
| Diff (x, l, r) -> iter f l; f x; iter f r
let rec fold f h x0 = match h with
| Empty -> x0
| Same (x, l, r) -> fold f l (fold f r (f x x0))
| Diff (x, l, r) -> fold f l (fold f r (f x x0))
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/proceedings-demos/ml/old/tests_rec_heap.ml | ocaml | same number of elements on both sides
left has [n+1] nodes and right has [n]
raise EmptyHeap
raise EmptyHeap
*
*
*
same code (and proof) for Same and Diff. the only purpose of matching a pattern is to assert !Empty
same symmetry as above
raise EmptyHeap | type 'a t =
| Empty
let rec set_of t = match t with
Empty - > Myaset.empty
| Same ( x , l , r ) - > Myaset.cup ( x ) ( Myaset.cup ( set_of l ) ( set_of r ) )
| Diff ( x , l , r ) - > Myaset.cup ( x ) ( Myaset.cup ( set_of l ) ( set_of r ) )
let rec sz t = match t with
Empty - > 0
| Same ( _ , l , r ) - > 1 + sz l + sz r
| Diff ( _ , l , r ) - > 1 + sz l + sz r
let h = match h with
Empty - > assert false
| Same ( x , _ , _ ) - > x
| Diff ( x , _ , _ ) - > x
Empty -> Myaset.empty
| Same (x, l, r) -> Myaset.cup (Myaset.sng x) (Myaset.cup (set_of l) (set_of r))
| Diff (x, l, r) -> Myaset.cup (Myaset.sng x) (Myaset.cup (set_of l) (set_of r))
let rec sz t = match t with
Empty -> 0
| Same (_, l, r) -> 1 + sz l + sz r
| Diff (_, l, r) -> 1 + sz l + sz r
let max h = match h with
Empty -> assert false
| Same (x, _, _) -> x
| Diff (x, _, _) -> x*)
let empty = Empty
let rec add x h = match h with
| Empty ->
Same (x, Empty, Empty)
| Same (y, l, r) ->
if x > y then Diff (x, add y l, r) else Diff (y, add x l, r)
| Diff (y, l, r) ->
if x > y then Same (x, l, add y r) else Same (y, l, add x r)
let maximum h = match h with
| Same (x, l, r) -> (x, Same (x, l, r)) | Diff (x, l, r) -> (x, Diff (x, l, r))
let rec extract_last h = match h with
| Same (x, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (x, Empty)
| Same (_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff (_, _, _) -> let _ = assert (1 = 0) in assert false)
| Same (_, _, _) ->
let y,r' = extract_last r in y, Diff (x, l, r')
| Diff (_, _, _) ->
let y,r' = extract_last r in y, Diff (x, l, r'))
| Diff (x, l, r) -> let y,l' = extract_last l in y, Same (x, l', r)
let rec descent x h = match h with
| Empty ->
let _ = assert (1 = 0) in assert false
| Diff (y, l, r) ->
(match r with
| Empty ->
(match l with
| Same (z, ll', lr') ->
if x > z then (y, Diff (x, Same (z, ll, lr), Empty))
else (y, Diff (z, Same (x, Empty, Empty), Empty))
| Diff (_, _, _) -> let _ = assert (1=0) in assert false
| Empty -> let _ = assert (1=0) in assert false)
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Diff (x, l, r))
else if ml > mr then
let (z, l') = descent x l in
(y, Diff (ml, l', r))
else
let (z, r') = descent x r in
(y, Diff (mr, l, r'))
| Same (_, _, _) ->
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Diff (x, l, r))
else if ml > mr then
let (z, l') = descent x l in
(y, Diff (ml, l', r))
else
let (z, r') = descent x r in
(y, Diff (mr, l, r')))
| Same (y, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (y, Same(x, Empty, Empty))
| Same(_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff(_, _, _) -> let _ = assert (1 = 0) in assert false)
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Same (x, l, r))
else if ml > mr then
let (z, l) = descent x l in
(y, Same(ml, l, r))
else
let (z, r) = descent x r in
(y, Same (mr, l, r))
| Same (_, _, _) ->
let (ml, l) = maximum l in
let (mr, r) = maximum r in
if x > ml && x > mr then
(y, Same (x, l, r))
else if ml > mr then
let (z, l) = descent x l in
(y, Same(ml, l, r))
else
let (z, r) = descent x r in
(y, Same (mr, l, r)))
let remove h = match h with
| Same (x, l, r) ->
(match l with
| Empty ->
(match r with
| Empty -> (x, Empty)
| Same (_, _, _) -> let _ = assert (1 = 0) in assert false
| Diff (_, _, _) -> let _ = assert (1 = 0) in assert false)
| Diff (_, _, _) -> let y,h' = extract_last h in descent y h'
| Same (_, _, _) -> let y,h' = extract_last h in descent y h')
| Diff (x, l, r) -> let y,h' = extract_last h in let _ = (fun x -> x) h' in descent y h'
let rec iter f = function
| Empty -> ()
| Same (x, l, r) -> iter f l; f x; iter f r
| Diff (x, l, r) -> iter f l; f x; iter f r
let rec fold f h x0 = match h with
| Empty -> x0
| Same (x, l, r) -> fold f l (fold f r (f x x0))
| Diff (x, l, r) -> fold f l (fold f r (f x x0))
|
89efeec8817aa0681e3a01695b3ec1d8f09674db9a9bc2d3ec8cc9954f8c0bb7 | gogotanaka/Ringo | Compiler.hs | module Ringo where
import Ringo.Parser (eval)
import Data.Functor ((<$>))
import System.Environment (getArgs)
import Data.Char (isSpace)
main :: IO()
main = do
[path] <- getArgs
code <- filter (not.isSpace) <$> readFile path
putStr $ eval code
| null | https://raw.githubusercontent.com/gogotanaka/Ringo/8875f44bea9f8ce51df243f2a0ddaabf8015d4e2/src/Compiler.hs | haskell | module Ringo where
import Ringo.Parser (eval)
import Data.Functor ((<$>))
import System.Environment (getArgs)
import Data.Char (isSpace)
main :: IO()
main = do
[path] <- getArgs
code <- filter (not.isSpace) <$> readFile path
putStr $ eval code
|
|
53a878cac1057a1b9e8f203a81fd58800512559c823cc675260b3351f272c10f | nebogeo/scheme-bricks | persist.scm | 28517 | null | https://raw.githubusercontent.com/nebogeo/scheme-bricks/d275062afef867610fda30ffa016e90b85a953c5/history/persist.scm | scheme | 28517 |
|
ac0aae48fb0d18830ea4d244ec31f8362795efb5093dc435e7f4cb39c8e264a9 | v-kolesnikov/sicp | 1_35_test.clj | (ns sicp.chapter01.1-35-test
(:require [clojure.test :refer :all]
[sicp.test-helper :refer :all]
[sicp.chapter01.1-35 :refer :all]))
(deftest test-fixed-point
(letfn [(cos [x] (Math/cos x))
(sum-of-sin-and-cos [x] (+ (Math/sin x) (Math/cos x)))]
(assert-equal 0.7390822985224024 (fixed-point cos 1.0))
(assert-equal 1.2587315962971173 (fixed-point sum-of-sin-and-cos 1.0))))
(deftest test-golden-ration
(assert-equal 1.6180327868852458 (golden-ration)))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/test/sicp/chapter01/1_35_test.clj | clojure | (ns sicp.chapter01.1-35-test
(:require [clojure.test :refer :all]
[sicp.test-helper :refer :all]
[sicp.chapter01.1-35 :refer :all]))
(deftest test-fixed-point
(letfn [(cos [x] (Math/cos x))
(sum-of-sin-and-cos [x] (+ (Math/sin x) (Math/cos x)))]
(assert-equal 0.7390822985224024 (fixed-point cos 1.0))
(assert-equal 1.2587315962971173 (fixed-point sum-of-sin-and-cos 1.0))))
(deftest test-golden-ration
(assert-equal 1.6180327868852458 (golden-ration)))
|
|
d0873a2d170ad4735d287e7987d1e2fc7013d260fb3a77581965cd2d3da10144 | keera-studios/keera-hails | HLintMain.hs | -----------------------------------------------------------------------------
-- |
-- Module : Main (hlint)
Copyright : ( C ) 2015 , 2013 - 2014
-- License : BSD-style (see the file LICENSE)
Maintainer : < >
-- Stability : provisional
-- Portability : portable
--
-- This module runs HLint on the source tree.
-----------------------------------------------------------------------------
module Main where
import Control.Monad
import Language.Haskell.HLint
import System.Environment
import System.Exit
main :: IO ()
main = do
args <- getArgs
hints <- hlint $ ["src"] ++ args
unless (null hints) exitFailure
| null | https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/keera-hails-reactivelenses/tests/HLintMain.hs | haskell | ---------------------------------------------------------------------------
|
Module : Main (hlint)
License : BSD-style (see the file LICENSE)
Stability : provisional
Portability : portable
This module runs HLint on the source tree.
--------------------------------------------------------------------------- | Copyright : ( C ) 2015 , 2013 - 2014
Maintainer : < >
module Main where
import Control.Monad
import Language.Haskell.HLint
import System.Environment
import System.Exit
main :: IO ()
main = do
args <- getArgs
hints <- hlint $ ["src"] ++ args
unless (null hints) exitFailure
|
595fa7ffa2c87052fbdb17513f63c8774fc2858fcb227cc7257299da79ce11ee | rkallos/canal | canal_tests.erl | -module(canal_tests).
-include_lib("canal/include/canal_internal.hrl").
-include("canal_test.hrl").
-include_lib("eunit/include/eunit.hrl").
%% runners
canal_test_() ->
{setup,
fun () -> setup() end,
fun (_) -> cleanup() end,
[
fun auth_subtest/0,
fun read_subtest/0,
fun write_subtest/0,
fun cache_subtest/0
]}.
%% tests
auth_subtest() ->
Creds = {approle, <<"bob_the_token">>, <<"bob_the_secret">>},
ok = canal:auth(Creds),
Creds = ?GET_OPT(credentials).
read_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
{error, {404, []}} = canal:read(<<"foo">>).
write_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
ok = canal:write(<<"foo">>, <<"bar">>),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>).
cache_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
ok = canal:write(<<"foo">>, <<"bar">>),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>),
canal_http_server:stop(),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>).
%% utils
cleanup() ->
ets:delete(?TABLE),
canal_app:stop(),
canal_http_server:stop().
setup() ->
ets:new(?TABLE, [ordered_set, named_table, public]),
{ok, _} = canal_http_server:start(),
application:set_env(canal, url, <<":8200">>),
canal_app:start().
| null | https://raw.githubusercontent.com/rkallos/canal/b1456e81615e986b04fd6727302972c55e10ad80/test/canal_tests.erl | erlang | runners
tests
utils | -module(canal_tests).
-include_lib("canal/include/canal_internal.hrl").
-include("canal_test.hrl").
-include_lib("eunit/include/eunit.hrl").
canal_test_() ->
{setup,
fun () -> setup() end,
fun (_) -> cleanup() end,
[
fun auth_subtest/0,
fun read_subtest/0,
fun write_subtest/0,
fun cache_subtest/0
]}.
auth_subtest() ->
Creds = {approle, <<"bob_the_token">>, <<"bob_the_secret">>},
ok = canal:auth(Creds),
Creds = ?GET_OPT(credentials).
read_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
{error, {404, []}} = canal:read(<<"foo">>).
write_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
ok = canal:write(<<"foo">>, <<"bar">>),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>).
cache_subtest() ->
ok = canal:auth({approle, <<"bob_the_token">>, <<"bob_the_secret">>}),
ok = canal:write(<<"foo">>, <<"bar">>),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>),
canal_http_server:stop(),
{ok, #{<<"value">> := <<"bar">>}} = canal:read(<<"foo">>).
cleanup() ->
ets:delete(?TABLE),
canal_app:stop(),
canal_http_server:stop().
setup() ->
ets:new(?TABLE, [ordered_set, named_table, public]),
{ok, _} = canal_http_server:start(),
application:set_env(canal, url, <<":8200">>),
canal_app:start().
|
6b2d5f06a08b055c87b9876e5e2b10ffff68c587febcd79b08134dca9c4e5933 | restyled-io/restyled.io | Lens.hs | module Restyled.Test.Lens
( fieldLens
, (.~)
, (?~)
, (^.)
, (^..)
, (^?)
) where
import Restyled.Prelude hiding (fieldLens)
import qualified Database.Persist as P
import Lens.Micro ((.~), (?~), (^.), (^..), (^?))
| Use an ' EntityField ' as a lens
--
-- The library-provided @fieldLens@ is over @'Entity' record@, and we need it
-- over just @record@ for Graphula. This is unsafe when used with a key
' EntityField ' , such as ' JobId ' , which is why the library - provided one works
-- the way that it does.
--
fieldLens
:: PersistEntity record => EntityField record field -> Lens' record field
fieldLens field = unsafeEntityLens . P.fieldLens field
unsafeEntityLens :: Lens' record (Entity record)
unsafeEntityLens = lens (Entity (error "unused")) $ \_ y -> entityVal y
| null | https://raw.githubusercontent.com/restyled-io/restyled.io/e3208b62dfea0916b9760cf8dd73abc7c5f080bb/test/Restyled/Test/Lens.hs | haskell |
The library-provided @fieldLens@ is over @'Entity' record@, and we need it
over just @record@ for Graphula. This is unsafe when used with a key
the way that it does.
| module Restyled.Test.Lens
( fieldLens
, (.~)
, (?~)
, (^.)
, (^..)
, (^?)
) where
import Restyled.Prelude hiding (fieldLens)
import qualified Database.Persist as P
import Lens.Micro ((.~), (?~), (^.), (^..), (^?))
| Use an ' EntityField ' as a lens
' EntityField ' , such as ' JobId ' , which is why the library - provided one works
fieldLens
:: PersistEntity record => EntityField record field -> Lens' record field
fieldLens field = unsafeEntityLens . P.fieldLens field
unsafeEntityLens :: Lens' record (Entity record)
unsafeEntityLens = lens (Entity (error "unused")) $ \_ y -> entityVal y
|
18be621b21705ab8db0a72bb89fa8fa6b3d27fc2db5b2dc089eb95d4553e72a9 | strojure/zizzmap | core_02_assoc.clj | (ns project.readme.core-02-assoc
(:require [strojure.zizzmap.core :as zizz]))
(def ^:private -map1
(zizz/assoc* {} :a (do (println "Init") 1)))
(get -map1 :a)
Init
= > 1
(def ^:private -map2
(zizz/assoc* {}
:a (do (println "Init :a") 1)
:b (do (println "Init :b") 2)))
(get -map2 :b)
Init
= > 2 | null | https://raw.githubusercontent.com/strojure/zizzmap/45bdffbd6d7eeeb06566e699dd69e34835187cd7/test/project/readme/core_02_assoc.clj | clojure | (ns project.readme.core-02-assoc
(:require [strojure.zizzmap.core :as zizz]))
(def ^:private -map1
(zizz/assoc* {} :a (do (println "Init") 1)))
(get -map1 :a)
Init
= > 1
(def ^:private -map2
(zizz/assoc* {}
:a (do (println "Init :a") 1)
:b (do (println "Init :b") 2)))
(get -map2 :b)
Init
= > 2 |
|
b83adf248f92d305ff3fb7ca2dd03690ce9d45e19d94771bf5ca00c6153cb1d2 | fortytools/holumbus | ClientMain.hs | -- ----------------------------------------------------------------------------
|
Module :
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Module :
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
-}
-- ----------------------------------------------------------------------------
module Main(main) where
import Holumbus.Common.Logging
import Holumbus.Common.Utils ( handleAll )
import Holumbus.Network.PortRegistry.PortRegistryPort
import qualified Holumbus.Distribution.DMapReduce as MR
import Holumbus.MapReduce.Types
import Holumbus.MapReduce.MapReduce
import Examples.MapReduce.Sort.Sort
version :: String
version = "Holumbus-Distribution Standalone-Client 0.1"
main :: IO ()
main
= do
putStrLn version
handleAll (\e -> putStrLn $ "EXCEPTION: " ++ show e) $
do
initializeLogging []
p <- newPortRegistryFromXmlFile "/tmp/registry.xml"
setPortRegistry p
mr <- initializeData
(ls,_) <- doMapReduce (sortAction) () namesList [] 1 5 1 1 TOTRawTuple mr
putStrLn "Result: "
putStrLn $ show ls
deinitializeData mr
initializeData :: IO (MR.DMapReduce)
initializeData
= do
let config = MR.defaultMRClientConfig
MR.mkMapReduceClient config
deinitializeData :: MR.DMapReduce -> IO ()
deinitializeData mr
= do
MR.closeMapReduce mr
-- ----------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/mapreduce/Examples/MapReduce/Sort/ClientMain.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | |
Module :
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Module :
Copyright : Copyright (C) 2008 Stefan Schmidt
License : MIT
Maintainer : Stefan Schmidt ()
Stability : experimental
Portability: portable
Version : 0.1
-}
module Main(main) where
import Holumbus.Common.Logging
import Holumbus.Common.Utils ( handleAll )
import Holumbus.Network.PortRegistry.PortRegistryPort
import qualified Holumbus.Distribution.DMapReduce as MR
import Holumbus.MapReduce.Types
import Holumbus.MapReduce.MapReduce
import Examples.MapReduce.Sort.Sort
version :: String
version = "Holumbus-Distribution Standalone-Client 0.1"
main :: IO ()
main
= do
putStrLn version
handleAll (\e -> putStrLn $ "EXCEPTION: " ++ show e) $
do
initializeLogging []
p <- newPortRegistryFromXmlFile "/tmp/registry.xml"
setPortRegistry p
mr <- initializeData
(ls,_) <- doMapReduce (sortAction) () namesList [] 1 5 1 1 TOTRawTuple mr
putStrLn "Result: "
putStrLn $ show ls
deinitializeData mr
initializeData :: IO (MR.DMapReduce)
initializeData
= do
let config = MR.defaultMRClientConfig
MR.mkMapReduceClient config
deinitializeData :: MR.DMapReduce -> IO ()
deinitializeData mr
= do
MR.closeMapReduce mr
|
fef08ce51eb3b8c0ae6ca1869adfe26a52cc06c991439e89df59be5f90a8b189 | mcorbin/meuse | token.clj | (ns meuse.db.public.token
(:require [meuse.db :refer [database]]
[meuse.db.actions.token :as token]
[mount.core :refer [defstate]]))
(defprotocol ITokenDB
(by-user [this user-name])
(create [this token])
(delete [this user-name token-name])
(set-last-used [this token-id])
(get-token-user-role [this token]))
(defrecord TokenDB [database]
ITokenDB
(by-user [this user-name]
(token/by-user database user-name))
(create [this token]
(token/create database token))
(delete [this user-name token-name]
(token/delete database user-name token-name))
(set-last-used [this token-id]
(token/set-last-used database token-id))
(get-token-user-role [this token]
(token/get-token-user-role database token)))
(defstate token-db
:start (TokenDB. database))
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/db/public/token.clj | clojure | (ns meuse.db.public.token
(:require [meuse.db :refer [database]]
[meuse.db.actions.token :as token]
[mount.core :refer [defstate]]))
(defprotocol ITokenDB
(by-user [this user-name])
(create [this token])
(delete [this user-name token-name])
(set-last-used [this token-id])
(get-token-user-role [this token]))
(defrecord TokenDB [database]
ITokenDB
(by-user [this user-name]
(token/by-user database user-name))
(create [this token]
(token/create database token))
(delete [this user-name token-name]
(token/delete database user-name token-name))
(set-last-used [this token-id]
(token/set-last-used database token-id))
(get-token-user-role [this token]
(token/get-token-user-role database token)))
(defstate token-db
:start (TokenDB. database))
|
|
a92e878cb1c2b534452763814a355da7fed4674572e6aeffa7662bca4856710d | alang9/dynamic-graphs | EulerTour.hs | -- | This module provides dynamic connectivity for an acyclic graph (i.e. a
-- forest).
--
-- It is based on:
-- /Finding biconnected components and computing tree functions in logarithmic parallel time/
by and Uzi Vishki/ ( 1984 ) .
--
We use two naming conventions in this module :
--
-- * A prime suffix (@'@) indicates a simpler or less polymorphic version of a
-- function or datatype. For example, see 'empty' and 'empty'', and
-- 'Graph' and 'Graph''.
--
-- * An underscore suffix (@_@) means that the return value is ignored. For
-- example, see 'link' and 'link_'.
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE ScopedTypeVariables #
module Data.Graph.Dynamic.EulerTour
( -- * Type
Forest
, Graph
, Graph'
-- * Construction
, empty
, empty'
, edgeless
, edgeless'
, fromTree
, fromTree'
-- * Queries
, connected
, edge
, vertex
, neighbours
-- * Modifying
, link
, link_
, cut
, cut_
, insert
, insert_
, delete
, delete_
-- * Advanced/internal operations
, findRoot
, componentSize
, spanningForest
-- * Debugging
, print
) where
import Control.Monad (filterM, foldM, forM_,
void)
import Control.Monad.Primitive
import qualified Data.Graph.Dynamic.Internal.HashTable as HT
import qualified Data.Graph.Dynamic.Internal.Random as Random
import qualified Data.Graph.Dynamic.Internal.Tree as Tree
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as HMS
import qualified Data.HashSet as HS
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe
import Data.Monoid
import Data.Proxy (Proxy (..))
import qualified Data.Tree as DT
import Prelude hiding (print)
| The most general type for an Euler Tour Forest . Used by other modules .
data Forest t a s v = ETF
{ edges :: {-# UNPACK#-} !(HT.HashTable s v (HMS.HashMap v (t s (v, v) a)))
, toMonoid :: v -> v -> a
, treeGen :: (Tree.TreeGen t s)
}
-- | Graph type polymorphic in the tree used to represent sequences.
type Graph t s v = Forest t () s v
-- | Simple graph type.
type Graph' s v = Graph Random.Tree s v
insertTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> t s (v, v) a -> m ()
insertTree (ETF ht _ _) x y t = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> HT.insert ht x $ HMS.singleton y t
Just m -> HT.insert ht x $ HMS.insert y t m
lookupTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> m (Maybe (t s (v, v) (a)))
lookupTree (ETF ht _ _) x y = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return Nothing
Just m -> return $ HMS.lookup y m
deleteTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> m ()
deleteTree (ETF ht _ _) x y = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return ()
Just m0 ->
let m1 = HMS.delete y m0 in
if HMS.null m1 then HT.delete ht x else HT.insert ht x m1
-- | /O(1)/
--
-- Create the empty tree.
empty
:: forall t m v a. (Tree.Tree t, PrimMonad m)
=> (v -> v -> a) -> m (Forest t a (PrimState m) v)
empty f = do
ht <- HT.new
tg <- Tree.newTreeGen (Proxy :: Proxy t)
return $ ETF ht f tg
-- | Simple version of 'empty'.
empty'
:: PrimMonad m => m (Graph' (PrimState m) v)
empty' = empty (\_ _ -> ())
-- | /O(v*log(v))/
--
-- Create a graph with the given vertices but no edges.
edgeless
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> (v -> v -> a) -> [v] -> m (Forest t a (PrimState m) v)
edgeless toMonoid vs = do
etf <- empty toMonoid
forM_ vs $ \v -> do
node <- Tree.singleton (treeGen etf) (v, v) (toMonoid v v)
insertTree etf v v node
return etf
-- | Simple version of 'edgeless'.
edgeless'
:: (Eq v, Hashable v, PrimMonad m)
=> [v] -> m (Graph' (PrimState m) v)
edgeless' = edgeless (\_ _ -> ())
-- | Create a graph from a 'DT.Tree'. Note that the values in nodes must be
-- unique.
fromTree
:: forall v m t a. (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> (v -> v -> a) -> DT.Tree v -> m (Forest t a (PrimState m) v)
fromTree toMonoid tree = do
etf <- empty toMonoid
_ <- go etf tree
return etf
where
go etf (DT.Node l children) = do
node0 <- Tree.singleton (treeGen etf) (l, l) (toMonoid l l)
insertTree etf l l node0
foldM (go' etf l) node0 children
go' etf parent node0 tr@(DT.Node l _) = do
lnode <- go etf tr
parentToL <- Tree.singleton (treeGen etf) (parent, l) (toMonoid parent l)
lToParent <- Tree.singleton (treeGen etf) (l, parent) (toMonoid l parent)
node1 <- Tree.concat $ node0 NonEmpty.:| [parentToL, lnode, lToParent]
insertTree etf l parent lToParent
insertTree etf parent l parentToL
return node1
| Simple version of .
fromTree'
:: (Eq v, Hashable v, PrimMonad m)
=> DT.Tree v -> m (Graph' (PrimState m) v)
fromTree' = fromTree (\_ _ -> ())
findRoot
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m, Monoid a)
=> Forest t a s v -> v -> m (Maybe (t s (v, v) a))
findRoot etf v = do
mbTree <- lookupTree etf v v
case mbTree of
Nothing -> return Nothing
Just t -> Just <$> Tree.root t
-- | /O(log(v))/
--
Remove an edge in between two vertices . If there is no edge in between
-- these vertices, do nothing. Return whether or not an edge was actually
-- removed.
cut
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
cut etf a b = do
mbAb <- lookupTree etf a b
mbBa <- lookupTree etf b a
case (mbAb, mbBa) of
_ | a == b -> return False -- Can't cut self-loops
(Just ab, Just ba) -> do
(part1, part2) <- Tree.split ab
baIsInPart1 <- case part1 of
Just p -> Tree.connected p ba
_ -> return False
(mbL, _, mbR) <- if baIsInPart1 then do
(part3, part4) <- Tree.split ba
return (part3, part4, part2)
else do
(part3, part4) <- Tree.split ba
return (part1, part3, part4)
_ <- sequenceA $ Tree.append <$> mbL <*> mbR
deleteTree etf a b
deleteTree etf b a
return True
(Nothing, _) -> return False -- No edge to cut
(_, Nothing) -> return False -- No edge to cut
-- | Version of 'cut' which ignores the result.
cut_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m ()
cut_ etf a b = void (cut etf a b)
-- | reroot the represented tree by shifting the euler tour. Returns the new
-- root.
reroot
:: (Tree.Tree t, PrimMonad m, s ~ PrimState m, Monoid v)
=> t s a v -> m (t s a v)
reroot t = do
(mbPre, mbPost) <- Tree.split t
t1 <- maybe (return t) (t `Tree.cons`) mbPost
maybe (return t1) (t1 `Tree.append`) mbPre
-- | /O(log(v))/
--
-- Check if this edge exists in the graph.
edge
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
edge etf a b = isJust <$> lookupTree etf a b
-- | /O(log(v))/
--
-- Check if this vertex exists in the graph.
vertex
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m)
=> Forest t a (PrimState m) v -> v -> m Bool
vertex etf a = isJust <$> lookupTree etf a a
-- | /O(log(v))/
--
Check if a path exists in between two vertices .
connected
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
connected etf a b = do
mbALoop <- lookupTree etf a a
mbBLoop <- lookupTree etf b b
case (mbALoop, mbBLoop) of
(Just aLoop, Just bLoop) -> Tree.connected aLoop bLoop
_ -> return False
-- | /O(log(v))/
--
Insert an edge in between two vertices . If the vertices are already
-- connected, we don't do anything, since this is an acyclic graph. Returns
-- whether or not an edge was actually inserted.
link
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
link etf@ETF{..} a b = do
mbALoop <- lookupTree etf a a
mbBLoop <- lookupTree etf b b
case (mbALoop, mbBLoop) of
(Just aLoop, Just bLoop) -> Tree.connected aLoop bLoop >>= \case
True -> return False
False -> do
bLoop1 <- reroot bLoop
abNode <- Tree.singleton treeGen (a, b) (toMonoid a b)
baNode <- Tree.singleton treeGen (b, a) (toMonoid b a)
bLoop2 <- abNode `Tree.cons` bLoop1
bLoop3 <- bLoop2 `Tree.snoc` baNode
(mbPreA, mbPostA) <- Tree.split aLoop
_ <- Tree.concat $
aLoop NonEmpty.:| catMaybes
[ Just bLoop3
, mbPostA
, mbPreA
]
insertTree etf a b abNode
insertTree etf b a baNode
return True
_ -> return False
-- | Version of 'link' which ignores the result.
link_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m ()
link_ etf a b = void (link etf a b)
-- | /O(log(v))/
--
-- Insert a new vertex. Do nothing if it is already there. Returns whether
-- or not a vertex was inserted in the graph.
insert
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m Bool
insert etf@ETF{..} v = do
mbTree <- lookupTree etf v v
case mbTree of
Just _ -> return False
Nothing -> do
node <- Tree.singleton treeGen (v, v) (toMonoid v v)
insertTree etf v v node
return True
-- | Version of 'insert' which ignores the result.
insert_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m ()
insert_ etf v = void (insert etf v)
-- | /O(log(v) + n/ where /n/ is the number of neighbours
--
-- Get all neighbours of the given vertex.
neighbours
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m [v]
neighbours etf x = fromMaybe [] <$> maybeNeighbours etf x
maybeNeighbours
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m (Maybe [v])
maybeNeighbours (ETF ht _ _) x = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return Nothing
Just m -> return $ Just $ filter (/= x) $ map fst $ HMS.toList m
-- | /O(n*log(v))/ where /n/ is the number of neighbours
--
-- Remove a vertex from the graph, if it exists. If it is connected to any
other vertices , those edges are cut first . Returns whether or not a vertex
-- was removed from the graph.
delete
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m Bool
delete etf x = do
mbNbs <- maybeNeighbours etf x
case mbNbs of
Nothing -> return False
Just nbs -> do
forM_ nbs $ \y -> cut etf x y
deleteTree etf x x
return True
-- | Version of 'delete' which ignores the result.
delete_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m ()
delete_ etf x = void (delete etf x)
print :: (Show a, Monoid b, Tree.TestTree t) => Forest t b RealWorld a -> IO ()
print (ETF ht _ _) = do
maps <- map snd <$> HT.toList ht
let trees = concatMap (map snd . HMS.toList) maps
comps <- components trees
forM_ comps $ \comp -> do
root <- Tree.root comp
Tree.print root
putStrLn ""
where
components [] = return []
components (t : ts) = do
ts' <- filterM (fmap not . Tree.connected t) ts
(t :) <$> components ts'
componentSize
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t (Sum Int) s v -> v -> m Int
componentSize etf v = do
mbTree <- lookupTree etf v v
case mbTree of
Nothing -> return 0
Just tree -> do
root <- Tree.root tree
getSum <$> Tree.aggregate root
-- | Obtain the current spanning forest.
spanningForest
:: (Eq v, Hashable v, Tree.Tree t, Monoid a, PrimMonad m)
=> Forest t a (PrimState m) v -> m (DT.Forest v)
spanningForest (ETF ht _ _) = do
maps <- map snd <$> HT.toList ht
let trees = concatMap (map snd . HMS.toList) maps
go HS.empty [] trees
where
go _visited acc [] = return acc
go visited acc (t : ts) = do
root <- Tree.readRoot t
label <- Tree.label root
if HS.member label visited then
go visited acc ts
else do
st <- spanningTree root
go (HS.insert label visited) (st : acc) ts
spanningTree
:: (Eq v, Hashable v, PrimMonad m, Monoid e, Tree.Tree t)
=> t (PrimState m) (v, v) e -> m (DT.Tree v)
spanningTree tree = do
list <- Tree.toList tree
case list of
((r, _) : _) -> return $ DT.Node r (fst $ go Nothing [] list)
_ -> error
"Data.Graph.Dynamic..EulerTour.spanningTree: empty list"
where
go _mbParent acc [] = (acc, [])
go mbParent acc ((a, b) : edges)
| a == b = go mbParent acc edges -- Ignore self-loops.
| Just b == mbParent = (acc, edges) -- Like a closing bracket.
| otherwise =
child .
let (child, rest) = go (Just a) [] edges in
go mbParent (DT.Node b child : acc) rest
| null | https://raw.githubusercontent.com/alang9/dynamic-graphs/b88f001850c7bee8faa62099e93172a0bb0df613/src/Data/Graph/Dynamic/EulerTour.hs | haskell | | This module provides dynamic connectivity for an acyclic graph (i.e. a
forest).
It is based on:
/Finding biconnected components and computing tree functions in logarithmic parallel time/
* A prime suffix (@'@) indicates a simpler or less polymorphic version of a
function or datatype. For example, see 'empty' and 'empty'', and
'Graph' and 'Graph''.
* An underscore suffix (@_@) means that the return value is ignored. For
example, see 'link' and 'link_'.
# LANGUAGE RecordWildCards #
* Type
* Construction
* Queries
* Modifying
* Advanced/internal operations
* Debugging
# UNPACK#
| Graph type polymorphic in the tree used to represent sequences.
| Simple graph type.
| /O(1)/
Create the empty tree.
| Simple version of 'empty'.
| /O(v*log(v))/
Create a graph with the given vertices but no edges.
| Simple version of 'edgeless'.
| Create a graph from a 'DT.Tree'. Note that the values in nodes must be
unique.
| /O(log(v))/
these vertices, do nothing. Return whether or not an edge was actually
removed.
Can't cut self-loops
No edge to cut
No edge to cut
| Version of 'cut' which ignores the result.
| reroot the represented tree by shifting the euler tour. Returns the new
root.
| /O(log(v))/
Check if this edge exists in the graph.
| /O(log(v))/
Check if this vertex exists in the graph.
| /O(log(v))/
| /O(log(v))/
connected, we don't do anything, since this is an acyclic graph. Returns
whether or not an edge was actually inserted.
| Version of 'link' which ignores the result.
| /O(log(v))/
Insert a new vertex. Do nothing if it is already there. Returns whether
or not a vertex was inserted in the graph.
| Version of 'insert' which ignores the result.
| /O(log(v) + n/ where /n/ is the number of neighbours
Get all neighbours of the given vertex.
| /O(n*log(v))/ where /n/ is the number of neighbours
Remove a vertex from the graph, if it exists. If it is connected to any
was removed from the graph.
| Version of 'delete' which ignores the result.
| Obtain the current spanning forest.
Ignore self-loops.
Like a closing bracket. | by and Uzi Vishki/ ( 1984 ) .
We use two naming conventions in this module :
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Data.Graph.Dynamic.EulerTour
Forest
, Graph
, Graph'
, empty
, empty'
, edgeless
, edgeless'
, fromTree
, fromTree'
, connected
, edge
, vertex
, neighbours
, link
, link_
, cut
, cut_
, insert
, insert_
, delete
, delete_
, findRoot
, componentSize
, spanningForest
, print
) where
import Control.Monad (filterM, foldM, forM_,
void)
import Control.Monad.Primitive
import qualified Data.Graph.Dynamic.Internal.HashTable as HT
import qualified Data.Graph.Dynamic.Internal.Random as Random
import qualified Data.Graph.Dynamic.Internal.Tree as Tree
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as HMS
import qualified Data.HashSet as HS
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe
import Data.Monoid
import Data.Proxy (Proxy (..))
import qualified Data.Tree as DT
import Prelude hiding (print)
| The most general type for an Euler Tour Forest . Used by other modules .
data Forest t a s v = ETF
, toMonoid :: v -> v -> a
, treeGen :: (Tree.TreeGen t s)
}
type Graph t s v = Forest t () s v
type Graph' s v = Graph Random.Tree s v
insertTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> t s (v, v) a -> m ()
insertTree (ETF ht _ _) x y t = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> HT.insert ht x $ HMS.singleton y t
Just m -> HT.insert ht x $ HMS.insert y t m
lookupTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> m (Maybe (t s (v, v) (a)))
lookupTree (ETF ht _ _) x y = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return Nothing
Just m -> return $ HMS.lookup y m
deleteTree
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t a s v -> v -> v -> m ()
deleteTree (ETF ht _ _) x y = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return ()
Just m0 ->
let m1 = HMS.delete y m0 in
if HMS.null m1 then HT.delete ht x else HT.insert ht x m1
empty
:: forall t m v a. (Tree.Tree t, PrimMonad m)
=> (v -> v -> a) -> m (Forest t a (PrimState m) v)
empty f = do
ht <- HT.new
tg <- Tree.newTreeGen (Proxy :: Proxy t)
return $ ETF ht f tg
empty'
:: PrimMonad m => m (Graph' (PrimState m) v)
empty' = empty (\_ _ -> ())
edgeless
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> (v -> v -> a) -> [v] -> m (Forest t a (PrimState m) v)
edgeless toMonoid vs = do
etf <- empty toMonoid
forM_ vs $ \v -> do
node <- Tree.singleton (treeGen etf) (v, v) (toMonoid v v)
insertTree etf v v node
return etf
edgeless'
:: (Eq v, Hashable v, PrimMonad m)
=> [v] -> m (Graph' (PrimState m) v)
edgeless' = edgeless (\_ _ -> ())
fromTree
:: forall v m t a. (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> (v -> v -> a) -> DT.Tree v -> m (Forest t a (PrimState m) v)
fromTree toMonoid tree = do
etf <- empty toMonoid
_ <- go etf tree
return etf
where
go etf (DT.Node l children) = do
node0 <- Tree.singleton (treeGen etf) (l, l) (toMonoid l l)
insertTree etf l l node0
foldM (go' etf l) node0 children
go' etf parent node0 tr@(DT.Node l _) = do
lnode <- go etf tr
parentToL <- Tree.singleton (treeGen etf) (parent, l) (toMonoid parent l)
lToParent <- Tree.singleton (treeGen etf) (l, parent) (toMonoid l parent)
node1 <- Tree.concat $ node0 NonEmpty.:| [parentToL, lnode, lToParent]
insertTree etf l parent lToParent
insertTree etf parent l parentToL
return node1
| Simple version of .
fromTree'
:: (Eq v, Hashable v, PrimMonad m)
=> DT.Tree v -> m (Graph' (PrimState m) v)
fromTree' = fromTree (\_ _ -> ())
findRoot
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m, Monoid a)
=> Forest t a s v -> v -> m (Maybe (t s (v, v) a))
findRoot etf v = do
mbTree <- lookupTree etf v v
case mbTree of
Nothing -> return Nothing
Just t -> Just <$> Tree.root t
Remove an edge in between two vertices . If there is no edge in between
cut
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
cut etf a b = do
mbAb <- lookupTree etf a b
mbBa <- lookupTree etf b a
case (mbAb, mbBa) of
(Just ab, Just ba) -> do
(part1, part2) <- Tree.split ab
baIsInPart1 <- case part1 of
Just p -> Tree.connected p ba
_ -> return False
(mbL, _, mbR) <- if baIsInPart1 then do
(part3, part4) <- Tree.split ba
return (part3, part4, part2)
else do
(part3, part4) <- Tree.split ba
return (part1, part3, part4)
_ <- sequenceA $ Tree.append <$> mbL <*> mbR
deleteTree etf a b
deleteTree etf b a
return True
cut_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m ()
cut_ etf a b = void (cut etf a b)
reroot
:: (Tree.Tree t, PrimMonad m, s ~ PrimState m, Monoid v)
=> t s a v -> m (t s a v)
reroot t = do
(mbPre, mbPost) <- Tree.split t
t1 <- maybe (return t) (t `Tree.cons`) mbPost
maybe (return t1) (t1 `Tree.append`) mbPre
edge
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
edge etf a b = isJust <$> lookupTree etf a b
vertex
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m)
=> Forest t a (PrimState m) v -> v -> m Bool
vertex etf a = isJust <$> lookupTree etf a a
Check if a path exists in between two vertices .
connected
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
connected etf a b = do
mbALoop <- lookupTree etf a a
mbBLoop <- lookupTree etf b b
case (mbALoop, mbBLoop) of
(Just aLoop, Just bLoop) -> Tree.connected aLoop bLoop
_ -> return False
Insert an edge in between two vertices . If the vertices are already
link
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m Bool
link etf@ETF{..} a b = do
mbALoop <- lookupTree etf a a
mbBLoop <- lookupTree etf b b
case (mbALoop, mbBLoop) of
(Just aLoop, Just bLoop) -> Tree.connected aLoop bLoop >>= \case
True -> return False
False -> do
bLoop1 <- reroot bLoop
abNode <- Tree.singleton treeGen (a, b) (toMonoid a b)
baNode <- Tree.singleton treeGen (b, a) (toMonoid b a)
bLoop2 <- abNode `Tree.cons` bLoop1
bLoop3 <- bLoop2 `Tree.snoc` baNode
(mbPreA, mbPostA) <- Tree.split aLoop
_ <- Tree.concat $
aLoop NonEmpty.:| catMaybes
[ Just bLoop3
, mbPostA
, mbPreA
]
insertTree etf a b abNode
insertTree etf b a baNode
return True
_ -> return False
link_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> v -> m ()
link_ etf a b = void (link etf a b)
insert
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m Bool
insert etf@ETF{..} v = do
mbTree <- lookupTree etf v v
case mbTree of
Just _ -> return False
Nothing -> do
node <- Tree.singleton treeGen (v, v) (toMonoid v v)
insertTree etf v v node
return True
insert_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m ()
insert_ etf v = void (insert etf v)
neighbours
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m [v]
neighbours etf x = fromMaybe [] <$> maybeNeighbours etf x
maybeNeighbours
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m (Maybe [v])
maybeNeighbours (ETF ht _ _) x = do
mbMap <- HT.lookup ht x
case mbMap of
Nothing -> return Nothing
Just m -> return $ Just $ filter (/= x) $ map fst $ HMS.toList m
other vertices , those edges are cut first . Returns whether or not a vertex
delete
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m Bool
delete etf x = do
mbNbs <- maybeNeighbours etf x
case mbNbs of
Nothing -> return False
Just nbs -> do
forM_ nbs $ \y -> cut etf x y
deleteTree etf x x
return True
delete_
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, Monoid a)
=> Forest t a (PrimState m) v -> v -> m ()
delete_ etf x = void (delete etf x)
print :: (Show a, Monoid b, Tree.TestTree t) => Forest t b RealWorld a -> IO ()
print (ETF ht _ _) = do
maps <- map snd <$> HT.toList ht
let trees = concatMap (map snd . HMS.toList) maps
comps <- components trees
forM_ comps $ \comp -> do
root <- Tree.root comp
Tree.print root
putStrLn ""
where
components [] = return []
components (t : ts) = do
ts' <- filterM (fmap not . Tree.connected t) ts
(t :) <$> components ts'
componentSize
:: (Eq v, Hashable v, Tree.Tree t, PrimMonad m, s ~ PrimState m)
=> Forest t (Sum Int) s v -> v -> m Int
componentSize etf v = do
mbTree <- lookupTree etf v v
case mbTree of
Nothing -> return 0
Just tree -> do
root <- Tree.root tree
getSum <$> Tree.aggregate root
spanningForest
:: (Eq v, Hashable v, Tree.Tree t, Monoid a, PrimMonad m)
=> Forest t a (PrimState m) v -> m (DT.Forest v)
spanningForest (ETF ht _ _) = do
maps <- map snd <$> HT.toList ht
let trees = concatMap (map snd . HMS.toList) maps
go HS.empty [] trees
where
go _visited acc [] = return acc
go visited acc (t : ts) = do
root <- Tree.readRoot t
label <- Tree.label root
if HS.member label visited then
go visited acc ts
else do
st <- spanningTree root
go (HS.insert label visited) (st : acc) ts
spanningTree
:: (Eq v, Hashable v, PrimMonad m, Monoid e, Tree.Tree t)
=> t (PrimState m) (v, v) e -> m (DT.Tree v)
spanningTree tree = do
list <- Tree.toList tree
case list of
((r, _) : _) -> return $ DT.Node r (fst $ go Nothing [] list)
_ -> error
"Data.Graph.Dynamic..EulerTour.spanningTree: empty list"
where
go _mbParent acc [] = (acc, [])
go mbParent acc ((a, b) : edges)
| otherwise =
child .
let (child, rest) = go (Just a) [] edges in
go mbParent (DT.Node b child : acc) rest
|
d31d5e864678692d09824ba1182c4efeec3c69f25ff00094e79125e552fac711 | fujita-y/ypsilon | srfi-41.scm | #!nobacktrace
(define-library (srfi srfi-41)
(import (srfi 41))
(export stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match _
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/44260d99e24000f9847e79c94826c3d9b76872c2/sitelib/srfi/srfi-41.scm | scheme | #!nobacktrace
(define-library (srfi srfi-41)
(import (srfi 41))
(export stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match _
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip))
|
|
853cbe6575a77db8af74abe71d6467368c027ee7a5b50dec46e2a6401bb5e2ca | awakesecurity/gRPC-haskell | Unregistered.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE ScopedTypeVariables #
module Network.GRPC.HighLevel.Server.Unregistered where
import Control.Arrow
import Control.Concurrent.MVar (newEmptyMVar,
putMVar,
takeMVar)
import qualified Control.Exception as CE
import Control.Monad
import Data.Foldable (find)
import Network.GRPC.HighLevel.Server
import Network.GRPC.LowLevel
import Network.GRPC.LowLevel.Server (forkServer)
import qualified Network.GRPC.LowLevel.Call.Unregistered as U
import qualified Network.GRPC.LowLevel.Server.Unregistered as U
import Proto3.Suite.Class
dispatchLoop :: Server
-> (String -> IO ())
-> MetadataMap
-> [Handler 'Normal]
-> [Handler 'ClientStreaming]
-> [Handler 'ServerStreaming]
-> [Handler 'BiDiStreaming]
-> IO ()
dispatchLoop s logger md hN hC hS hB =
forever $ U.withServerCallAsync s $ \sc ->
case findHandler sc allHandlers of
Just (AnyHandler ah) -> case ah of
UnaryHandler _ h -> unaryHandler sc h
ClientStreamHandler _ h -> csHandler sc h
ServerStreamHandler _ h -> ssHandler sc h
BiDiStreamHandler _ h -> bdHandler sc h
Nothing -> unknownHandler sc
where
allHandlers = map AnyHandler hN ++ map AnyHandler hC
++ map AnyHandler hS ++ map AnyHandler hB
findHandler sc = find ((== U.callMethod sc) . anyHandlerMethodName)
unaryHandler :: (Message a, Message b) => U.ServerCall -> ServerHandler a b -> IO ()
unaryHandler sc h =
handleError $
U.serverHandleNormalCall' s sc md $ \_sc' bs ->
convertServerHandler h (const bs <$> U.convertCall sc)
csHandler :: (Message a, Message b) => U.ServerCall -> ServerReaderHandler a b -> IO ()
csHandler sc = handleError . U.serverReader s sc md . convertServerReaderHandler
ssHandler :: (Message a, Message b) => U.ServerCall -> ServerWriterHandler a b -> IO ()
ssHandler sc = handleError . U.serverWriter s sc md . convertServerWriterHandler
bdHandler :: (Message a, Message b) => U.ServerCall -> ServerRWHandler a b -> IO ()
bdHandler sc = handleError . U.serverRW s sc md . convertServerRWHandler
unknownHandler :: U.ServerCall -> IO ()
unknownHandler sc = void $ U.serverHandleNormalCall' s sc md $ \_ _ ->
return (mempty, mempty, StatusNotFound, StatusDetails "unknown method")
handleError :: IO a -> IO ()
handleError = (handleCallError logger . left herr =<<) . CE.try
where herr (e :: CE.SomeException) = GRPCIOHandlerException (show e)
serverLoop :: ServerOptions -> IO ()
serverLoop ServerOptions{..} =
In the library , " doc / core / epoll - polling - engine.md " seems
-- to indicate that the thread which actually awakens from sleep
-- on file descriptor events may differ from the one which seeks
-- to "pluck" the resulting event.
--
-- Thus it seems possible that "dispatchLoop" may be waiting on
-- a condition variable when the "serverLoop" thread is killed.
--
Note that " pthread_cond_timedwait " never returns ; see :
< >
--
Therefore to awaken " dispatchLoop " we must initiate a
shutdown ; it would not suffice to kill its thread .
( Presumably a shutdown broadcasts on relvant condition
-- variables; regardless, we do see it awaken "dispatchLoop".)
--
The " withServer " cleanup code will initiate a shutdown .
-- We arrange to trigger it by leaving the "serverLoop" thread
in an interruptible sleep ( " takeMVar " ) while " dispatchLoop "
-- runs in its own thread.
withGRPC $ \grpc ->
withServer grpc config $ \server -> do
Killing the " serverLoop " thread triggers the " withServer "
-- cleanup code, which initiates a shutdown, which in turn
-- kills the "dispatchLoop" thread and any other thread we
-- may have started with "forkServer".
done <- newEmptyMVar
launched <- forkServer server $
dispatchLoop server
optLogger
optInitialMetadata
optNormalHandlers
optClientStreamHandlers
optServerStreamHandlers
optBiDiStreamHandlers
`CE.finally` putMVar done ()
when launched $
takeMVar done
where
config = ServerConfig
{ host = optServerHost
, port = optServerPort
, methodsToRegisterNormal = []
, methodsToRegisterClientStreaming = []
, methodsToRegisterServerStreaming = []
, methodsToRegisterBiDiStreaming = []
, serverArgs =
[CompressionAlgArg GrpcCompressDeflate | optUseCompression]
++
[ UserAgentPrefix optUserAgentPrefix
, UserAgentSuffix optUserAgentSuffix
]
++
foldMap (pure . MaxReceiveMessageLength) optMaxReceiveMessageLength
++
foldMap (pure . MaxMetadataSize) optMaxMetadataSize
, sslConfig = optSSLConfig
}
| null | https://raw.githubusercontent.com/awakesecurity/gRPC-haskell/112777023f475ddd752c954056e679fbca0baa44/src/Network/GRPC/HighLevel/Server/Unregistered.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE RecordWildCards #
to indicate that the thread which actually awakens from sleep
on file descriptor events may differ from the one which seeks
to "pluck" the resulting event.
Thus it seems possible that "dispatchLoop" may be waiting on
a condition variable when the "serverLoop" thread is killed.
variables; regardless, we do see it awaken "dispatchLoop".)
We arrange to trigger it by leaving the "serverLoop" thread
runs in its own thread.
cleanup code, which initiates a shutdown, which in turn
kills the "dispatchLoop" thread and any other thread we
may have started with "forkServer". | # LANGUAGE GADTs #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Network.GRPC.HighLevel.Server.Unregistered where
import Control.Arrow
import Control.Concurrent.MVar (newEmptyMVar,
putMVar,
takeMVar)
import qualified Control.Exception as CE
import Control.Monad
import Data.Foldable (find)
import Network.GRPC.HighLevel.Server
import Network.GRPC.LowLevel
import Network.GRPC.LowLevel.Server (forkServer)
import qualified Network.GRPC.LowLevel.Call.Unregistered as U
import qualified Network.GRPC.LowLevel.Server.Unregistered as U
import Proto3.Suite.Class
dispatchLoop :: Server
-> (String -> IO ())
-> MetadataMap
-> [Handler 'Normal]
-> [Handler 'ClientStreaming]
-> [Handler 'ServerStreaming]
-> [Handler 'BiDiStreaming]
-> IO ()
dispatchLoop s logger md hN hC hS hB =
forever $ U.withServerCallAsync s $ \sc ->
case findHandler sc allHandlers of
Just (AnyHandler ah) -> case ah of
UnaryHandler _ h -> unaryHandler sc h
ClientStreamHandler _ h -> csHandler sc h
ServerStreamHandler _ h -> ssHandler sc h
BiDiStreamHandler _ h -> bdHandler sc h
Nothing -> unknownHandler sc
where
allHandlers = map AnyHandler hN ++ map AnyHandler hC
++ map AnyHandler hS ++ map AnyHandler hB
findHandler sc = find ((== U.callMethod sc) . anyHandlerMethodName)
unaryHandler :: (Message a, Message b) => U.ServerCall -> ServerHandler a b -> IO ()
unaryHandler sc h =
handleError $
U.serverHandleNormalCall' s sc md $ \_sc' bs ->
convertServerHandler h (const bs <$> U.convertCall sc)
csHandler :: (Message a, Message b) => U.ServerCall -> ServerReaderHandler a b -> IO ()
csHandler sc = handleError . U.serverReader s sc md . convertServerReaderHandler
ssHandler :: (Message a, Message b) => U.ServerCall -> ServerWriterHandler a b -> IO ()
ssHandler sc = handleError . U.serverWriter s sc md . convertServerWriterHandler
bdHandler :: (Message a, Message b) => U.ServerCall -> ServerRWHandler a b -> IO ()
bdHandler sc = handleError . U.serverRW s sc md . convertServerRWHandler
unknownHandler :: U.ServerCall -> IO ()
unknownHandler sc = void $ U.serverHandleNormalCall' s sc md $ \_ _ ->
return (mempty, mempty, StatusNotFound, StatusDetails "unknown method")
handleError :: IO a -> IO ()
handleError = (handleCallError logger . left herr =<<) . CE.try
where herr (e :: CE.SomeException) = GRPCIOHandlerException (show e)
serverLoop :: ServerOptions -> IO ()
serverLoop ServerOptions{..} =
In the library , " doc / core / epoll - polling - engine.md " seems
Note that " pthread_cond_timedwait " never returns ; see :
< >
Therefore to awaken " dispatchLoop " we must initiate a
shutdown ; it would not suffice to kill its thread .
( Presumably a shutdown broadcasts on relvant condition
The " withServer " cleanup code will initiate a shutdown .
in an interruptible sleep ( " takeMVar " ) while " dispatchLoop "
withGRPC $ \grpc ->
withServer grpc config $ \server -> do
Killing the " serverLoop " thread triggers the " withServer "
done <- newEmptyMVar
launched <- forkServer server $
dispatchLoop server
optLogger
optInitialMetadata
optNormalHandlers
optClientStreamHandlers
optServerStreamHandlers
optBiDiStreamHandlers
`CE.finally` putMVar done ()
when launched $
takeMVar done
where
config = ServerConfig
{ host = optServerHost
, port = optServerPort
, methodsToRegisterNormal = []
, methodsToRegisterClientStreaming = []
, methodsToRegisterServerStreaming = []
, methodsToRegisterBiDiStreaming = []
, serverArgs =
[CompressionAlgArg GrpcCompressDeflate | optUseCompression]
++
[ UserAgentPrefix optUserAgentPrefix
, UserAgentSuffix optUserAgentSuffix
]
++
foldMap (pure . MaxReceiveMessageLength) optMaxReceiveMessageLength
++
foldMap (pure . MaxMetadataSize) optMaxMetadataSize
, sslConfig = optSSLConfig
}
|
3c5678395375435ffcc18a4d4427e0e7844d872c719e1b38ac088d6e20fd5548 | finnishtransportagency/harja | paallystys_test.clj | (ns harja.palvelin.palvelut.yllapitokohteet.paallystys-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[namespacefy.core :refer [namespacefy]]
[harja.testi :refer :all]
[taoensso.timbre :as log]
[harja.palvelin.asetukset :as a]
[com.stuartsierra.component :as component]
[harja.kyselyt.konversio :as konv]
[cheshire.core :as cheshire]
[harja.integraatio :as integraatio]
[harja.domain.urakka :as urakka-domain]
[harja.domain.sopimus :as sopimus-domain]
[harja.domain.paallystysilmoitus :as paallystysilmoitus-domain]
[harja.domain.paallystyksen-maksuerat :as paallystyksen-maksuerat-domain]
[harja.domain.muokkaustiedot :as m]
[harja.domain.paallystys-ja-paikkaus :as paallystys-ja-paikkaus-domain]
[harja.domain.pot2 :as pot2-domain]
[harja.pvm :as pvm]
[harja.domain.skeema :as skeema]
[clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[harja.jms-test :refer [feikki-jms]]
[harja.palvelin.komponentit.fim :as fim]
[harja.palvelin.komponentit.fim-test :refer [+testi-fim+]]
[harja.palvelin.integraatiot.jms :as jms]
[harja.kyselyt.integraatiot :as integraatio-kyselyt]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.palvelut.yllapitokohteet.paallystys :as paallystys :refer :all]
[harja.palvelin.palvelut.yllapitokohteet.pot2 :as pot2]
[harja.palvelin.palvelut.yllapitokohteet-test :as yllapitokohteet-test]
[harja.palvelin.integraatiot.integraatioloki :as integraatioloki]
[harja.palvelin.integraatiot.vayla-rest.sahkoposti :as sahkoposti-api]
[harja.palvelin.integraatiot.integraatiopisteet.http :as integraatiopiste-http]
[harja.tyokalut.xml :as xml]
[harja.domain.paallystysilmoitus :as pot-domain])
(:import (java.util UUID))
(:use org.httpkit.fake))
(def ehdon-timeout 20000)
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:http-palvelin (testi-http-palvelin)
:fim (component/using
(fim/->FIM {:url +testi-fim+})
[:db :integraatioloki])
:integraatioloki (component/using
(integraatioloki/->Integraatioloki nil)
[:db])
:itmf (feikki-jms "itmf")
:api-sahkoposti (component/using
(sahkoposti-api/->ApiSahkoposti {:api-sahkoposti integraatio/api-sahkoposti-asetukset
:tloik {:toimenpidekuittausjono "Harja.HarjaToT-LOIK.Ack"}})
[:http-palvelin :db :integraatioloki :itmf])
:paallystys (component/using
(paallystys/->Paallystys)
[:http-palvelin :db :fim :api-sahkoposti])
:pot2 (component/using
(pot2/->POT2)
[:http-palvelin :db :fim :api-sahkoposti])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :each
urakkatieto-fixture
jarjestelma-fixture)
(def pot-testidata
{:versio 1
:perustiedot {:aloituspvm (pvm/luo-pvm 2019 9 1)
:valmispvm-kohde (pvm/luo-pvm 2019 9 2)
:valmispvm-paallystys (pvm/luo-pvm 2019 9 2)
:takuupvm (pvm/luo-pvm 2019 9 3)
:tr-osoite {:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 1
:tr-loppuosa 4
:tr-loppuetaisyys 5}
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 1
:tr-loppuosa 4
:tr-loppuetaisyys 5}
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}
Alikohteen tiedot
HUOMAA POISTETTU , EI SAA TALLENTUA !
:nimi "Tie 20"
:tr-numero 20
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Emt"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]
:alustatoimet [{:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:kasittelymenetelma 1
:paksuus 1234
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1
:tekninen-toimenpide 1}]}})
(def pot2-testidata
{:paallystyskohde-id 28,
:versio 2,
:lisatiedot "POT2 lisätieto"
:perustiedot {:tila nil,
:tr-kaista nil,
:kohdenimi "Aloittamaton kohde mt20",
:kohdenumero "L43",
:tr-ajorata nil,
:kommentit [],
:tr-loppuosa 3,
:valmispvm-kohde #inst "2021-06-20T21:00:00.000-00:00",
:tunnus nil,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:aloituspvm #inst "2021-06-18T21:00:00.000-00:00",
:takuupvm nil,
:tr-osoite {:tr-kaista nil,
:tr-ajorata nil,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:tr-alkuetaisyys 1,
:tr-numero 20},
:asiatarkastus {:lisatiedot nil,
:hyvaksytty nil,
:tarkastusaika nil,
:tarkastaja nil},
:tr-alkuetaisyys 1,
:tr-numero 20,
:tekninen-osa {:paatos nil,
:kasittelyaika nil,
:perustelu nil},
:valmispvm-paallystys nil},
:ilmoitustiedot nil,
:paallystekerros [{:kohdeosa-id 13,
:tr-kaista 11,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:nimi "Kohdeosa kaista 11",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 12,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}
{:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}]})
(defn- tallenna-pot2-testi-paallystysilmoitus
[urakka-id sopimus-id paallystyskohde-id paallystysilmoitus]
(let [paallystysilmoitus-kannassa-ennen (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))
_ (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi pot-domain/pot2-vuodesta-eteenpain
:paallystysilmoitus paallystysilmoitus}))
paallystysilmoitus-kannassa-jalkeen (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen]))
(deftest skeemavalidointi-toimii
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (not (nil? paallystyskohde-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc-in [:ilmoitustiedot :ylimaarainen-keyword]
"Huonoa dataa, jota ei saa päästää kantaan."))
maara-ennen-pyyntoa
(ffirst
(q
(str "SELECT count(*) FROM paallystysilmoitus"
" LEFT JOIN yllapitokohde ON yllapitokohde.id = paallystysilmoitus.paallystyskohde"
" AND urakka = " urakka-id
" AND sopimus = " sopimus-id ";")))]
(is (thrown? RuntimeException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})))
(let [maara-pyynnon-jalkeen
(ffirst
(q
(str "SELECT count(*) FROM paallystysilmoitus"
" LEFT JOIN yllapitokohde ON yllapitokohde.id = paallystysilmoitus.paallystyskohde"
" AND urakka = " urakka-id
" AND sopimus = " sopimus-id ";")))]
(is (= maara-ennen-pyyntoa maara-pyynnon-jalkeen))))))
(deftest skeemavalidointi-toimii-ilman-kaikkia-avaimia
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (not (nil? paallystyskohde-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc :ilmoitustiedot
Alikohteen tiedot
:nimi "Tie 666"
:tr-numero 666
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 1
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
on annettu , ( )
:pitoisuus 54
:lisaaineet "asd"}]
:alustatoimet [{:tr-numero 666
:tr-kaista 1
:tr-ajorata 1
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
Verkkoon liittyvät avaimet , arvoja ei siis annettu
}]}))]
(is (thrown? IllegalArgumentException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))))))
(deftest testidata-on-validia
On näkymää validoinnista läpi
(let [ilmoitustiedot (q "SELECT pi.ilmoitustiedot
FROM paallystysilmoitus pi
JOIN yllapitokohde yk ON yk.id = pi.paallystyskohde
WHERE yk.vuodet[1] >= 2019
AND pi.versio = 1")]
(doseq [[ilmoitusosa] ilmoitustiedot]
(is (skeema/validoi paallystysilmoitus-domain/+paallystysilmoitus-ilmoitustiedot+
(konv/jsonb->clojuremap ilmoitusosa))))))
(deftest hae-paallystysilmoitukset-1
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id})]
(is (= (count paallystysilmoitukset) 12) "Päällystysilmoituksia löytyi")))
(deftest hae-paallystysilmoitukset-2
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2015})]
(is (= (count paallystysilmoitukset) 0) "Päällystysilmoituksia ei löydy vuodelle 2015")))
(deftest hae-paallystysilmoitukset-3
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2017})]
(is (= (count paallystysilmoitukset) 5) "Päällystysilmoituksia löytyi vuodelle 2017")))
(deftest hae-paallystysilmoitukset-utajarvi-2021-pot2
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi paallystysilmoitus-domain/pot2-vuodesta-eteenpain})
tarkea-kohde (first (filter #(= (:nimi %) "Tärkeä kohde mt20") paallystysilmoitukset))]
(is (= 3 (count paallystysilmoitukset)) "Päällystysilmoituksia löytyi vuodelle 2021")
(is (= 2 (:versio tarkea-kohde)))
(is (= :aloitettu (:tila tarkea-kohde)) "Tila")
(is (= false (:lahetys-onnistunut tarkea-kohde)) "Lähetys")
(is (= "L42" (:kohdenumero tarkea-kohde)) "Kohdenumero")
(is (nil? (:paatos-tekninen-osa tarkea-kohde)) "Päätös")
(is (nil? (:ilmoitustiedot tarkea-kohde)))
(is (= {:numero 20, :alkuosa 1, :alkuetaisyys 1066, :loppuosa 1, :loppuetaisyys 3827}
(:yha-tr-osoite tarkea-kohde)))
(is (= 2 (count (:kohdeosat tarkea-kohde))) "Kohdeosien lkm")))
(deftest hae-yllapitokohteen-puuttuva-paallystysilmoitus
Testattavalla ylläpitokohteella ei ole päällystysilmoitusta ,
silti , jota käyttäjä voi täyttämään
;; (erityisesti kohdeosien esitäyttö on tärkeää)
Testataan , että tällainen " " on .
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystyskohde-id (hae-yllapitokohde-kuusamontien-testi-jolta-puuttuu-paallystysilmoitus)
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
(is (not (nil? paallystysilmoitus-kannassa)))
(is (nil? (:tila paallystysilmoitus-kannassa)) "Päällystysilmoituksen tila on tyhjä")
Puuttuvan päällystysilmoituksen
(is (= (count kohdeosat) 1))
(is (every? #(number? (:kohdeosa-id %)) kohdeosat))))
(deftest hae-yllapitokohteen-olemassa-oleva-paallystysilmoitus
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystyskohde-id (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
;; Päällystysilmoituksen perustiedot OK
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (:versio paallystysilmoitus-kannassa) 1))
(is (= (:tila paallystysilmoitus-kannassa) :aloitettu) "Päällystysilmoituksen tila on aloitttu")
(is (== (:maaramuutokset paallystysilmoitus-kannassa) 205))
(is (== (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 7043.95))
(is (= (:maaramuutokset-ennustettu? paallystysilmoitus-kannassa) true))
(is (= (:kohdenimi paallystysilmoitus-kannassa) "Leppäjärven ramppi"))
(is (= (:kohdenumero paallystysilmoitus-kannassa) "L03"))
Kohdeosat on OK
(is (= (count kohdeosat) 2))
(is (= (first (filter #(= (:nimi %) "Leppäjärven kohdeosa") kohdeosat))
Alikohteen tiedot
:kohdeosa-id 666
:nimi "Leppäjärven kohdeosa"
:tr-ajorata 1
:tr-alkuetaisyys 0
:tr-alkuosa 1
:tr-kaista 11
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20
:paallystetyyppi nil
:raekoko nil
:tyomenetelma nil
:massamaara nil
:toimenpide nil
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 2
:toimenpide-raekoko 1
:toimenpide-tyomenetelma 21
:kokonaismassamaara 12
:kuulamylly 2
:leveys 12
:massamenekki 1
:pinta-ala 12
:rc% 12
;; Kiviaines- ja sideainetiedot
:esiintyma "12"
:km-arvo "12"
:lisaaineet "12"
:muotoarvo "12"
:pitoisuus 12
:sideainetyyppi 2}))
(is (every? #(number? (:kohdeosa-id %)) kohdeosat))))
(deftest hae-yllapitokohteen-olemassa-oleva-pot2-paallystysilmoitus
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (:versio paallystysilmoitus-kannassa) 2))
(is (= {:numero 20, :alkuosa 1, :alkuetaisyys 1066, :loppuosa 1, :loppuetaisyys 3827}
(:yha-tr-osoite paallystysilmoitus-kannassa)))
(is (= 2 (count kohdeosat)))))
(defn- hae-yllapitokohdeosadata [yllapitokohde-id]
(set (q-map (str "SELECT nimi, paallystetyyppi, raekoko, tyomenetelma, massamaara, toimenpide
FROM yllapitokohdeosa WHERE NOT poistettu AND yllapitokohde = " yllapitokohde-id))))
(defn- tallenna-testipaallystysilmoitus
[paallystysilmoitus, vuosi]
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))
vastaus (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi vuosi
:paallystysilmoitus paallystysilmoitus}))
yllapitokohdeosadata (hae-yllapitokohdeosadata (:paallystyskohde-id paallystysilmoitus))]
[urakka-id sopimus-id vastaus yllapitokohdeosadata]))
(defn- tallenna-vaara-paallystysilmoitus
[paallystyskohde-id paallystysilmoiuts vuosi odotettu]
( log / debug " " paallystyskohde - id )
(is (some? paallystyskohde-id))
(let [paallystysilmoitus (-> paallystysilmoiuts
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
Toistaiseki tuetaan että map , vain että oikeanlainen expection heitetään
(if (map? odotettu)
(is (thrown? IllegalArgumentException
(tallenna-testipaallystysilmoitus paallystysilmoitus vuosi)))
(is (thrown-with-msg? IllegalArgumentException (re-pattern odotettu)
(tallenna-testipaallystysilmoitus paallystysilmoitus vuosi))))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= maara-ennen-lisaysta maara-lisayksen-jalkeen) "Ei saa olla mitään uutta kannassa"))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-uusi-paallystysilmoitus-kantaan
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")]
(is (some? paallystyskohde-id))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi ilmoitus")
(let [paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus paallystysilmoitus 2020)]
Vastauksena saadaan annetun vuoden . Poistetun .
(is (= (count (:yllapitokohteet vastaus)) 2))
(is (= (count (:paallystysilmoitukset vastaus)) 2))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(log/debug "Testitallennus valmis. POTTI kannassa: " (pr-str paallystysilmoitus-kannassa))
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(is (= (:tila paallystysilmoitus-kannassa) :valmis))
(is (= (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 4753.95M))
(is (= (update-in (:ilmoitustiedot paallystysilmoitus-kannassa) [:osoitteet 0] (fn [osoite]
(dissoc osoite :kohdeosa-id)))
{:alustatoimet [{:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuetaisyys 3
:tr-alkuosa 3
:tr-loppuetaisyys 5
:tr-loppuosa 3
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1}]
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]}))
(is (= yllapitokohdeosadata
#{{:nimi "Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"}} ))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-feilaa-validointi-alkuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
(assoc-in [:ilmoitustiedot :osoitteet 0 :tr-alkuosa] 2))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"Kaista 11 ajoradalla 1 ei kata koko osaa 3")))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-feilaa-validointi-loppuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
(assoc-in [:ilmoitustiedot :osoitteet 0 :tr-loppuetaisyys] 6000))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"(aet: 3, let: 6000)")))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-paallekkain
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
Alikohteen tiedot
:nimi "Tie 22 tosi pieni pätkä"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 4
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"Kohteenosa on päällekkäin osan")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-feilaa-validointi-alkuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 0 :tr-alkuosa] 2))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-feilaa-validointi-loppuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 0 :tr-loppuetaisyys] 6000))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-paallekkain
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 2] {:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000000,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest tallenna-pot2-paallystysilmoitus-jos-paallekkain-mutta-eri-jarjestysnro
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 2] {:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 2,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 500,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id))))
(deftest tallenna-pot2-paallystysilmoitus-jossa-alikohde-muulla-tiella
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
muu-tr-numero 5555
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 1 :tr-numero] muu-tr-numero))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id _ _] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä"))
(let [paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kulutuskerros (:paallystekerros paallystysilmoitus-kannassa)]
(is (= 2 (count kulutuskerros)))
(is (= #{20 muu-tr-numero} (set (map #(:tr-numero %) kulutuskerros)))))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest paivittaa-paallystysilmoitus-muokkaa-yllapitokohdeosaa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
_ (is (some? paallystyskohde-id))
alkuperainen-paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))]
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " alkuperäinen ilmoitus")
(let [[_ _ _ yllapitokohdeosadata] (tallenna-testipaallystysilmoitus alkuperainen-paallystysilmoitus 2020)
kohdeosa-id (:id yllapitokohdeosadata)]
(is (= yllapitokohdeosadata
#{{:nimi "Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"}}))
(let [uusi-paallystysilmoitus (-> alkuperainen-paallystysilmoitus
(assoc-in [:ilmoitustiedot :osoitteet 0 :nimi] "Uusi Tie 22")
(assoc-in [:ilmoitustiedot :osoitteet 0 :toimenpide] "Freude")
(assoc-in [:ilmoitustiedot :osoitteet 0 :kohdeosa-id] kohdeosa-id))
[_ _ vastaus paivitetty-yllapitokohdeosadata] (tallenna-testipaallystysilmoitus uusi-paallystysilmoitus 2020)]
(is (nil? (:virhe vastaus)))
(is (= paivitetty-yllapitokohdeosadata
#{{:nimi "Uusi Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Freude"}}))))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-uusi-pot2-paallystysilmoitus-kantaan
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")]
(is (some? paallystyskohde-id))
(is (= 28 paallystyskohde-id))
(u (str "UPDATE yllapitokohdeosa SET toimenpide = 'Wut' WHERE yllapitokohde = 28"))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi pot2 ilmoitus")
(let [paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
Vastauksena saadaan annetun vuoden . Poistetun .
(is (= 3 (count (:yllapitokohteet vastaus))) "Ylläpitokohteiden määrä vuonna 2021")
(is (= 3 (count (:paallystysilmoitukset vastaus))) "Ylläpitokohteiden määrä vuonna 2021")
(is (= #{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Wut"}
{:nimi "Kohdeosa kaista 11",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Wut"}}
yllapitokohdeosadata))
(let [[tallennettu-versio ilmoitustiedot] (first (q "SELECT versio, ilmoitustiedot FROM paallystysilmoitus
WHERE paallystyskohde = " paallystyskohde-id))]
(is (= tallennettu-versio 2))
(is (nil? ilmoitustiedot) "POT2:ssa kirjoittamme ne omille tauluille"))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(log/debug "Testitallennus valmis. POTTI kannassa: " (pr-str paallystysilmoitus-kannassa))
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(is (= (:tila paallystysilmoitus-kannassa) :valmis))
(is (= "POT2 lisätieto" (:lisatiedot paallystysilmoitus-kannassa)) "Tallenna lisätiedot")
(is (= (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 0M))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))))
(deftest paivittaa-pot2-paallystysilmoitus-ei-muoka-kaikki-yllapitokohdeosan-kentat
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")]
(is (= 28 paallystyskohde-id))
(u (str "UPDATE yllapitokohdeosa SET toimenpide = 'Freude' WHERE yllapitokohde = 28"))
(let [alkuperainen-paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
[_ _ _ yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
alkuperainen-paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(is (= yllapitokohdeosadata
#{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}
{:nimi "Kohdeosa kaista 11",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}}) "toimenpide jne ei ole päivetetty")
(let [uusi-paallystysilmoitus (-> alkuperainen-paallystysilmoitus
(assoc-in [:paallystekerros 0 :nimi] "Uusi uudistettu tie 22"))
[_ _ _ paivitetty-yllapitokohdeosadata] (tallenna-testipaallystysilmoitus uusi-paallystysilmoitus 2020)]
(is (= paivitetty-yllapitokohdeosadata
#{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}
{:nimi "Uusi uudistettu tie 22",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}}) "toimenpide jne ei ole päivetetty, mutta nimi on päivetetty")))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-paallystysilmoitus-ei-salli-null-materiaali-paallystyskerroksessa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true)
(update-in [:paallystekerros 0] dissoc :materiaali))]
(is (thrown-with-msg? IllegalArgumentException #"Materiaali on valinnainen vain jos toimenpide on KAR"
(tallenna-pot2-testi-paallystysilmoitus urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)))))
(deftest tallenna-pot2-paallystysilmoitus-salli-null-materiaali-vain-jos-on-kar-toimenpide
(let [kar-toimenpide pot2-domain/+kulutuskerros-toimenpide-karhinta+
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true)
(update-in [:paallystekerros 0] dissoc :materiaali)
(assoc-in [:paallystekerros 0 :toimenpide] kar-toimenpide))
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)]
(is (nil? (get-in paallystysilmoitus-kannassa-jalkeen [:paallystekerros 1 :materiaali])))
(is (= kar-toimenpide (get-in paallystysilmoitus-kannassa-jalkeen [:paallystekerros 1 :toimenpide])))))
(deftest tallenna-pot2-paallystysilmoitus-kohteen-alku-ja-loppupvm-muuttuvat
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :aloituspvm] #inst "2021-06-15T21:00:00.000-00:00")
(assoc-in [:perustiedot :valmispvm-kohde] #inst "2021-06-19T21:00:00.000-00:00"))
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)]
(is (= (:aloituspvm paallystysilmoitus-kannassa-ennen) #inst "2021-06-18T21:00:00.000-00:00") "Kohteen aloituspvm ennen muutosta")
(is (= (:aloituspvm paallystysilmoitus-kannassa-jalkeen) #inst "2021-06-15T21:00:00.000-00:00") "Kohteen aloituspvm muutoksen jälkeen")
(is (nil? (:valmispvm-kohde paallystysilmoitus-kannassa-ennen)) "Kohteen valmispvm-kohde ennen muutosta")
(is (= (:valmispvm-kohde paallystysilmoitus-kannassa-jalkeen) #inst "2021-06-19T21:00:00.000-00:00") "Kohteen valmispvm-kohde muutoksen jälkeen")))
(deftest tallenna-pot2-paallystysilmoitus-throwaa-jos-loppupvm-puuttuu
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :aloituspvm] #inst "2021-06-15T21:00:00.000-00:00")
(assoc-in [:perustiedot :valmispvm-kohde] nil))]
(is (thrown? IllegalArgumentException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2021
:paallystysilmoitus paallystysilmoitus})))))
(deftest ei-saa-paivittaa-jos-on-vaara-versio
(let [paallystyskohde-vanha-pot-id (ffirst (q "SELECT id FROM yllapitokohde WHERE nimi = 'Ouluntie'"))]
(is (not (nil? paallystyskohde-vanha-pot-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus-pot2 (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-vanha-pot-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))]
(is (thrown-with-msg? IllegalArgumentException #"Väärä POT versio. Pyynnössä on 2, pitäisi olla 1. Ota yhteyttä Harjan tukeen."
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi paallystysilmoitus-domain/pot2-vuodesta-eteenpain
:paallystysilmoitus paallystysilmoitus-pot2}))))))
(deftest ei-saa-paivittaa-jos-ei-ole-versiota
(let [paallystysilmoitus-pot2 (-> pot-testidata
(dissoc :versio)
(assoc :paallystyskohde-id 123))]
(is (thrown-with-msg? IllegalArgumentException #"Pyynnöstä puuttuu versio. Ota yhteyttä Harjan tukeen."
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id 1
:sopimus-id 1
:vuosi 2020
:paallystysilmoitus paallystysilmoitus-pot2})))))
(defn- alustarivi-idlla-loytyy?
"Palauttaa booleanin, löytyykö annetulla pot2a_id:llä riviä"
[alustarivit id]
(boolean (some? (first (filter #(= id (:pot2a_id %)) alustarivit)))))
(defn- alustarivi-idlla
"Palauttaa rivi, annetulla pot2a_id:llä"
[alustarivit id]
(first (filter #(= id (:pot2a_id %)) alustarivit)))
(def pot2-alustatestien-ilmoitus
{:perustiedot {:tila :aloitettu,
:tr-kaista nil,
:kohdenimi "Tärkeä kohde mt20",
:kohdenumero "L42",
:tr-ajorata nil,
:kommentit [],
:tr-loppuosa 1,
:valmispvm-kohde #inst "2021-06-23T21:00:00.000-00:00",
:tunnus nil,
:tr-alkuosa 1,
:versio 2,
:tr-loppuetaisyys 3827,
:aloituspvm #inst "2021-06-18T21:00:00.000-00:00",
:takuupvm #inst "2024-12-30T22:00:00.000-00:00",
:tr-osoite {:tr-kaista nil, :tr-ajorata nil, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 3827,
:tr-alkuetaisyys 1066, :tr-numero 20},
:asiatarkastus {:lisatiedot nil, :hyvaksytty nil, :tarkastusaika nil, :tarkastaja nil},
:tr-alkuetaisyys 1066, :tr-numero 20,
:tekninen-osa {:paatos nil, :kasittelyaika nil, :perustelu nil},
:valmispvm-paallystys #inst "2021-06-20T21:00:00.000-00:00"},
:paallystyskohde-id 27,
:versio 2,
:lisatiedot "POT2 alustatesti ilmoitus"
:ilmoitustiedot nil,
:paallystekerros [{:kohdeosa-id 11, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 1, :jarjestysnro 1,
:tr-alkuosa 1, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Tärkeä kohdeosa kaista 11",
:materiaali 1, :tr-alkuetaisyys 1066, :piennar true, :tr-numero 20, :toimenpide 22, :pot2p_id 1}
{:kohdeosa-id 12, :tr-kaista 12, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 1, :jarjestysnro 1,
:tr-alkuosa 1, :massamenekki 333, :tr-loppuetaisyys 3827, :nimi "Tärkeä kohdeosa kaista 12",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false, :tr-numero 20, :toimenpide 23, :pot2p_id 2}],
:alusta [{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500, :materiaali 1,
:tr-alkuetaisyys 1066, :tr-numero 20, :toimenpide 32, :pot2a_id 1,
:massa 1, :kokonaismassamaara 100, :massamaara 5}]})
(def pot2-alusta-esimerkki
[{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero 20, :toimenpide 32,
:massa 1, :massamaara 100}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys (inc 1066), :tr-numero 20, :toimenpide 32,
:massa 1, :massamaara 100}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys (- 2000 1),
:materiaali 1, :pituus 500,
:tr-alkuetaisyys 1500, :tr-numero 20, :toimenpide 11,
:kasittelysyvyys 55, :sideaine 1, :sideainepitoisuus 10.0M, :murske 1}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 2500,
:materiaali 1, :pituus 500,
:tr-alkuetaisyys 2000, :tr-numero 20, :toimenpide 3,
:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}])
(deftest tallenna-pot2-poista-alustarivi
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id pot2-alustatestien-ilmoitus)
alustarivit-ennen (:alusta paallystysilmoitus-kannassa-ennen)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)]
(is (not (nil? paallystysilmoitus-kannassa-ennen)))
(is (= (:versio paallystysilmoitus-kannassa-ennen) 2))
(is (= 6 (count alustarivit-ennen)))
(is (= 1 (count alustarivit-jalkeen)))
(is (alustarivi-idlla-loytyy? alustarivit-ennen 1) "alusta id:llä 1 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 2) "alusta id:llä 2 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 1) "alusta id:llä 1 löytyy")
(is (not (alustarivi-idlla-loytyy? alustarivit-jalkeen 2)) "alusta id:llä 2 ei saa löytyä")
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (assoc pot2-alustatestien-ilmoitus :alusta pot2-alusta-esimerkki)
Tehdään tallennus alustariviä
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-ennen (:alusta paallystysilmoitus-kannassa-ennen)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-6 (alustarivi-idlla alustarivit-jalkeen 11)]
(is (not (nil? paallystysilmoitus-kannassa-ennen)))
(is (= (:versio paallystysilmoitus-kannassa-ennen) 2))
(is (= 6 (count alustarivit-ennen)))
(is (= 4 (count alustarivit-jalkeen)))
(is (alustarivi-idlla-loytyy? alustarivit-ennen 1) "alusta id:llä 1 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 2) "alusta id:llä 2 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 3) "alusta id:llä 3 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 4) "alusta id:llä 4 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 5) "alusta id:llä 5 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 6) "alusta id:llä 6 löytyy")
(is (not (alustarivi-idlla-loytyy? alustarivit-jalkeen 7)) "alusta id:llä 7 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 8) "alusta id:llä 8 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 9) "alusta id:llä 9 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 10) "alusta id:llä 10 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 11) "alusta id:llä 10 löytyy")
(is (= {:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}
(select-keys alustarivi-6 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-vain-pakolliset-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] dissoc :verkon-tarkoitus))
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-10 (alustarivi-idlla alustarivit-jalkeen 11)]
(is (= {:verkon-tyyppi 1 :verkon-tarkoitus nil :verkon-sijainti 3}
(select-keys alustarivi-10 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-vain-pakolliset-tas-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 2] dissoc :murske :massamaara))
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-9 (alustarivi-idlla alustarivit-jalkeen 10)]
(is (= {:kasittelysyvyys 55, :sideaine 1, :sideainepitoisuus 10.0M, :murske nil, :massamaara nil}
(select-keys alustarivi-9 [:kasittelysyvyys :sideaine :sideainepitoisuus :murske :massamaara])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-jossa-on-alikohde-muulla-tiella-lisaa-alustarivi
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 7777
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc-in [:paallystekerros 2]
{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 10, :jarjestysnro 1,
:tr-alkuosa 10, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Muu tie",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23, :pot2p_id 3})
(assoc :alusta pot2-alusta-esimerkki)
(assoc-in [:alusta 4]
{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 10, :tr-alkuosa 10, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero muu-tr-numero, :toimenpide 32,
:kokonaismassamaara 100, :massa 1, :massamaara 20}))
Tehdään tallennus alustariviä
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)]
(is (= 5 (count alustarivit-jalkeen)))
(is (= #{{:pot2a_id 10
:tr-numero 20}
{:pot2a_id 11
:tr-numero 20}
{:pot2a_id 12
:tr-numero 7777}
{:pot2a_id 8
:tr-numero 20}
{:pot2a_id 9
:tr-numero 20}}
(clojure.set/project alustarivit-jalkeen [:pot2a_id :tr-numero])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
VHAR-5750
(deftest tallenna-pot2-jossa-on-alikohde-muulla-tiella-validointi-ottaa-tie-huomioon.
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 837
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(dissoc :alusta)
(dissoc :paallystekerros)
(assoc :paallystekerros
[{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 0, :pinta_ala 15000, :tr-loppuosa 2, :jarjestysnro 1,
:tr-alkuosa 2, :massamenekki 333, :tr-loppuetaisyys 1100, :nimi "Muu tie 1",
:materiaali 2, :tr-alkuetaisyys 1001, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23}
{:kohdeosa-id nil, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 0, :pinta_ala 15000, :tr-loppuosa 2, :jarjestysnro 1,
:tr-alkuosa 2, :massamenekki 333, :tr-loppuetaisyys 1110, :nimi "Muu tie 2",
:materiaali 2, :tr-alkuetaisyys 1100, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23}]))
Tehdään tallennus alustariviä
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
paallystekerrokset-jalkeen (:paallystekerros paallystysilmoitus-kannassa-jalkeen)]
#_(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivi-on-tiella-joka-ei-loydy-kulutuskerroksesta
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 7777
vaara-tr-numero 5555
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc-in [:paallystekerros 2]
{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 10, :jarjestysnro 1,
:tr-alkuosa 10, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Muu tie",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23, :pot2p_id 3})
(assoc :alusta pot2-alusta-esimerkki)
(assoc-in [:alusta 4]
{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 10, :tr-alkuosa 10, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero vaara-tr-numero, :toimenpide 32}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustatoimenpiteen täytyy olla samalla tiellä kuin jokin alikohteista. Tienumero 5555 ei ole.")))
(deftest tallenna-pot2-paivittaa-alustarivi-jossa-on-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
alkuperaiset-verkon-tiedot {:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge alkuperaiset-verkon-tiedot))
[_ paallystysilmoitus-kannassa-uusi] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-uudet (:alusta paallystysilmoitus-kannassa-uusi)
paivitetyt-verkon-tiedot {:verkon-tyyppi 9 :verkon-tarkoitus 1 :verkon-sijainti 2}
paivitetty-paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta alustarivit-uudet)
(update-in [:alusta 3] merge paivitetyt-verkon-tiedot))
[_ paallystysilmoitus-kannassa-paivitetty] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paivitetty-paallystysilmoitus)
alustarivit-paivitetyt (:alusta paallystysilmoitus-kannassa-paivitetty)
paivitetty-alustarivi-11 (alustarivi-idlla alustarivit-paivitetyt 11)]
(is (some? paivitetty-alustarivi-11) "alusta id:llä 10 löytyy")
(is (= paivitetyt-verkon-tiedot (select-keys paivitetty-alustarivi-11 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-ei-ole-kaikki-pakolliset-verkontiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] dissoc :verkon-sijainti))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustassa väärät lisätiedot.")))
(deftest ei-saa-tallenna-pot2-jos-sama-tr-osoite-samalla-alustatoimenpiteella
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 1] merge {:tr-kaista 11}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Kohteenosa on päällekkäin toisen osan kanssa.")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-on-vaarat-lisatiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
verkon-tiedot {:verkon-tyyppi 1 :verkon-sijainti 3 :verkon-tarkoitus 1 :massamaara 1}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge verkon-tiedot))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustassa väärät lisätiedot.")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-on-vaarat-verkontiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
verkon-tiedot {:verkon-tyyppi 1 :verkon-tarkoitus 333 :verkon-sijainti 3}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge verkon-tiedot))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
{"alustatoimenpide""ERROR: insert or update on table \"pot2_alusta\" violates foreign key constraint \"pot2_alusta_verkon_tarkoitus_fkey\"\n Detail: Key (verkon_tarkoitus)=(333) is not present in table \"pot2_verkon_tarkoitus\"."}
)))
(deftest uuden-paallystysilmoituksen-tallennus-eri-urakkaan-ei-onnistu
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-ei-ole-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi ilmoitus")
(let [urakka-id (hae-oulun-alueurakan-2014-2019-id)
sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id)
paallystysilmoitus (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)]
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))))))
(deftest paivita-paallystysilmoitukselle-paatostiedot
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu] "Hyvä ilmoitus!"))
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))]
(with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))
(let [paallystysilmoitus-kannassa
(kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(is (some? paallystysilmoitus-kannassa))
(is (= (:tila paallystysilmoitus-kannassa) :lukittu))
(is (= (get-in paallystysilmoitus-kannassa [:tekninen-osa :paatos]) :hyvaksytty))
(is (= (get-in paallystysilmoitus-kannassa [:tekninen-osa :perustelu])
(get-in paallystysilmoitus [:perustiedot :tekninen-osa :perustelu])))
Tie 22 tiedot tallentuivat kantaan , 20 ei koska
(is (some #(= (:nimi %) "Tie 22")
(get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])))
(is (not (some #(= (:nimi %) "Tie 20")
(get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet]))))
(is (= (update-in (:ilmoitustiedot paallystysilmoitus-kannassa) [:osoitteet 0] (fn [osoite]
(dissoc osoite :kohdeosa-id)))
{:alustatoimet [{:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuetaisyys 3
:tr-alkuosa 3
:tr-loppuetaisyys 5
:tr-loppuosa 3
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1}]
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]}))
, ei voi enää päivittää
(log/debug "Tarkistetaan, ettei voi muokata lukittua ilmoitusta.")
(is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})))
(u (str "UPDATE paallystysilmoitus SET
tila = NULL,
paatos_tekninen_osa = NULL,
perustelu_tekninen_osa = NULL
WHERE paallystyskohde =" paallystyskohde-id ";"))))))
(deftest lisaa-kohdeosa
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-ei-ole-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
hae-kohteiden-maara #(count (q (str "SELECT * FROM yllapitokohdeosa"
" WHERE poistettu IS NOT TRUE "
" AND yllapitokohde = " paallystyskohde-id ";")))]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})
(let [kohteita-ennen-lisaysta (hae-kohteiden-maara)
paallystysilmoitus (update-in paallystysilmoitus [:ilmoitustiedot :osoitteet]
Alikohteen tiedot
:nimi "Tie 123"
:tr-numero 666
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 1
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
;; Päällystetoimenpiteen tiedot
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
;; Kiviaines- ja sideainetiedot
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"})]
(is (= 1 kohteita-ennen-lisaysta))
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})
(is (= (inc kohteita-ennen-lisaysta) (hae-kohteiden-maara)) "Kohteita on nyt 1 enemmän")))))
(deftest ala-paivita-paallystysilmoitukselle-paatostiedot-jos-ei-oikeuksia
(let [paallystyskohde-id (hae-muhoksen-yllapitokohde-ilman-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu]
"Yritän saada ilmoituksen hyväksytyksi ilman oikeuksia."))]
(is (thrown? RuntimeException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-tero+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))))))
(deftest yllapitokohteiden-maksuerien-haku-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:hae-paallystyksen-maksuerat
+kayttaja-jvh+
{::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017})
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (== (:kokonaishinta leppajarven-ramppi) 7248.95))
(is (= (count (:maksuerat leppajarven-ramppi)) 2))))
(deftest yllapitokohteen-uusien-maksuerien-tallennus-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
leppajarven-ramppi (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)
testidata (gen/sample (s/gen ::paallystyksen-maksuerat-domain/tallennettava-yllapitokohde-maksuerineen))]
(doseq [yllapitokohde testidata]
(u "DELETE FROM yllapitokohteen_maksuera WHERE yllapitokohde = " leppajarven-ramppi ";")
(u "DELETE FROM yllapitokohteen_maksueratunnus WHERE yllapitokohde = " leppajarven-ramppi ";")
(let [maksuerat (:maksuerat yllapitokohde)
maksueranumerot (map :maksueranumero maksuerat)
, tallentaa vain viimeisimmän .
Otetaan viimeiset , että tallennus menee oikein
tallennettavat-maksuerat (if (empty? maksueranumerot)
[]
(keep (fn [maksueranumero]
(-> (filter #(= (:maksueranumero %) maksueranumero) maksuerat)
last
(dissoc :id)))
(range (apply min maksueranumerot)
(inc (apply max maksueranumerot)))))
payload {::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017
:yllapitokohteet [(assoc yllapitokohde :id leppajarven-ramppi)]}
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystyksen-maksuerat
+kayttaja-jvh+
payload)
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (= (map #(dissoc % :id) (:maksuerat leppajarven-ramppi))
tallennettavat-maksuerat))))))
(deftest yllapitokohteen-maksuerien-paivitys-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
leppajarven-ramppi (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)]
(let [tallennettavat-maksuerat [{:maksueranumero 1 :sisalto "Päivitetäänpäs tämä"}
{:maksueranumero 4 :sisalto nil}
{:maksueranumero 5 :sisalto "Uusi maksuerä"}]
payload {::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017
:yllapitokohteet [{:id leppajarven-ramppi
:maksuerat tallennettavat-maksuerat
:maksueratunnus "Uusi maksuerätunnus"}]}
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystyksen-maksuerat
+kayttaja-jvh+
payload)
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (= (:maksueratunnus leppajarven-ramppi) "Uusi maksuerätunnus"))
(is (= (:maksuerat leppajarven-ramppi)
[{:id 1
:maksueranumero 1
:sisalto "Päivitetäänpäs tämä"}
{:id 2
:maksueranumero 2
:sisalto "Puolet"}
{:id 6
:maksueranumero 4
:sisalto nil}
{:id 7
:maksueranumero 5
:sisalto "Uusi maksuerä"}])
"Uudet maksuerät ilmestyivät kantaan, vanhat päivitettiin ja payloadissa olemattomiin ei koskettu"))))
(deftest avaa-lukitun-potin-lukitus
(let [kohde-id (hae-yllapitokohteen-id-nimella "Oulun ohitusramppi")
payload {::urakka-domain/id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
::paallystysilmoitus-domain/paallystyskohde-id kohde-id
::paallystysilmoitus-domain/tila :valmis}
tila-ennen-kutsua (keyword (second (first (q (str "SELECT id, tila FROM paallystysilmoitus WHERE paallystyskohde = " kohde-id)))))
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila +kayttaja-jvh+ payload)]
(is (= :lukittu tila-ennen-kutsua))
(is (= :valmis (:tila vastaus)))))
(deftest avaa-lukitun-potin-lukitus-ei-sallittu-koska-tero-ei-tassa-urakanvalvojana
(let [kohde-id (hae-yllapitokohteen-id-nimella "Oulun ohitusramppi")
payload {::urakka-domain/id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
::paallystysilmoitus-domain/paallystyskohde-id kohde-id
::paallystysilmoitus-domain/tila :valmis}]
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila
+kayttaja-tero+
payload)))
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila
+kayttaja-vastuuhlo-muhos+
payload)))))
(deftest sahkopostien-lahetys
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (:paallystyskohde (first (q-map (str "SELECT paallystyskohde "
"FROM paallystysilmoitus pi "
"JOIN yllapitokohde yk ON yk.id=pi.paallystyskohde "
"WHERE (pi.paatos_tekninen_osa IS NULL OR "
"pi.paatos_tekninen_osa='hylatty'::paallystysilmoituksen_paatostyyppi) AND "
"pi.tila!='valmis'::paallystystila AND "
"yk.urakka=" urakka-id " "
"LIMIT 1"))))
Tehdään ensin sellainen päällystysilmoitus , on
ja lähetetään
paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-muhoksen-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))]
(with-fake-http
[{:url +testi-fim+ :method :get} fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(let [vastaus (future (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))
_ (odota-ehdon-tayttymista #(realized? vastaus) "Saatiin vastaus :tallenna-paallystysilmoitus" ehdon-timeout)
_ (Thread/sleep 1000)
integraatioviestit (q-map (str "select id, integraatiotapahtuma, suunta, sisaltotyyppi, siirtotyyppi, sisalto, otsikko, parametrit, osoite, kasitteleva_palvelin
FROM integraatioviesti;"))
integraatiotapahtumat (q-map (str "select id, integraatio, alkanut, paattynyt, lisatietoja, onnistunut, ulkoinenid FROM integraatiotapahtuma"))
Hyväksytään ilmoitus valvojalle
paallystysilmoitus (-> (assoc pot-testidata
:paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu] "Hyvä ilmoitus!"))]
Ensimmäinen integraatioviesti sisältää tiedot haetuista FIM käyttäjistä , olla sähköposti , lähetettiin
(is (clojure.string/includes? (:sisalto (second integraatioviestit)) ""))
(is (= (integraatio-kyselyt/integraation-id (:db jarjestelma) "fim" "hae-urakan-kayttajat") (:integraatio (first integraatiotapahtumat))))
(is (= (integraatio-kyselyt/integraation-id (:db jarjestelma) "api" "sahkoposti-lahetys") (:integraatio (second integraatiotapahtumat))))))
#_ (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus (str (UUID/randomUUID)))]
(let [_ (println "************************************************** uusi tallennnus ********************************' ")
vastaus (future (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))
_ (odota-ehdon-tayttymista #(realized? vastaus) "Saatiin vastaus :tallenna-paallystysilmoitus" ehdon-timeout)
integraatioviestit (q-map (str "select id, integraatiotapahtuma, suunta, sisaltotyyppi, siirtotyyppi, sisalto, otsikko, parametrit, osoite, kasitteleva_palvelin
FROM integraatioviesti;"))
_ (println "***************************** integraatioviestit" (pr-str integraatioviestit))
integraatiotapahtumat (q-map (str "select id, integraatio, alkanut, paattynyt, lisatietoja, onnistunut, ulkoinenid FROM integraatiotapahtuma"))]
Viides integraatioviesti sisältää tiedot haetuista FIM käyttäjistä , olla sähköposti , lähetettiin
(is (clojure.string/includes? (:sisalto (nth integraatioviestit 5)) ""))))))
(deftest lisaa-paallystysilmoitukseen-kohdeosien-id
(let [paallystysilmoitus {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1
:nimi "1 A"
:toimenpide-paallystetyyppi 1
:tr-ajorata 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 2
:nimi "1 B"
:toimenpide-paallystetyyppi 1
:tr-ajorata 1
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}
{:kohdeosa-id 3
:nimi "2 A"
:toimenpide-paallystetyyppi 1
:tr-ajorata 2
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 4
:nimi "2 B"
:toimenpide-paallystetyyppi 1
:tr-ajorata 2
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]}}
kohdeosat [{:id 1
:nimi "1 A"
:tr-ajorata 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 2
:nimi "1 B"
:tr-ajorata 1
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}
{:id 3
:nimi "2 A"
:tr-ajorata 2
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 4
:nimi "2 B"
:tr-ajorata 2
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]]
(is (= {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1, :nimi "1 A",
:toimenpide-paallystetyyppi 1, :tr-ajorata 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1, :tr-kaista 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}
{:kohdeosa-id 2, :nimi "1 B",
:toimenpide-paallystetyyppi 1, :tr-ajorata 1,
:tr-alkuetaisyys 1500, :tr-alkuosa 1,
:tr-kaista 1, :tr-loppuetaisyys 0,
:tr-loppuosa 3, :tr-numero 20}
{:kohdeosa-id 3, :nimi "2 A",
:toimenpide-paallystetyyppi 1, :tr-ajorata 2,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-kaista 21, :tr-loppuetaisyys 1000,
:tr-loppuosa 1, :tr-numero 20}
{:kohdeosa-id 4, :nimi "2 B",
:toimenpide-paallystetyyppi 1, :tr-ajorata 2,
:tr-alkuetaisyys 1500, :tr-alkuosa 1,
:tr-kaista 21, :tr-loppuetaisyys 0,
:tr-loppuosa 3,
:tr-numero 20}]}}
(paallystys/lisaa-paallystysilmoitukseen-kohdeosien-idt paallystysilmoitus kohdeosat))
"Kohdeosille on lisätty id:t oikein, kun ajorata ja kaista ovat paikoillaan"))
(let [paallystysilmoitus {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1
:nimi "1"
:toimenpide-paallystetyyppi 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 3
:nimi "2"
:toimenpide-paallystetyyppi 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}]}}
kohdeosat [{:id 1
:nimi "1"
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 2
:nimi "2"
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]]
(is (= {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1, :nimi "1",
:toimenpide-paallystetyyppi 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}
{:kohdeosa-id 1, :nimi "2",
:toimenpide-paallystetyyppi 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}]}}
(paallystys/lisaa-paallystysilmoitukseen-kohdeosien-idt paallystysilmoitus kohdeosat))
"Kohdeosille on lisätty id:t oikein, kun ajorataa ja kaistaa ei ole")))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/af09d60911ed31ea98634a9d5c7f4b062e63504f/test/clj/harja/palvelin/palvelut/yllapitokohteet/paallystys_test.clj | clojure | Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
(erityisesti kohdeosien esitäyttö on tärkeää)
Päällystysilmoituksen perustiedot OK
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
"))))))
Päällystetoimenpiteen tiedot
Kiviaines- ja sideainetiedot
"))
")) | (ns harja.palvelin.palvelut.yllapitokohteet.paallystys-test
(:require [clojure.java.io :as io]
[clojure.test :refer :all]
[namespacefy.core :refer [namespacefy]]
[harja.testi :refer :all]
[taoensso.timbre :as log]
[harja.palvelin.asetukset :as a]
[com.stuartsierra.component :as component]
[harja.kyselyt.konversio :as konv]
[cheshire.core :as cheshire]
[harja.integraatio :as integraatio]
[harja.domain.urakka :as urakka-domain]
[harja.domain.sopimus :as sopimus-domain]
[harja.domain.paallystysilmoitus :as paallystysilmoitus-domain]
[harja.domain.paallystyksen-maksuerat :as paallystyksen-maksuerat-domain]
[harja.domain.muokkaustiedot :as m]
[harja.domain.paallystys-ja-paikkaus :as paallystys-ja-paikkaus-domain]
[harja.domain.pot2 :as pot2-domain]
[harja.pvm :as pvm]
[harja.domain.skeema :as skeema]
[clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as gen]
[harja.jms-test :refer [feikki-jms]]
[harja.palvelin.komponentit.fim :as fim]
[harja.palvelin.komponentit.fim-test :refer [+testi-fim+]]
[harja.palvelin.integraatiot.jms :as jms]
[harja.kyselyt.integraatiot :as integraatio-kyselyt]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.palvelut.yllapitokohteet.paallystys :as paallystys :refer :all]
[harja.palvelin.palvelut.yllapitokohteet.pot2 :as pot2]
[harja.palvelin.palvelut.yllapitokohteet-test :as yllapitokohteet-test]
[harja.palvelin.integraatiot.integraatioloki :as integraatioloki]
[harja.palvelin.integraatiot.vayla-rest.sahkoposti :as sahkoposti-api]
[harja.palvelin.integraatiot.integraatiopisteet.http :as integraatiopiste-http]
[harja.tyokalut.xml :as xml]
[harja.domain.paallystysilmoitus :as pot-domain])
(:import (java.util UUID))
(:use org.httpkit.fake))
(def ehdon-timeout 20000)
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:http-palvelin (testi-http-palvelin)
:fim (component/using
(fim/->FIM {:url +testi-fim+})
[:db :integraatioloki])
:integraatioloki (component/using
(integraatioloki/->Integraatioloki nil)
[:db])
:itmf (feikki-jms "itmf")
:api-sahkoposti (component/using
(sahkoposti-api/->ApiSahkoposti {:api-sahkoposti integraatio/api-sahkoposti-asetukset
:tloik {:toimenpidekuittausjono "Harja.HarjaToT-LOIK.Ack"}})
[:http-palvelin :db :integraatioloki :itmf])
:paallystys (component/using
(paallystys/->Paallystys)
[:http-palvelin :db :fim :api-sahkoposti])
:pot2 (component/using
(pot2/->POT2)
[:http-palvelin :db :fim :api-sahkoposti])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :each
urakkatieto-fixture
jarjestelma-fixture)
(def pot-testidata
{:versio 1
:perustiedot {:aloituspvm (pvm/luo-pvm 2019 9 1)
:valmispvm-kohde (pvm/luo-pvm 2019 9 2)
:valmispvm-paallystys (pvm/luo-pvm 2019 9 2)
:takuupvm (pvm/luo-pvm 2019 9 3)
:tr-osoite {:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 1
:tr-loppuosa 4
:tr-loppuetaisyys 5}
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 1
:tr-loppuosa 4
:tr-loppuetaisyys 5}
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}
Alikohteen tiedot
HUOMAA POISTETTU , EI SAA TALLENTUA !
:nimi "Tie 20"
:tr-numero 20
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Emt"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]
:alustatoimet [{:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:kasittelymenetelma 1
:paksuus 1234
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1
:tekninen-toimenpide 1}]}})
(def pot2-testidata
{:paallystyskohde-id 28,
:versio 2,
:lisatiedot "POT2 lisätieto"
:perustiedot {:tila nil,
:tr-kaista nil,
:kohdenimi "Aloittamaton kohde mt20",
:kohdenumero "L43",
:tr-ajorata nil,
:kommentit [],
:tr-loppuosa 3,
:valmispvm-kohde #inst "2021-06-20T21:00:00.000-00:00",
:tunnus nil,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:aloituspvm #inst "2021-06-18T21:00:00.000-00:00",
:takuupvm nil,
:tr-osoite {:tr-kaista nil,
:tr-ajorata nil,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:tr-alkuetaisyys 1,
:tr-numero 20},
:asiatarkastus {:lisatiedot nil,
:hyvaksytty nil,
:tarkastusaika nil,
:tarkastaja nil},
:tr-alkuetaisyys 1,
:tr-numero 20,
:tekninen-osa {:paatos nil,
:kasittelyaika nil,
:perustelu nil},
:valmispvm-paallystys nil},
:ilmoitustiedot nil,
:paallystekerros [{:kohdeosa-id 13,
:tr-kaista 11,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:nimi "Kohdeosa kaista 11",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 12,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}
{:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}]})
(defn- tallenna-pot2-testi-paallystysilmoitus
[urakka-id sopimus-id paallystyskohde-id paallystysilmoitus]
(let [paallystysilmoitus-kannassa-ennen (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))
_ (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi pot-domain/pot2-vuodesta-eteenpain
:paallystysilmoitus paallystysilmoitus}))
paallystysilmoitus-kannassa-jalkeen (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen]))
(deftest skeemavalidointi-toimii
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (not (nil? paallystyskohde-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc-in [:ilmoitustiedot :ylimaarainen-keyword]
"Huonoa dataa, jota ei saa päästää kantaan."))
maara-ennen-pyyntoa
(ffirst
(q
(str "SELECT count(*) FROM paallystysilmoitus"
" LEFT JOIN yllapitokohde ON yllapitokohde.id = paallystysilmoitus.paallystyskohde"
" AND urakka = " urakka-id
" AND sopimus = " sopimus-id ";")))]
(is (thrown? RuntimeException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})))
(let [maara-pyynnon-jalkeen
(ffirst
(q
(str "SELECT count(*) FROM paallystysilmoitus"
" LEFT JOIN yllapitokohde ON yllapitokohde.id = paallystysilmoitus.paallystyskohde"
" AND urakka = " urakka-id
" AND sopimus = " sopimus-id ";")))]
(is (= maara-ennen-pyyntoa maara-pyynnon-jalkeen))))))
(deftest skeemavalidointi-toimii-ilman-kaikkia-avaimia
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (not (nil? paallystyskohde-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc :ilmoitustiedot
Alikohteen tiedot
:nimi "Tie 666"
:tr-numero 666
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 1
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
on annettu , ( )
:pitoisuus 54
:lisaaineet "asd"}]
:alustatoimet [{:tr-numero 666
:tr-kaista 1
:tr-ajorata 1
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
Verkkoon liittyvät avaimet , arvoja ei siis annettu
}]}))]
(is (thrown? IllegalArgumentException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))))))
(deftest testidata-on-validia
On näkymää validoinnista läpi
(let [ilmoitustiedot (q "SELECT pi.ilmoitustiedot
FROM paallystysilmoitus pi
JOIN yllapitokohde yk ON yk.id = pi.paallystyskohde
WHERE yk.vuodet[1] >= 2019
AND pi.versio = 1")]
(doseq [[ilmoitusosa] ilmoitustiedot]
(is (skeema/validoi paallystysilmoitus-domain/+paallystysilmoitus-ilmoitustiedot+
(konv/jsonb->clojuremap ilmoitusosa))))))
(deftest hae-paallystysilmoitukset-1
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id})]
(is (= (count paallystysilmoitukset) 12) "Päällystysilmoituksia löytyi")))
(deftest hae-paallystysilmoitukset-2
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2015})]
(is (= (count paallystysilmoitukset) 0) "Päällystysilmoituksia ei löydy vuodelle 2015")))
(deftest hae-paallystysilmoitukset-3
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2017})]
(is (= (count paallystysilmoitukset) 5) "Päällystysilmoituksia löytyi vuodelle 2017")))
(deftest hae-paallystysilmoitukset-utajarvi-2021-pot2
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitukset (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitukset +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi paallystysilmoitus-domain/pot2-vuodesta-eteenpain})
tarkea-kohde (first (filter #(= (:nimi %) "Tärkeä kohde mt20") paallystysilmoitukset))]
(is (= 3 (count paallystysilmoitukset)) "Päällystysilmoituksia löytyi vuodelle 2021")
(is (= 2 (:versio tarkea-kohde)))
(is (= :aloitettu (:tila tarkea-kohde)) "Tila")
(is (= false (:lahetys-onnistunut tarkea-kohde)) "Lähetys")
(is (= "L42" (:kohdenumero tarkea-kohde)) "Kohdenumero")
(is (nil? (:paatos-tekninen-osa tarkea-kohde)) "Päätös")
(is (nil? (:ilmoitustiedot tarkea-kohde)))
(is (= {:numero 20, :alkuosa 1, :alkuetaisyys 1066, :loppuosa 1, :loppuetaisyys 3827}
(:yha-tr-osoite tarkea-kohde)))
(is (= 2 (count (:kohdeosat tarkea-kohde))) "Kohdeosien lkm")))
(deftest hae-yllapitokohteen-puuttuva-paallystysilmoitus
Testattavalla ylläpitokohteella ei ole päällystysilmoitusta ,
silti , jota käyttäjä voi täyttämään
Testataan , että tällainen " " on .
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystyskohde-id (hae-yllapitokohde-kuusamontien-testi-jolta-puuttuu-paallystysilmoitus)
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
(is (not (nil? paallystysilmoitus-kannassa)))
(is (nil? (:tila paallystysilmoitus-kannassa)) "Päällystysilmoituksen tila on tyhjä")
Puuttuvan päällystysilmoituksen
(is (= (count kohdeosat) 1))
(is (every? #(number? (:kohdeosa-id %)) kohdeosat))))
(deftest hae-yllapitokohteen-olemassa-oleva-paallystysilmoitus
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystyskohde-id (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (:versio paallystysilmoitus-kannassa) 1))
(is (= (:tila paallystysilmoitus-kannassa) :aloitettu) "Päällystysilmoituksen tila on aloitttu")
(is (== (:maaramuutokset paallystysilmoitus-kannassa) 205))
(is (== (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 7043.95))
(is (= (:maaramuutokset-ennustettu? paallystysilmoitus-kannassa) true))
(is (= (:kohdenimi paallystysilmoitus-kannassa) "Leppäjärven ramppi"))
(is (= (:kohdenumero paallystysilmoitus-kannassa) "L03"))
Kohdeosat on OK
(is (= (count kohdeosat) 2))
(is (= (first (filter #(= (:nimi %) "Leppäjärven kohdeosa") kohdeosat))
Alikohteen tiedot
:kohdeosa-id 666
:nimi "Leppäjärven kohdeosa"
:tr-ajorata 1
:tr-alkuetaisyys 0
:tr-alkuosa 1
:tr-kaista 11
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20
:paallystetyyppi nil
:raekoko nil
:tyomenetelma nil
:massamaara nil
:toimenpide nil
:toimenpide-paallystetyyppi 2
:toimenpide-raekoko 1
:toimenpide-tyomenetelma 21
:kokonaismassamaara 12
:kuulamylly 2
:leveys 12
:massamenekki 1
:pinta-ala 12
:rc% 12
:esiintyma "12"
:km-arvo "12"
:lisaaineet "12"
:muotoarvo "12"
:pitoisuus 12
:sideainetyyppi 2}))
(is (every? #(number? (:kohdeosa-id %)) kohdeosat))))
(deftest hae-yllapitokohteen-olemassa-oleva-pot2-paallystysilmoitus
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kohdeosat (get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])]
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (:versio paallystysilmoitus-kannassa) 2))
(is (= {:numero 20, :alkuosa 1, :alkuetaisyys 1066, :loppuosa 1, :loppuetaisyys 3827}
(:yha-tr-osoite paallystysilmoitus-kannassa)))
(is (= 2 (count kohdeosat)))))
(defn- hae-yllapitokohdeosadata [yllapitokohde-id]
(set (q-map (str "SELECT nimi, paallystetyyppi, raekoko, tyomenetelma, massamaara, toimenpide
FROM yllapitokohdeosa WHERE NOT poistettu AND yllapitokohde = " yllapitokohde-id))))
(defn- tallenna-testipaallystysilmoitus
[paallystysilmoitus, vuosi]
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))
vastaus (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi vuosi
:paallystysilmoitus paallystysilmoitus}))
yllapitokohdeosadata (hae-yllapitokohdeosadata (:paallystyskohde-id paallystysilmoitus))]
[urakka-id sopimus-id vastaus yllapitokohdeosadata]))
(defn- tallenna-vaara-paallystysilmoitus
[paallystyskohde-id paallystysilmoiuts vuosi odotettu]
( log / debug " " paallystyskohde - id )
(is (some? paallystyskohde-id))
(let [paallystysilmoitus (-> paallystysilmoiuts
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
Toistaiseki tuetaan että map , vain että oikeanlainen expection heitetään
(if (map? odotettu)
(is (thrown? IllegalArgumentException
(tallenna-testipaallystysilmoitus paallystysilmoitus vuosi)))
(is (thrown-with-msg? IllegalArgumentException (re-pattern odotettu)
(tallenna-testipaallystysilmoitus paallystysilmoitus vuosi))))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= maara-ennen-lisaysta maara-lisayksen-jalkeen) "Ei saa olla mitään uutta kannassa"))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-uusi-paallystysilmoitus-kantaan
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")]
(is (some? paallystyskohde-id))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi ilmoitus")
(let [paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus paallystysilmoitus 2020)]
Vastauksena saadaan annetun vuoden . Poistetun .
(is (= (count (:yllapitokohteet vastaus)) 2))
(is (= (count (:paallystysilmoitukset vastaus)) 2))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(log/debug "Testitallennus valmis. POTTI kannassa: " (pr-str paallystysilmoitus-kannassa))
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(is (= (:tila paallystysilmoitus-kannassa) :valmis))
(is (= (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 4753.95M))
(is (= (update-in (:ilmoitustiedot paallystysilmoitus-kannassa) [:osoitteet 0] (fn [osoite]
(dissoc osoite :kohdeosa-id)))
{:alustatoimet [{:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuetaisyys 3
:tr-alkuosa 3
:tr-loppuetaisyys 5
:tr-loppuosa 3
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1}]
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]}))
(is (= yllapitokohdeosadata
#{{:nimi "Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"}} ))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-feilaa-validointi-alkuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
(assoc-in [:ilmoitustiedot :osoitteet 0 :tr-alkuosa] 2))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"Kaista 11 ajoradalla 1 ei kata koko osaa 3")))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-feilaa-validointi-loppuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
(assoc-in [:ilmoitustiedot :osoitteet 0 :tr-loppuetaisyys] 6000))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"(aet: 3, let: 6000)")))
(deftest ei-saa-tallenna-paallystysilmoitus-jos-paallekkain
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
paallystysilmoitus (-> pot-testidata
Alikohteen tiedot
:nimi "Tie 22 tosi pieni pätkä"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 4
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2020
"Kohteenosa on päällekkäin osan")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-feilaa-validointi-alkuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 0 :tr-alkuosa] 2))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-feilaa-validointi-loppuosa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 0 :tr-loppuetaisyys] 6000))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-paallekkain
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 2] {:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 1,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 5000000,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alikohde ei voi olla pääkohteen ulkopuolella")))
(deftest tallenna-pot2-paallystysilmoitus-jos-paallekkain-mutta-eri-jarjestysnro
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 2] {:kohdeosa-id 14,
:tr-kaista 12,
:tr-ajorata 1,
:jarjestysnro 2,
:tr-loppuosa 3,
:tr-alkuosa 3,
:tr-loppuetaisyys 500,
:nimi "Kohdeosa kaista 12",
:tr-alkuetaisyys 3,
:tr-numero 20,
:toimenpide 21,
:leveys 3,
:kokonaismassamaara 2,
:pinta_ala 1,
:massamenekki 2,
:materiaali 1}))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id))))
(deftest tallenna-pot2-paallystysilmoitus-jossa-alikohde-muulla-tiella
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
muu-tr-numero 5555
paallystysilmoitus (-> pot2-testidata
(assoc-in [:paallystekerros 1 :tr-numero] muu-tr-numero))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id _ _] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))]
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä"))
(let [paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})
kulutuskerros (:paallystekerros paallystysilmoitus-kannassa)]
(is (= 2 (count kulutuskerros)))
(is (= #{20 muu-tr-numero} (set (map #(:tr-numero %) kulutuskerros)))))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest paivittaa-paallystysilmoitus-muokkaa-yllapitokohdeosaa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Kirkkotie")
_ (is (some? paallystyskohde-id))
alkuperainen-paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))]
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " alkuperäinen ilmoitus")
(let [[_ _ _ yllapitokohdeosadata] (tallenna-testipaallystysilmoitus alkuperainen-paallystysilmoitus 2020)
kohdeosa-id (:id yllapitokohdeosadata)]
(is (= yllapitokohdeosadata
#{{:nimi "Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"}}))
(let [uusi-paallystysilmoitus (-> alkuperainen-paallystysilmoitus
(assoc-in [:ilmoitustiedot :osoitteet 0 :nimi] "Uusi Tie 22")
(assoc-in [:ilmoitustiedot :osoitteet 0 :toimenpide] "Freude")
(assoc-in [:ilmoitustiedot :osoitteet 0 :kohdeosa-id] kohdeosa-id))
[_ _ vastaus paivitetty-yllapitokohdeosadata] (tallenna-testipaallystysilmoitus uusi-paallystysilmoitus 2020)]
(is (nil? (:virhe vastaus)))
(is (= paivitetty-yllapitokohdeosadata
#{{:nimi "Uusi Tie 22"
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Freude"}}))))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-uusi-pot2-paallystysilmoitus-kantaan
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")]
(is (some? paallystyskohde-id))
(is (= 28 paallystyskohde-id))
(u (str "UPDATE yllapitokohdeosa SET toimenpide = 'Wut' WHERE yllapitokohde = 28"))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi pot2 ilmoitus")
(let [paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
maara-ennen-lisaysta (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
[urakka-id sopimus-id vastaus yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
Vastauksena saadaan annetun vuoden . Poistetun .
(is (= 3 (count (:yllapitokohteet vastaus))) "Ylläpitokohteiden määrä vuonna 2021")
(is (= 3 (count (:paallystysilmoitukset vastaus))) "Ylläpitokohteiden määrä vuonna 2021")
(is (= #{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Wut"}
{:nimi "Kohdeosa kaista 11",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Wut"}}
yllapitokohdeosadata))
(let [[tallennettu-versio ilmoitustiedot] (first (q "SELECT versio, ilmoitustiedot FROM paallystysilmoitus
WHERE paallystyskohde = " paallystyskohde-id))]
(is (= tallennettu-versio 2))
(is (nil? ilmoitustiedot) "POT2:ssa kirjoittamme ne omille tauluille"))
(let [maara-lisayksen-jalkeen (ffirst (q (str "SELECT count(*) FROM paallystysilmoitus;")))
paallystysilmoitus-kannassa (kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(log/debug "Testitallennus valmis. POTTI kannassa: " (pr-str paallystysilmoitus-kannassa))
(is (not (nil? paallystysilmoitus-kannassa)))
(is (= (+ maara-ennen-lisaysta 1) maara-lisayksen-jalkeen) "Tallennuksen jälkeen päällystysilmoituksien määrä")
(is (= (:tila paallystysilmoitus-kannassa) :valmis))
(is (= "POT2 lisätieto" (:lisatiedot paallystysilmoitus-kannassa)) "Tallenna lisätiedot")
(is (= (:kokonaishinta-ilman-maaramuutoksia paallystysilmoitus-kannassa) 0M))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))))
(deftest paivittaa-pot2-paallystysilmoitus-ei-muoka-kaikki-yllapitokohdeosan-kentat
Ei saa olla POT ilmoitusta
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")]
(is (= 28 paallystyskohde-id))
(u (str "UPDATE yllapitokohdeosa SET toimenpide = 'Freude' WHERE yllapitokohde = 28"))
(let [alkuperainen-paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
[_ _ _ yllapitokohdeosadata] (tallenna-testipaallystysilmoitus
alkuperainen-paallystysilmoitus
paallystysilmoitus-domain/pot2-vuodesta-eteenpain)]
(is (= yllapitokohdeosadata
#{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}
{:nimi "Kohdeosa kaista 11",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}}) "toimenpide jne ei ole päivetetty")
(let [uusi-paallystysilmoitus (-> alkuperainen-paallystysilmoitus
(assoc-in [:paallystekerros 0 :nimi] "Uusi uudistettu tie 22"))
[_ _ _ paivitetty-yllapitokohdeosadata] (tallenna-testipaallystysilmoitus uusi-paallystysilmoitus 2020)]
(is (= paivitetty-yllapitokohdeosadata
#{{:nimi "Kohdeosa kaista 12",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}
{:nimi "Uusi uudistettu tie 22",
:paallystetyyppi nil,
:raekoko nil,
:tyomenetelma nil,
:massamaara nil,
:toimenpide "Freude"}}) "toimenpide jne ei ole päivetetty, mutta nimi on päivetetty")))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-paallystysilmoitus-ei-salli-null-materiaali-paallystyskerroksessa
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true)
(update-in [:paallystekerros 0] dissoc :materiaali))]
(is (thrown-with-msg? IllegalArgumentException #"Materiaali on valinnainen vain jos toimenpide on KAR"
(tallenna-pot2-testi-paallystysilmoitus urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)))))
(deftest tallenna-pot2-paallystysilmoitus-salli-null-materiaali-vain-jos-on-kar-toimenpide
(let [kar-toimenpide pot2-domain/+kulutuskerros-toimenpide-karhinta+
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true)
(update-in [:paallystekerros 0] dissoc :materiaali)
(assoc-in [:paallystekerros 0 :toimenpide] kar-toimenpide))
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)]
(is (nil? (get-in paallystysilmoitus-kannassa-jalkeen [:paallystekerros 1 :materiaali])))
(is (= kar-toimenpide (get-in paallystysilmoitus-kannassa-jalkeen [:paallystekerros 1 :toimenpide])))))
(deftest tallenna-pot2-paallystysilmoitus-kohteen-alku-ja-loppupvm-muuttuvat
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :aloituspvm] #inst "2021-06-15T21:00:00.000-00:00")
(assoc-in [:perustiedot :valmispvm-kohde] #inst "2021-06-19T21:00:00.000-00:00"))
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)]
(is (= (:aloituspvm paallystysilmoitus-kannassa-ennen) #inst "2021-06-18T21:00:00.000-00:00") "Kohteen aloituspvm ennen muutosta")
(is (= (:aloituspvm paallystysilmoitus-kannassa-jalkeen) #inst "2021-06-15T21:00:00.000-00:00") "Kohteen aloituspvm muutoksen jälkeen")
(is (nil? (:valmispvm-kohde paallystysilmoitus-kannassa-ennen)) "Kohteen valmispvm-kohde ennen muutosta")
(is (= (:valmispvm-kohde paallystysilmoitus-kannassa-jalkeen) #inst "2021-06-19T21:00:00.000-00:00") "Kohteen valmispvm-kohde muutoksen jälkeen")))
(deftest tallenna-pot2-paallystysilmoitus-throwaa-jos-loppupvm-puuttuu
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Aloittamaton kohde mt20")
urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :aloituspvm] #inst "2021-06-15T21:00:00.000-00:00")
(assoc-in [:perustiedot :valmispvm-kohde] nil))]
(is (thrown? IllegalArgumentException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2021
:paallystysilmoitus paallystysilmoitus})))))
(deftest ei-saa-paivittaa-jos-on-vaara-versio
(let [paallystyskohde-vanha-pot-id (ffirst (q "SELECT id FROM yllapitokohde WHERE nimi = 'Ouluntie'"))]
(is (not (nil? paallystyskohde-vanha-pot-id)))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus-pot2 (-> pot2-testidata
(assoc :paallystyskohde-id paallystyskohde-vanha-pot-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))]
(is (thrown-with-msg? IllegalArgumentException #"Väärä POT versio. Pyynnössä on 2, pitäisi olla 1. Ota yhteyttä Harjan tukeen."
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi paallystysilmoitus-domain/pot2-vuodesta-eteenpain
:paallystysilmoitus paallystysilmoitus-pot2}))))))
(deftest ei-saa-paivittaa-jos-ei-ole-versiota
(let [paallystysilmoitus-pot2 (-> pot-testidata
(dissoc :versio)
(assoc :paallystyskohde-id 123))]
(is (thrown-with-msg? IllegalArgumentException #"Pyynnöstä puuttuu versio. Ota yhteyttä Harjan tukeen."
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id 1
:sopimus-id 1
:vuosi 2020
:paallystysilmoitus paallystysilmoitus-pot2})))))
(defn- alustarivi-idlla-loytyy?
"Palauttaa booleanin, löytyykö annetulla pot2a_id:llä riviä"
[alustarivit id]
(boolean (some? (first (filter #(= id (:pot2a_id %)) alustarivit)))))
(defn- alustarivi-idlla
"Palauttaa rivi, annetulla pot2a_id:llä"
[alustarivit id]
(first (filter #(= id (:pot2a_id %)) alustarivit)))
(def pot2-alustatestien-ilmoitus
{:perustiedot {:tila :aloitettu,
:tr-kaista nil,
:kohdenimi "Tärkeä kohde mt20",
:kohdenumero "L42",
:tr-ajorata nil,
:kommentit [],
:tr-loppuosa 1,
:valmispvm-kohde #inst "2021-06-23T21:00:00.000-00:00",
:tunnus nil,
:tr-alkuosa 1,
:versio 2,
:tr-loppuetaisyys 3827,
:aloituspvm #inst "2021-06-18T21:00:00.000-00:00",
:takuupvm #inst "2024-12-30T22:00:00.000-00:00",
:tr-osoite {:tr-kaista nil, :tr-ajorata nil, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 3827,
:tr-alkuetaisyys 1066, :tr-numero 20},
:asiatarkastus {:lisatiedot nil, :hyvaksytty nil, :tarkastusaika nil, :tarkastaja nil},
:tr-alkuetaisyys 1066, :tr-numero 20,
:tekninen-osa {:paatos nil, :kasittelyaika nil, :perustelu nil},
:valmispvm-paallystys #inst "2021-06-20T21:00:00.000-00:00"},
:paallystyskohde-id 27,
:versio 2,
:lisatiedot "POT2 alustatesti ilmoitus"
:ilmoitustiedot nil,
:paallystekerros [{:kohdeosa-id 11, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 1, :jarjestysnro 1,
:tr-alkuosa 1, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Tärkeä kohdeosa kaista 11",
:materiaali 1, :tr-alkuetaisyys 1066, :piennar true, :tr-numero 20, :toimenpide 22, :pot2p_id 1}
{:kohdeosa-id 12, :tr-kaista 12, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 1, :jarjestysnro 1,
:tr-alkuosa 1, :massamenekki 333, :tr-loppuetaisyys 3827, :nimi "Tärkeä kohdeosa kaista 12",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false, :tr-numero 20, :toimenpide 23, :pot2p_id 2}],
:alusta [{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500, :materiaali 1,
:tr-alkuetaisyys 1066, :tr-numero 20, :toimenpide 32, :pot2a_id 1,
:massa 1, :kokonaismassamaara 100, :massamaara 5}]})
(def pot2-alusta-esimerkki
[{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero 20, :toimenpide 32,
:massa 1, :massamaara 100}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys (inc 1066), :tr-numero 20, :toimenpide 32,
:massa 1, :massamaara 100}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys (- 2000 1),
:materiaali 1, :pituus 500,
:tr-alkuetaisyys 1500, :tr-numero 20, :toimenpide 11,
:kasittelysyvyys 55, :sideaine 1, :sideainepitoisuus 10.0M, :murske 1}
{:tr-kaista 12, :tr-ajorata 1, :tr-loppuosa 1, :tr-alkuosa 1, :tr-loppuetaisyys 2500,
:materiaali 1, :pituus 500,
:tr-alkuetaisyys 2000, :tr-numero 20, :toimenpide 3,
:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}])
(deftest tallenna-pot2-poista-alustarivi
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id pot2-alustatestien-ilmoitus)
alustarivit-ennen (:alusta paallystysilmoitus-kannassa-ennen)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)]
(is (not (nil? paallystysilmoitus-kannassa-ennen)))
(is (= (:versio paallystysilmoitus-kannassa-ennen) 2))
(is (= 6 (count alustarivit-ennen)))
(is (= 1 (count alustarivit-jalkeen)))
(is (alustarivi-idlla-loytyy? alustarivit-ennen 1) "alusta id:llä 1 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 2) "alusta id:llä 2 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 1) "alusta id:llä 1 löytyy")
(is (not (alustarivi-idlla-loytyy? alustarivit-jalkeen 2)) "alusta id:llä 2 ei saa löytyä")
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (assoc pot2-alustatestien-ilmoitus :alusta pot2-alusta-esimerkki)
Tehdään tallennus alustariviä
[paallystysilmoitus-kannassa-ennen paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-ennen (:alusta paallystysilmoitus-kannassa-ennen)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-6 (alustarivi-idlla alustarivit-jalkeen 11)]
(is (not (nil? paallystysilmoitus-kannassa-ennen)))
(is (= (:versio paallystysilmoitus-kannassa-ennen) 2))
(is (= 6 (count alustarivit-ennen)))
(is (= 4 (count alustarivit-jalkeen)))
(is (alustarivi-idlla-loytyy? alustarivit-ennen 1) "alusta id:llä 1 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 2) "alusta id:llä 2 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 3) "alusta id:llä 3 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 4) "alusta id:llä 4 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 5) "alusta id:llä 5 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-ennen 6) "alusta id:llä 6 löytyy")
(is (not (alustarivi-idlla-loytyy? alustarivit-jalkeen 7)) "alusta id:llä 7 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 8) "alusta id:llä 8 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 9) "alusta id:llä 9 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 10) "alusta id:llä 10 löytyy")
(is (alustarivi-idlla-loytyy? alustarivit-jalkeen 11) "alusta id:llä 10 löytyy")
(is (= {:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}
(select-keys alustarivi-6 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-vain-pakolliset-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] dissoc :verkon-tarkoitus))
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-10 (alustarivi-idlla alustarivit-jalkeen 11)]
(is (= {:verkon-tyyppi 1 :verkon-tarkoitus nil :verkon-sijainti 3}
(select-keys alustarivi-10 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-lisaa-alustarivi-ja-vain-pakolliset-tas-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 2] dissoc :murske :massamaara))
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)
alustarivi-9 (alustarivi-idlla alustarivit-jalkeen 10)]
(is (= {:kasittelysyvyys 55, :sideaine 1, :sideainepitoisuus 10.0M, :murske nil, :massamaara nil}
(select-keys alustarivi-9 [:kasittelysyvyys :sideaine :sideainepitoisuus :murske :massamaara])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest tallenna-pot2-jossa-on-alikohde-muulla-tiella-lisaa-alustarivi
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 7777
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc-in [:paallystekerros 2]
{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 10, :jarjestysnro 1,
:tr-alkuosa 10, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Muu tie",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23, :pot2p_id 3})
(assoc :alusta pot2-alusta-esimerkki)
(assoc-in [:alusta 4]
{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 10, :tr-alkuosa 10, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero muu-tr-numero, :toimenpide 32,
:kokonaismassamaara 100, :massa 1, :massamaara 20}))
Tehdään tallennus alustariviä
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-jalkeen (:alusta paallystysilmoitus-kannassa-jalkeen)]
(is (= 5 (count alustarivit-jalkeen)))
(is (= #{{:pot2a_id 10
:tr-numero 20}
{:pot2a_id 11
:tr-numero 20}
{:pot2a_id 12
:tr-numero 7777}
{:pot2a_id 8
:tr-numero 20}
{:pot2a_id 9
:tr-numero 20}}
(clojure.set/project alustarivit-jalkeen [:pot2a_id :tr-numero])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
VHAR-5750
(deftest tallenna-pot2-jossa-on-alikohde-muulla-tiella-validointi-ottaa-tie-huomioon.
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 837
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(dissoc :alusta)
(dissoc :paallystekerros)
(assoc :paallystekerros
[{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 0, :pinta_ala 15000, :tr-loppuosa 2, :jarjestysnro 1,
:tr-alkuosa 2, :massamenekki 333, :tr-loppuetaisyys 1100, :nimi "Muu tie 1",
:materiaali 2, :tr-alkuetaisyys 1001, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23}
{:kohdeosa-id nil, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 0, :pinta_ala 15000, :tr-loppuosa 2, :jarjestysnro 1,
:tr-alkuosa 2, :massamenekki 333, :tr-loppuetaisyys 1110, :nimi "Muu tie 2",
:materiaali 2, :tr-alkuetaisyys 1100, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23}]))
Tehdään tallennus alustariviä
[_ paallystysilmoitus-kannassa-jalkeen] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
paallystekerrokset-jalkeen (:paallystekerros paallystysilmoitus-kannassa-jalkeen)]
#_(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivi-on-tiella-joka-ei-loydy-kulutuskerroksesta
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
muu-tr-numero 7777
vaara-tr-numero 5555
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc-in [:paallystekerros 2]
{:kohdeosa-id 13, :tr-kaista 11, :leveys 3, :kokonaismassamaara 5000,
:tr-ajorata 1, :pinta_ala 15000, :tr-loppuosa 10, :jarjestysnro 1,
:tr-alkuosa 10, :massamenekki 333, :tr-loppuetaisyys 1500, :nimi "Muu tie",
:materiaali 2, :tr-alkuetaisyys 1066, :piennar false,
:tr-numero muu-tr-numero, :toimenpide 23, :pot2p_id 3})
(assoc :alusta pot2-alusta-esimerkki)
(assoc-in [:alusta 4]
{:tr-kaista 11, :tr-ajorata 1, :tr-loppuosa 10, :tr-alkuosa 10, :tr-loppuetaisyys 1500,
:materiaali 1, :pituus 434,
:tr-alkuetaisyys 1066, :tr-numero vaara-tr-numero, :toimenpide 32}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustatoimenpiteen täytyy olla samalla tiellä kuin jokin alikohteista. Tienumero 5555 ei ole.")))
(deftest tallenna-pot2-paivittaa-alustarivi-jossa-on-verkko-tiedot
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
alkuperaiset-verkon-tiedot {:verkon-tyyppi 1 :verkon-tarkoitus 2 :verkon-sijainti 3}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge alkuperaiset-verkon-tiedot))
[_ paallystysilmoitus-kannassa-uusi] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paallystysilmoitus)
alustarivit-uudet (:alusta paallystysilmoitus-kannassa-uusi)
paivitetyt-verkon-tiedot {:verkon-tyyppi 9 :verkon-tarkoitus 1 :verkon-sijainti 2}
paivitetty-paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta alustarivit-uudet)
(update-in [:alusta 3] merge paivitetyt-verkon-tiedot))
[_ paallystysilmoitus-kannassa-paivitetty] (tallenna-pot2-testi-paallystysilmoitus
urakka-id sopimus-id paallystyskohde-id paivitetty-paallystysilmoitus)
alustarivit-paivitetyt (:alusta paallystysilmoitus-kannassa-paivitetty)
paivitetty-alustarivi-11 (alustarivi-idlla alustarivit-paivitetyt 11)]
(is (some? paivitetty-alustarivi-11) "alusta id:llä 10 löytyy")
(is (= paivitetyt-verkon-tiedot (select-keys paivitetty-alustarivi-11 [:verkon-tyyppi :verkon-tarkoitus :verkon-sijainti])))
(poista-paallystysilmoitus-paallystyskohtella paallystyskohde-id)))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-ei-ole-kaikki-pakolliset-verkontiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] dissoc :verkon-sijainti))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustassa väärät lisätiedot.")))
(deftest ei-saa-tallenna-pot2-jos-sama-tr-osoite-samalla-alustatoimenpiteella
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 1] merge {:tr-kaista 11}))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Kohteenosa on päällekkäin toisen osan kanssa.")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-on-vaarat-lisatiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
verkon-tiedot {:verkon-tyyppi 1 :verkon-sijainti 3 :verkon-tarkoitus 1 :massamaara 1}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge verkon-tiedot))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
"Alustassa väärät lisätiedot.")))
(deftest ei-saa-tallenna-pot2-paallystysilmoitus-jos-alustarivilla-on-vaarat-verkontiedot
(let [paallystyskohde-id (hae-yllapitokohteen-id-nimella "Tärkeä kohde mt20")
verkon-tiedot {:verkon-tyyppi 1 :verkon-tarkoitus 333 :verkon-sijainti 3}
paallystysilmoitus (-> pot2-alustatestien-ilmoitus
(assoc :alusta pot2-alusta-esimerkki)
(update-in [:alusta 3] merge verkon-tiedot))]
(tallenna-vaara-paallystysilmoitus paallystyskohde-id paallystysilmoitus 2021
{"alustatoimenpide""ERROR: insert or update on table \"pot2_alusta\" violates foreign key constraint \"pot2_alusta_verkon_tarkoitus_fkey\"\n Detail: Key (verkon_tarkoitus)=(333) is not present in table \"pot2_verkon_tarkoitus\"."}
)))
(deftest uuden-paallystysilmoituksen-tallennus-eri-urakkaan-ei-onnistu
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-ei-ole-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(log/debug "Tallennetaan päällystyskohteelle " paallystyskohde-id " uusi ilmoitus")
(let [urakka-id (hae-oulun-alueurakan-2014-2019-id)
sopimus-id (hae-oulun-alueurakan-2014-2019-paasopimuksen-id)
paallystysilmoitus (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)]
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))))))
(deftest paivita-paallystysilmoitukselle-paatostiedot
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu] "Hyvä ilmoitus!"))
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-utajarven-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))]
(with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus}))
(let [paallystysilmoitus-kannassa
(kutsu-palvelua (:http-palvelin jarjestelma)
:urakan-paallystysilmoitus-paallystyskohteella +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:paallystyskohde-id paallystyskohde-id})]
(is (some? paallystysilmoitus-kannassa))
(is (= (:tila paallystysilmoitus-kannassa) :lukittu))
(is (= (get-in paallystysilmoitus-kannassa [:tekninen-osa :paatos]) :hyvaksytty))
(is (= (get-in paallystysilmoitus-kannassa [:tekninen-osa :perustelu])
(get-in paallystysilmoitus [:perustiedot :tekninen-osa :perustelu])))
Tie 22 tiedot tallentuivat kantaan , 20 ei koska
(is (some #(= (:nimi %) "Tie 22")
(get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet])))
(is (not (some #(= (:nimi %) "Tie 20")
(get-in paallystysilmoitus-kannassa [:ilmoitustiedot :osoitteet]))))
(is (= (update-in (:ilmoitustiedot paallystysilmoitus-kannassa) [:osoitteet 0] (fn [osoite]
(dissoc osoite :kohdeosa-id)))
{:alustatoimet [{:kasittelymenetelma 1
:paksuus 1234
:tekninen-toimenpide 1
:tr-numero 22
:tr-kaista 11
:tr-ajorata 1
:tr-alkuetaisyys 3
:tr-alkuosa 3
:tr-loppuetaisyys 5
:tr-loppuosa 3
:verkkotyyppi 1
:verkon-sijainti 1
:verkon-tarkoitus 1}]
Alikohteen tiedot
:nimi "Tie 22"
:tr-numero 22
:tr-alkuosa 3
:tr-alkuetaisyys 3
:tr-loppuosa 3
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 11
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2.00M
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"}]}))
, ei voi enää päivittää
(log/debug "Tarkistetaan, ettei voi muokata lukittua ilmoitusta.")
(is (thrown? SecurityException (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})))
(u (str "UPDATE paallystysilmoitus SET
tila = NULL,
paatos_tekninen_osa = NULL,
perustelu_tekninen_osa = NULL
(deftest lisaa-kohdeosa
(let [paallystyskohde-id (hae-utajarven-yllapitokohde-jolla-ei-ole-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id (hae-urakan-id-nimella "Utajärven päällystysurakka")
sopimus-id (hae-utajarven-paallystysurakan-paasopimuksen-id)
paallystysilmoitus (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
hae-kohteiden-maara #(count (q (str "SELECT * FROM yllapitokohdeosa"
" WHERE poistettu IS NOT TRUE "
" AND yllapitokohde = " paallystyskohde-id ";")))]
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})
(let [kohteita-ennen-lisaysta (hae-kohteiden-maara)
paallystysilmoitus (update-in paallystysilmoitus [:ilmoitustiedot :osoitteet]
Alikohteen tiedot
:nimi "Tie 123"
:tr-numero 666
:tr-alkuosa 2
:tr-alkuetaisyys 3
:tr-loppuosa 4
:tr-loppuetaisyys 5
:tr-ajorata 1
:tr-kaista 1
:paallystetyyppi 1
:raekoko 1
:tyomenetelma 12
:massamaara 2
:toimenpide "Wut"
:toimenpide-paallystetyyppi 1
:toimenpide-raekoko 1
:kokonaismassamaara 2
:rc% 3
:toimenpide-tyomenetelma 12
:leveys 5
:massamenekki 7
:pinta-ala 8
:esiintyma "asd"
:km-arvo "asd"
:muotoarvo "asd"
:sideainetyyppi 1
:pitoisuus 54
:lisaaineet "asd"})]
(is (= 1 kohteita-ennen-lisaysta))
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-jvh+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2019
:paallystysilmoitus paallystysilmoitus})
(is (= (inc kohteita-ennen-lisaysta) (hae-kohteiden-maara)) "Kohteita on nyt 1 enemmän")))))
(deftest ala-paivita-paallystysilmoitukselle-paatostiedot-jos-ei-oikeuksia
(let [paallystyskohde-id (hae-muhoksen-yllapitokohde-ilman-paallystysilmoitusta)]
(is (some? paallystyskohde-id))
(let [urakka-id @muhoksen-paallystysurakan-id
sopimus-id @muhoksen-paallystysurakan-paasopimuksen-id
paallystysilmoitus (-> (assoc pot-testidata :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu]
"Yritän saada ilmoituksen hyväksytyksi ilman oikeuksia."))]
(is (thrown? RuntimeException
(kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus +kayttaja-tero+
{:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))))))
(deftest yllapitokohteiden-maksuerien-haku-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:hae-paallystyksen-maksuerat
+kayttaja-jvh+
{::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017})
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (== (:kokonaishinta leppajarven-ramppi) 7248.95))
(is (= (count (:maksuerat leppajarven-ramppi)) 2))))
(deftest yllapitokohteen-uusien-maksuerien-tallennus-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
leppajarven-ramppi (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)
testidata (gen/sample (s/gen ::paallystyksen-maksuerat-domain/tallennettava-yllapitokohde-maksuerineen))]
(doseq [yllapitokohde testidata]
(u "DELETE FROM yllapitokohteen_maksuera WHERE yllapitokohde = " leppajarven-ramppi ";")
(u "DELETE FROM yllapitokohteen_maksueratunnus WHERE yllapitokohde = " leppajarven-ramppi ";")
(let [maksuerat (:maksuerat yllapitokohde)
maksueranumerot (map :maksueranumero maksuerat)
, tallentaa vain viimeisimmän .
Otetaan viimeiset , että tallennus menee oikein
tallennettavat-maksuerat (if (empty? maksueranumerot)
[]
(keep (fn [maksueranumero]
(-> (filter #(= (:maksueranumero %) maksueranumero) maksuerat)
last
(dissoc :id)))
(range (apply min maksueranumerot)
(inc (apply max maksueranumerot)))))
payload {::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017
:yllapitokohteet [(assoc yllapitokohde :id leppajarven-ramppi)]}
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystyksen-maksuerat
+kayttaja-jvh+
payload)
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (= (map #(dissoc % :id) (:maksuerat leppajarven-ramppi))
tallennettavat-maksuerat))))))
(deftest yllapitokohteen-maksuerien-paivitys-toimii
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
leppajarven-ramppi (hae-yllapitokohde-leppajarven-ramppi-jolla-paallystysilmoitus)]
(let [tallennettavat-maksuerat [{:maksueranumero 1 :sisalto "Päivitetäänpäs tämä"}
{:maksueranumero 4 :sisalto nil}
{:maksueranumero 5 :sisalto "Uusi maksuerä"}]
payload {::urakka-domain/id urakka-id
::sopimus-domain/id sopimus-id
::urakka-domain/vuosi 2017
:yllapitokohteet [{:id leppajarven-ramppi
:maksuerat tallennettavat-maksuerat
:maksueratunnus "Uusi maksuerätunnus"}]}
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystyksen-maksuerat
+kayttaja-jvh+
payload)
leppajarven-ramppi (yllapitokohteet-test/kohde-nimella vastaus "Leppäjärven ramppi")]
(is (= (count vastaus) 5) "Kaikki kohteet palautuu")
(is (= (:maksueratunnus leppajarven-ramppi) "Uusi maksuerätunnus"))
(is (= (:maksuerat leppajarven-ramppi)
[{:id 1
:maksueranumero 1
:sisalto "Päivitetäänpäs tämä"}
{:id 2
:maksueranumero 2
:sisalto "Puolet"}
{:id 6
:maksueranumero 4
:sisalto nil}
{:id 7
:maksueranumero 5
:sisalto "Uusi maksuerä"}])
"Uudet maksuerät ilmestyivät kantaan, vanhat päivitettiin ja payloadissa olemattomiin ei koskettu"))))
(deftest avaa-lukitun-potin-lukitus
(let [kohde-id (hae-yllapitokohteen-id-nimella "Oulun ohitusramppi")
payload {::urakka-domain/id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
::paallystysilmoitus-domain/paallystyskohde-id kohde-id
::paallystysilmoitus-domain/tila :valmis}
tila-ennen-kutsua (keyword (second (first (q (str "SELECT id, tila FROM paallystysilmoitus WHERE paallystyskohde = " kohde-id)))))
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila +kayttaja-jvh+ payload)]
(is (= :lukittu tila-ennen-kutsua))
(is (= :valmis (:tila vastaus)))))
(deftest avaa-lukitun-potin-lukitus-ei-sallittu-koska-tero-ei-tassa-urakanvalvojana
(let [kohde-id (hae-yllapitokohteen-id-nimella "Oulun ohitusramppi")
payload {::urakka-domain/id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
::paallystysilmoitus-domain/paallystyskohde-id kohde-id
::paallystysilmoitus-domain/tila :valmis}]
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila
+kayttaja-tero+
payload)))
(is (thrown? Exception (kutsu-palvelua (:http-palvelin jarjestelma)
:aseta-paallystysilmoituksen-tila
+kayttaja-vastuuhlo-muhos+
payload)))))
(deftest sahkopostien-lahetys
(let [urakka-id (hae-urakan-id-nimella "Muhoksen päällystysurakka")
sopimus-id (hae-muhoksen-paallystysurakan-paasopimuksen-id)
paallystyskohde-id (:paallystyskohde (first (q-map (str "SELECT paallystyskohde "
"FROM paallystysilmoitus pi "
"JOIN yllapitokohde yk ON yk.id=pi.paallystyskohde "
"WHERE (pi.paatos_tekninen_osa IS NULL OR "
"pi.paatos_tekninen_osa='hylatty'::paallystysilmoituksen_paatostyyppi) AND "
"pi.tila!='valmis'::paallystystila AND "
"yk.urakka=" urakka-id " "
"LIMIT 1"))))
Tehdään ensin sellainen päällystysilmoitus , on
ja lähetetään
paallystysilmoitus (-> pot-testidata
(assoc :paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :valmis-kasiteltavaksi] true))
fim-vastaus (slurp (io/resource "xsd/fim/esimerkit/hae-muhoksen-paallystysurakan-kayttajat.xml"))
viesti-id (str (UUID/randomUUID))]
(with-fake-http
[{:url +testi-fim+ :method :get} fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus viesti-id)]
(let [vastaus (future (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))
_ (odota-ehdon-tayttymista #(realized? vastaus) "Saatiin vastaus :tallenna-paallystysilmoitus" ehdon-timeout)
_ (Thread/sleep 1000)
integraatioviestit (q-map (str "select id, integraatiotapahtuma, suunta, sisaltotyyppi, siirtotyyppi, sisalto, otsikko, parametrit, osoite, kasitteleva_palvelin
integraatiotapahtumat (q-map (str "select id, integraatio, alkanut, paattynyt, lisatietoja, onnistunut, ulkoinenid FROM integraatiotapahtuma"))
Hyväksytään ilmoitus valvojalle
paallystysilmoitus (-> (assoc pot-testidata
:paallystyskohde-id paallystyskohde-id)
(assoc-in [:perustiedot :tekninen-osa :paatos] :hyvaksytty)
(assoc-in [:perustiedot :tekninen-osa :perustelu] "Hyvä ilmoitus!"))]
Ensimmäinen integraatioviesti sisältää tiedot haetuista FIM käyttäjistä , olla sähköposti , lähetettiin
(is (clojure.string/includes? (:sisalto (second integraatioviestit)) ""))
(is (= (integraatio-kyselyt/integraation-id (:db jarjestelma) "fim" "hae-urakan-kayttajat") (:integraatio (first integraatiotapahtumat))))
(is (= (integraatio-kyselyt/integraation-id (:db jarjestelma) "api" "sahkoposti-lahetys") (:integraatio (second integraatiotapahtumat))))))
#_ (with-fake-http
[+testi-fim+ fim-vastaus
{:url ":8084/harja/api/sahkoposti/xml" :method :post} (onnistunut-sahkopostikuittaus (str (UUID/randomUUID)))]
(let [_ (println "************************************************** uusi tallennnus ********************************' ")
vastaus (future (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysilmoitus
+kayttaja-jvh+ {:urakka-id urakka-id
:sopimus-id sopimus-id
:vuosi 2018
:paallystysilmoitus paallystysilmoitus}))
_ (odota-ehdon-tayttymista #(realized? vastaus) "Saatiin vastaus :tallenna-paallystysilmoitus" ehdon-timeout)
integraatioviestit (q-map (str "select id, integraatiotapahtuma, suunta, sisaltotyyppi, siirtotyyppi, sisalto, otsikko, parametrit, osoite, kasitteleva_palvelin
_ (println "***************************** integraatioviestit" (pr-str integraatioviestit))
integraatiotapahtumat (q-map (str "select id, integraatio, alkanut, paattynyt, lisatietoja, onnistunut, ulkoinenid FROM integraatiotapahtuma"))]
Viides integraatioviesti sisältää tiedot haetuista FIM käyttäjistä , olla sähköposti , lähetettiin
(is (clojure.string/includes? (:sisalto (nth integraatioviestit 5)) ""))))))
(deftest lisaa-paallystysilmoitukseen-kohdeosien-id
(let [paallystysilmoitus {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1
:nimi "1 A"
:toimenpide-paallystetyyppi 1
:tr-ajorata 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 2
:nimi "1 B"
:toimenpide-paallystetyyppi 1
:tr-ajorata 1
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}
{:kohdeosa-id 3
:nimi "2 A"
:toimenpide-paallystetyyppi 1
:tr-ajorata 2
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 4
:nimi "2 B"
:toimenpide-paallystetyyppi 1
:tr-ajorata 2
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]}}
kohdeosat [{:id 1
:nimi "1 A"
:tr-ajorata 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 2
:nimi "1 B"
:tr-ajorata 1
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}
{:id 3
:nimi "2 A"
:tr-ajorata 2
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 4
:nimi "2 B"
:tr-ajorata 2
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-kaista 21
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]]
(is (= {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1, :nimi "1 A",
:toimenpide-paallystetyyppi 1, :tr-ajorata 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1, :tr-kaista 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}
{:kohdeosa-id 2, :nimi "1 B",
:toimenpide-paallystetyyppi 1, :tr-ajorata 1,
:tr-alkuetaisyys 1500, :tr-alkuosa 1,
:tr-kaista 1, :tr-loppuetaisyys 0,
:tr-loppuosa 3, :tr-numero 20}
{:kohdeosa-id 3, :nimi "2 A",
:toimenpide-paallystetyyppi 1, :tr-ajorata 2,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-kaista 21, :tr-loppuetaisyys 1000,
:tr-loppuosa 1, :tr-numero 20}
{:kohdeosa-id 4, :nimi "2 B",
:toimenpide-paallystetyyppi 1, :tr-ajorata 2,
:tr-alkuetaisyys 1500, :tr-alkuosa 1,
:tr-kaista 21, :tr-loppuetaisyys 0,
:tr-loppuosa 3,
:tr-numero 20}]}}
(paallystys/lisaa-paallystysilmoitukseen-kohdeosien-idt paallystysilmoitus kohdeosat))
"Kohdeosille on lisätty id:t oikein, kun ajorata ja kaista ovat paikoillaan"))
(let [paallystysilmoitus {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1
:nimi "1"
:toimenpide-paallystetyyppi 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:kohdeosa-id 3
:nimi "2"
:toimenpide-paallystetyyppi 1
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}]}}
kohdeosat [{:id 1
:nimi "1"
:tr-alkuetaisyys 1
:tr-alkuosa 1
:tr-loppuetaisyys 1000
:tr-loppuosa 1
:tr-numero 20}
{:id 2
:nimi "2"
:tr-alkuetaisyys 1500
:tr-alkuosa 1
:tr-loppuetaisyys 0
:tr-loppuosa 3
:tr-numero 20}]]
(is (= {:ilmoitustiedot {:osoitteet [{:kohdeosa-id 1, :nimi "1",
:toimenpide-paallystetyyppi 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}
{:kohdeosa-id 1, :nimi "2",
:toimenpide-paallystetyyppi 1,
:tr-alkuetaisyys 1, :tr-alkuosa 1,
:tr-loppuetaisyys 1000, :tr-loppuosa 1,
:tr-numero 20}]}}
(paallystys/lisaa-paallystysilmoitukseen-kohdeosien-idt paallystysilmoitus kohdeosat))
"Kohdeosille on lisätty id:t oikein, kun ajorataa ja kaistaa ei ole")))
|
0493bc707a53df78e28b7dfa30ff2b32adcded260d24ecac860c744bd061989b | athensresearch/athens | utils.cljc | (ns athens.common.utils
"Athens Common Utilities.
Shared between CLJ and CLJS."
(:require
[clojure.pprint :as pprint])
#?(:cljs
(:require-macros
[athens.common.utils]))
#?(:clj
(:import
(java.time
LocalDateTime)
(java.util
Date))))
(defn now-ts
[]
#?(:clj (.getTime (Date.))
:cljs (.getTime (js/Date.))))
(defn now-ms
[]
#?(:clj (/ (.getNano (LocalDateTime/now)) 1000000)
:cljs (js/performance.now)))
(defn uuid->string
"Useful for printing and to get around how cljs transit uuids are not uuids
(see -cljs/issues/41).
It would be less characters to just type `str` instead of this fn, especially
with a namespace, but forgetting to convert uuids at all is a common error,
so having a dedicated fn helps us keep it in mind."
[uuid]
(str uuid))
(defn gen-block-uid
"Generates new `:block/uid`."
[]
(subs (str (random-uuid)) 27))
(defn gen-event-id
[]
(random-uuid))
(defmacro log-time
[prefix expr]
`(let [start# (now-ms)
ret# ~expr]
(log/info ~prefix (double (- (now-ms) start#)) "ms")
ret#))
(defmacro parses-to
[parser & tests]
`(t/are [in# out#] (= out# (do
(println in#)
(time (~parser in#))))
~@tests))
(defn spy
"Pretty print and return x.
Useful for debugging and logging."
[x]
(pprint/pprint x)
x)
| null | https://raw.githubusercontent.com/athensresearch/athens/536ba577e38ead6810fd9d357f1ef5991999fc88/src/cljc/athens/common/utils.cljc | clojure | (ns athens.common.utils
"Athens Common Utilities.
Shared between CLJ and CLJS."
(:require
[clojure.pprint :as pprint])
#?(:cljs
(:require-macros
[athens.common.utils]))
#?(:clj
(:import
(java.time
LocalDateTime)
(java.util
Date))))
(defn now-ts
[]
#?(:clj (.getTime (Date.))
:cljs (.getTime (js/Date.))))
(defn now-ms
[]
#?(:clj (/ (.getNano (LocalDateTime/now)) 1000000)
:cljs (js/performance.now)))
(defn uuid->string
"Useful for printing and to get around how cljs transit uuids are not uuids
(see -cljs/issues/41).
It would be less characters to just type `str` instead of this fn, especially
with a namespace, but forgetting to convert uuids at all is a common error,
so having a dedicated fn helps us keep it in mind."
[uuid]
(str uuid))
(defn gen-block-uid
"Generates new `:block/uid`."
[]
(subs (str (random-uuid)) 27))
(defn gen-event-id
[]
(random-uuid))
(defmacro log-time
[prefix expr]
`(let [start# (now-ms)
ret# ~expr]
(log/info ~prefix (double (- (now-ms) start#)) "ms")
ret#))
(defmacro parses-to
[parser & tests]
`(t/are [in# out#] (= out# (do
(println in#)
(time (~parser in#))))
~@tests))
(defn spy
"Pretty print and return x.
Useful for debugging and logging."
[x]
(pprint/pprint x)
x)
|
|
4d947704455f2dda97e47fd55b55c29eed9be6820675ecb0e3839b375e3061ef | stackbuilders/hapistrano | Main.hs | module Main where
import Lib
main :: IO ()
main = helloWorld
| null | https://raw.githubusercontent.com/stackbuilders/hapistrano/ffbe5b6263d9d6d84049932dbe5ef7732edc3f1e/example/app/Main.hs | haskell | module Main where
import Lib
main :: IO ()
main = helloWorld
|
|
2a34ab74a84725f3b54d5b9fb0a73a7ff2e7a5007b2f4535f30b95277a4951f7 | blindglobe/clocc | defsys.lisp | (in-package :user)
(defparameter *here* (make-pathname
:directory (pathname-directory *load-truename*)))
(pushnew 'compile pcl::*defclass-times*)
(pushnew 'compile pcl::*defgeneric-times*)
(defvar *clx-directory* "target:clx/*")
(defvar *clue-directory* (merge-pathnames "clue/" *here*))
(setf (search-list "clue:") (list *here*))
;; Don't warn about botched values decls
(setf c:*suppress-values-declaration* t)
(pushnew 'values pcl::*non-variable-declarations*)
Ensure * features * knows about CLOS and PCL
(when (find-package 'pcl)
(pushnew :pcl *features*)
(pushnew :clos *features*)
(unless (find-package :clos)
(rename-package :pcl :pcl '(:clos))))
(when (find-package 'clos)
(pushnew :clos *features*))
Ensure * features * knows about the Common Lisp Error Handler
(when (find-package 'conditions)
(pushnew :cleh *features*))
handle PCL 's precompile " feature "
(defun hack-precom (path op &optional (pathname "precom"))
(declare (type (member :compile :load :ignore) op))
(let* ((src (merge-pathnames (make-pathname :name pathname :type "lisp")
path))
(obj (compile-file-pathname src)))
( format t " ~ & ~a ~a ~a ~a~% " path op pathname )
(case op
(:compile
(when (probe-file src)
(unless (probe-file obj)
(compile-file src))))
(:load
(when (probe-file obj)
(load obj))))))
(defsystem
clx
(:default-pathname "target:clx/")
"macros"
"bufmac")
(defvar *clue-precom* "clue:clue/precom")
(defvar *pict-precom* "clue:pictures/precom")
(when (probe-file "clue:patch.lisp")
(load "clue:patch" :if-source-newer :compile))
(defsystem
clue
(:default-pathname "clue:clue/"
:needed-systems (clx) )
#+nil"common-lisp"
"clue" ; Define packages
(:module clue-precom-load
:load-form (hack-precom "clue:clue/" :load)
:compile-form t)
#+nil"clx-patch" ; Modify xlib:create-window
#+nil"window-doc" ; pointer documentation window support
"defgeneric" ; pw adds
Utilities for event translation
CLOS for resources and type conversion
"intrinsics" ; The "guts"
Support for gcontext , pixmap , cursor
"resource" ; Resource and type conversion
"gray" ; Gray stipple patterns
"cursor" ; Standard cursor names
"events" ; Event handling
"virtual" ; Support for windowless contacts
"shells" ; Support for top-level window/session mgr.
Geometry management methods for root contacts
#+nil"stream" ; interactive-stream (non-portable!!)
"package" ; External cluei symbols exported from clue
(:module clue-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:clue/" :compile))
)
(defsystem
clio
(:needed-systems ( clue )
:default-pathname "clue:clio/"
:components
"clio"
"defgeneric"
(:module clio-precom-load
:load-form (hack-precom "clue:clio/" :load)
:compile-form t)
"ol-defs"
"utility"
"core-mixins"
"gravity"
"ol-images"
"buttons"
"form"
"table"
"choices"
"scroller"
"slider"
"scroll-frame"
"mchoices"
"menu"
"psheet"
"command"
"confirm"
"buffer"
"text-command"
"display-text"
"edit-text"
"display-imag"
"dlog-button"
(:module clio-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:clio/" :compile))
))
(defsystem
clio-examples
(:default-pathname "clue:clio/examples/")
"package" "cmd-frame" "sketchpad" "sketch")
(defsystem
pictures
( :default-pathname "clue:pictures/"
:needed-systems (clue ))
"package"
(:module pict-precom-load
:load-form (hack-precom "clue:pictures/" :load)
:compile-form t)
"defgeneric"
"types"
"macros"
"sequence"
"transform"
"extent"
"edge"
"class-def" :needed-systems ("edge" "extent")
;; these have circular dependencies
"gstate" :needed-systems ("class-def")
"gstack"
"graphic"
"font-family"
"view-draw"
"scene"
"line"
"circle"
"polypoint"
"polygon"
"rectangle"
"bspline"
"ellipse"
"label"
"gimage"
"gevents"
"grabber"
"view"
"view-events"
"view-select"
"view-zoom"
"view-pan"
"utilities"
"save"
"restore"
(:module pict-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:pictures/" :compile))
)
(defun load-clue()
(load-system 'clue)
(purify))
(defun compile-it (thing)
(with-compilation-unit
(:optimize
'(optimize
(ext:inhibit-warnings 3)
(debug #-(or high-security small) 2
#+(and small (not high-security)) .5
#+high-security 3)
( speed 2 ) ( inhibit - warnings 3 )
(safety #-(or high-security small) 1
#+(and small (not high-security)) 0
#+high-security 3)
)
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(compile-system thing)))
(defun compile-all()
(with-compilation-unit
(:optimize
'(optimize
( ext : inhibit - warnings 3 )
(debug #-small 2 #+small .5)
(speed 2) (inhibit-warnings 3)
(safety #-small 1 #+small 1)
)
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(compile-system 'graphics)))
(unintern 'name)
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/defsys.lisp | lisp | Don't warn about botched values decls
Define packages
Modify xlib:create-window
pointer documentation window support
pw adds
The "guts"
Resource and type conversion
Gray stipple patterns
Standard cursor names
Event handling
Support for windowless contacts
Support for top-level window/session mgr.
interactive-stream (non-portable!!)
External cluei symbols exported from clue
these have circular dependencies | (in-package :user)
(defparameter *here* (make-pathname
:directory (pathname-directory *load-truename*)))
(pushnew 'compile pcl::*defclass-times*)
(pushnew 'compile pcl::*defgeneric-times*)
(defvar *clx-directory* "target:clx/*")
(defvar *clue-directory* (merge-pathnames "clue/" *here*))
(setf (search-list "clue:") (list *here*))
(setf c:*suppress-values-declaration* t)
(pushnew 'values pcl::*non-variable-declarations*)
Ensure * features * knows about CLOS and PCL
(when (find-package 'pcl)
(pushnew :pcl *features*)
(pushnew :clos *features*)
(unless (find-package :clos)
(rename-package :pcl :pcl '(:clos))))
(when (find-package 'clos)
(pushnew :clos *features*))
Ensure * features * knows about the Common Lisp Error Handler
(when (find-package 'conditions)
(pushnew :cleh *features*))
handle PCL 's precompile " feature "
(defun hack-precom (path op &optional (pathname "precom"))
(declare (type (member :compile :load :ignore) op))
(let* ((src (merge-pathnames (make-pathname :name pathname :type "lisp")
path))
(obj (compile-file-pathname src)))
( format t " ~ & ~a ~a ~a ~a~% " path op pathname )
(case op
(:compile
(when (probe-file src)
(unless (probe-file obj)
(compile-file src))))
(:load
(when (probe-file obj)
(load obj))))))
(defsystem
clx
(:default-pathname "target:clx/")
"macros"
"bufmac")
(defvar *clue-precom* "clue:clue/precom")
(defvar *pict-precom* "clue:pictures/precom")
(when (probe-file "clue:patch.lisp")
(load "clue:patch" :if-source-newer :compile))
(defsystem
clue
(:default-pathname "clue:clue/"
:needed-systems (clx) )
#+nil"common-lisp"
(:module clue-precom-load
:load-form (hack-precom "clue:clue/" :load)
:compile-form t)
Utilities for event translation
CLOS for resources and type conversion
Support for gcontext , pixmap , cursor
Geometry management methods for root contacts
(:module clue-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:clue/" :compile))
)
(defsystem
clio
(:needed-systems ( clue )
:default-pathname "clue:clio/"
:components
"clio"
"defgeneric"
(:module clio-precom-load
:load-form (hack-precom "clue:clio/" :load)
:compile-form t)
"ol-defs"
"utility"
"core-mixins"
"gravity"
"ol-images"
"buttons"
"form"
"table"
"choices"
"scroller"
"slider"
"scroll-frame"
"mchoices"
"menu"
"psheet"
"command"
"confirm"
"buffer"
"text-command"
"display-text"
"edit-text"
"display-imag"
"dlog-button"
(:module clio-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:clio/" :compile))
))
(defsystem
clio-examples
(:default-pathname "clue:clio/examples/")
"package" "cmd-frame" "sketchpad" "sketch")
(defsystem
pictures
( :default-pathname "clue:pictures/"
:needed-systems (clue ))
"package"
(:module pict-precom-load
:load-form (hack-precom "clue:pictures/" :load)
:compile-form t)
"defgeneric"
"types"
"macros"
"sequence"
"transform"
"extent"
"edge"
"class-def" :needed-systems ("edge" "extent")
"gstate" :needed-systems ("class-def")
"gstack"
"graphic"
"font-family"
"view-draw"
"scene"
"line"
"circle"
"polypoint"
"polygon"
"rectangle"
"bspline"
"ellipse"
"label"
"gimage"
"gevents"
"grabber"
"view"
"view-events"
"view-select"
"view-zoom"
"view-pan"
"utilities"
"save"
"restore"
(:module pict-precom-com
:load-form t
:compile-only t
:compile-form (hack-precom "clue:pictures/" :compile))
)
(defun load-clue()
(load-system 'clue)
(purify))
(defun compile-it (thing)
(with-compilation-unit
(:optimize
'(optimize
(ext:inhibit-warnings 3)
(debug #-(or high-security small) 2
#+(and small (not high-security)) .5
#+high-security 3)
( speed 2 ) ( inhibit - warnings 3 )
(safety #-(or high-security small) 1
#+(and small (not high-security)) 0
#+high-security 3)
)
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(compile-system thing)))
(defun compile-all()
(with-compilation-unit
(:optimize
'(optimize
( ext : inhibit - warnings 3 )
(debug #-small 2 #+small .5)
(speed 2) (inhibit-warnings 3)
(safety #-small 1 #+small 1)
)
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(compile-system 'graphics)))
(unintern 'name)
|
b18ef625d778239728af29eb5f39eed72fc76231637a433f5b11a4d426afaa37 | tmattio/js-bindings | node_path.mli | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es2020
module Path : sig
module ParsedPath : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val root : t -> string [@@js.get "root"]
val set_root : t -> string -> unit [@@js.set "root"]
val dir : t -> string [@@js.get "dir"]
val set_dir : t -> string -> unit [@@js.set "dir"]
val base : t -> string [@@js.get "base"]
val set_base : t -> string -> unit [@@js.set "base"]
val ext : t -> string [@@js.get "ext"]
val set_ext : t -> string -> unit [@@js.set "ext"]
val name : t -> string [@@js.get "name"]
val set_name : t -> string -> unit [@@js.set "name"]
end
[@@js.scope "ParsedPath"]
module FormatInputPathObject : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val root : t -> string [@@js.get "root"]
val set_root : t -> string -> unit [@@js.set "root"]
val dir : t -> string [@@js.get "dir"]
val set_dir : t -> string -> unit [@@js.set "dir"]
val base : t -> string [@@js.get "base"]
val set_base : t -> string -> unit [@@js.set "base"]
val ext : t -> string [@@js.get "ext"]
val set_ext : t -> string -> unit [@@js.set "ext"]
val name : t -> string [@@js.get "name"]
val set_name : t -> string -> unit [@@js.set "name"]
end
[@@js.scope "FormatInputPathObject"]
module PlatformPath : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val normalize : t -> string -> string [@@js.call "normalize"]
val join : t -> (string list[@js.variadic]) -> string [@@js.call "join"]
val resolve : t -> (string list[@js.variadic]) -> string
[@@js.call "resolve"]
val is_absolute : t -> string -> bool [@@js.call "isAbsolute"]
val relative : t -> from:string -> to_:string -> string
[@@js.call "relative"]
val dirname : t -> string -> string [@@js.call "dirname"]
val basename : t -> string -> ?ext:string -> unit -> string
[@@js.call "basename"]
val extname : t -> string -> string [@@js.call "extname"]
val sep : t -> string [@@js.get "sep"]
val delimiter : t -> string [@@js.get "delimiter"]
val parse : t -> string -> ParsedPath.t [@@js.call "parse"]
val format : t -> FormatInputPathObject.t -> string [@@js.call "format"]
val to_namespaced_path : t -> string -> string
[@@js.call "toNamespacedPath"]
val posix : t -> t [@@js.get "posix"]
val win32 : t -> t [@@js.get "win32"]
end
[@@js.scope "PlatformPath"]
val normalize : string -> string [@@js.global "normalize"]
val join : (string list[@js.variadic]) -> string [@@js.global "join"]
val resolve : (string list[@js.variadic]) -> string [@@js.global "resolve"]
val is_absolute : string -> bool [@@js.global "isAbsolute"]
val relative : from:string -> to_:string -> string [@@js.global "relative"]
val dirname : string -> string [@@js.global "dirname"]
val basename : string -> ?ext:string -> unit -> string
[@@js.global "basename"]
val extname : string -> string [@@js.global "extname"]
val sep : string [@@js.global "sep"]
val delimiter : string [@@js.global "delimiter"]
val parse : string -> ParsedPath.t [@@js.global "parse"]
val format : FormatInputPathObject.t -> string [@@js.global "format"]
val to_namespaced_path : string -> string [@@js.call "toNamespacedPath"]
end
[@@js.scope Import.path]
| null | https://raw.githubusercontent.com/tmattio/js-bindings/ca3bd6a12db519c8de7f41b303f14cf70cfd4c5f/lib/node/node_path.mli | ocaml | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es2020
module Path : sig
module ParsedPath : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val root : t -> string [@@js.get "root"]
val set_root : t -> string -> unit [@@js.set "root"]
val dir : t -> string [@@js.get "dir"]
val set_dir : t -> string -> unit [@@js.set "dir"]
val base : t -> string [@@js.get "base"]
val set_base : t -> string -> unit [@@js.set "base"]
val ext : t -> string [@@js.get "ext"]
val set_ext : t -> string -> unit [@@js.set "ext"]
val name : t -> string [@@js.get "name"]
val set_name : t -> string -> unit [@@js.set "name"]
end
[@@js.scope "ParsedPath"]
module FormatInputPathObject : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val root : t -> string [@@js.get "root"]
val set_root : t -> string -> unit [@@js.set "root"]
val dir : t -> string [@@js.get "dir"]
val set_dir : t -> string -> unit [@@js.set "dir"]
val base : t -> string [@@js.get "base"]
val set_base : t -> string -> unit [@@js.set "base"]
val ext : t -> string [@@js.get "ext"]
val set_ext : t -> string -> unit [@@js.set "ext"]
val name : t -> string [@@js.get "name"]
val set_name : t -> string -> unit [@@js.set "name"]
end
[@@js.scope "FormatInputPathObject"]
module PlatformPath : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val normalize : t -> string -> string [@@js.call "normalize"]
val join : t -> (string list[@js.variadic]) -> string [@@js.call "join"]
val resolve : t -> (string list[@js.variadic]) -> string
[@@js.call "resolve"]
val is_absolute : t -> string -> bool [@@js.call "isAbsolute"]
val relative : t -> from:string -> to_:string -> string
[@@js.call "relative"]
val dirname : t -> string -> string [@@js.call "dirname"]
val basename : t -> string -> ?ext:string -> unit -> string
[@@js.call "basename"]
val extname : t -> string -> string [@@js.call "extname"]
val sep : t -> string [@@js.get "sep"]
val delimiter : t -> string [@@js.get "delimiter"]
val parse : t -> string -> ParsedPath.t [@@js.call "parse"]
val format : t -> FormatInputPathObject.t -> string [@@js.call "format"]
val to_namespaced_path : t -> string -> string
[@@js.call "toNamespacedPath"]
val posix : t -> t [@@js.get "posix"]
val win32 : t -> t [@@js.get "win32"]
end
[@@js.scope "PlatformPath"]
val normalize : string -> string [@@js.global "normalize"]
val join : (string list[@js.variadic]) -> string [@@js.global "join"]
val resolve : (string list[@js.variadic]) -> string [@@js.global "resolve"]
val is_absolute : string -> bool [@@js.global "isAbsolute"]
val relative : from:string -> to_:string -> string [@@js.global "relative"]
val dirname : string -> string [@@js.global "dirname"]
val basename : string -> ?ext:string -> unit -> string
[@@js.global "basename"]
val extname : string -> string [@@js.global "extname"]
val sep : string [@@js.global "sep"]
val delimiter : string [@@js.global "delimiter"]
val parse : string -> ParsedPath.t [@@js.global "parse"]
val format : FormatInputPathObject.t -> string [@@js.global "format"]
val to_namespaced_path : string -> string [@@js.call "toNamespacedPath"]
end
[@@js.scope Import.path]
|
|
14dfe93a397a81b050de82aa86d6259af9332e3d58229f83c79045b043e6d335 | project-oak/hafnium-verification | procCfgTests.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
module BackwardCfg = ProcCfg.Backward (ProcCfg.Normal)
module InstrCfg = ProcCfg.OneInstrPerNode (ProcCfg.Normal)
module BackwardInstrCfg = ProcCfg.Backward (InstrCfg)
let tests =
let cfg = Cfg.create () in
let test_pdesc =
Cfg.create_proc_desc cfg
(ProcAttributes.default (SourceFile.invalid __FILE__) Procname.empty_block)
in
let dummy_instr1 = Sil.skip_instr in
let dummy_instr2 = Sil.Metadata (Abstract Location.dummy) in
let dummy_instr3 =
Sil.Metadata (ExitScope ([Var.of_id (Ident.create_fresh Ident.knormal)], Location.dummy))
in
let dummy_instr4 = Sil.skip_instr in
let instrs1 = [dummy_instr1; dummy_instr2] in
let instrs2 = [dummy_instr3] in
let instrs3 = [dummy_instr4] in
let instrs4 = [] in
let create_node instrs =
Procdesc.create_node test_pdesc Location.dummy (Procdesc.Node.Stmt_node (Skip "")) instrs
in
let n1 = create_node instrs1 in
let n2 = create_node instrs2 in
let n3 = create_node instrs3 in
let n4 = create_node instrs4 in
Procdesc.set_start_node test_pdesc n1 ;
(* let -> represent normal transitions and -*-> represent exceptional transitions *)
(* creating graph n1 -> n2, n1 -*-> n3, n2 -> n4, n2 -*-> n3, n3 -> n4 , n3 -*> n4 *)
Procdesc.node_set_succs test_pdesc n1 ~normal:[n2] ~exn:[n3] ;
Procdesc.node_set_succs test_pdesc n2 ~normal:[n4] ~exn:[n3] ;
Procdesc.node_set_succs test_pdesc n3 ~normal:[n4] ~exn:[n4] ;
let normal_proc_cfg = ProcCfg.Normal.from_pdesc test_pdesc in
let exceptional_proc_cfg = ProcCfg.Exceptional.from_pdesc test_pdesc in
let backward_proc_cfg = BackwardCfg.from_pdesc test_pdesc in
let backward_instr_proc_cfg = BackwardInstrCfg.from_pdesc test_pdesc in
let open OUnit2 in
let cmp l1 l2 =
let sort = List.sort ~compare:Procdesc.Node.compare in
List.equal Procdesc.Node.equal (sort l1) (sort l2)
in
let pp_diff fmt (actual, expected) =
let pp_sep fmt _ = F.pp_print_char fmt ',' in
let pp_node_list fmt l = F.pp_print_list ~pp_sep Procdesc.Node.pp fmt l in
F.fprintf fmt "Expected output %a but got %a" pp_node_list expected pp_node_list actual
in
let create_test ~fold input expected _ =
let input = Container.to_list input ~fold in
assert_equal ~cmp ~pp_diff input expected
in
let instr_test =
let instr_test_ _ =
let list_of_instrs instrs = Instrs.fold instrs ~init:[] ~f:(fun l i -> i :: l) |> List.rev in
( match ProcCfg.Normal.instrs n1 |> list_of_instrs with
| [instr1; instr2] ->
assert_bool "First instr should be dummy_instr1" (phys_equal instr1 dummy_instr1) ;
assert_bool "Second instr should be dummy_instr2" (phys_equal instr2 dummy_instr2)
| _ ->
assert_failure "Expected exactly two instructions" ) ;
( match BackwardCfg.instrs n1 |> list_of_instrs with
| [instr1; instr2] ->
assert_bool "First instr should be dummy_instr2" (phys_equal instr1 dummy_instr2) ;
assert_bool "Second instr should be dummy_instr1" (phys_equal instr2 dummy_instr1)
| _ ->
assert_failure "Expected exactly two instructions" ) ;
let instr_n1 = InstrCfg.Node.of_underlying_node n1 in
( match InstrCfg.instrs instr_n1 |> list_of_instrs with
| [instr] ->
assert_bool "Only instr should be dummy_instr1" (phys_equal instr dummy_instr1)
| _ ->
assert_failure "Expected exactly one instruction" ) ;
let n1' = InstrCfg.Node.underlying_node instr_n1 in
assert_bool "underlying_node should return node of underlying CFG type" (phys_equal n1 n1') ;
let backward_instr_n1 = BackwardInstrCfg.Node.of_underlying_node n1 in
( match BackwardInstrCfg.instrs backward_instr_n1 |> list_of_instrs with
| [instr] ->
assert_bool "Only instr should be dummy_instr1" (phys_equal instr dummy_instr1)
| _ ->
assert_failure "Expected exactly one instruction" ) ;
let n1'' = BackwardInstrCfg.Node.underlying_node backward_instr_n1 in
assert_bool "underlying_node should return node of underlying CFG type" (phys_equal n1 n1'') ;
(* test the preds/succs using backward + instr cfg *)
let check_backward_instr_ fold backward_instr_node expected_instrs =
match Container.to_list ~fold:(fold backward_instr_proc_cfg) backward_instr_node with
| [n] ->
assert_equal (BackwardInstrCfg.instrs n) (expected_instrs |> Instrs.reverse_order)
| _ ->
assert_failure "Expected exactly one node"
in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n1
(Instrs.singleton dummy_instr2) ;
let backward_instr_n2 = BackwardInstrCfg.Node.of_underlying_node n2 in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n2 Instrs.empty ;
let backward_instr_n3 = BackwardInstrCfg.Node.of_underlying_node n3 in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n3 Instrs.empty ;
check_backward_instr_ BackwardInstrCfg.fold_normal_succs backward_instr_n2
(Instrs.singleton dummy_instr2)
in
"instr_test" >:: instr_test_
in
let graph_tests =
[ (* test the succs of the normal cfg. forward... *)
("succs_n1", ProcCfg.Normal.fold_succs normal_proc_cfg, n1, [n2])
; ("normal_succs_n1", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n1, [n2])
; ("succs_n2", ProcCfg.Normal.fold_succs normal_proc_cfg, n2, [n4])
; ("normal_succs_n2", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n2, [n4])
; ("succs_n3", ProcCfg.Normal.fold_succs normal_proc_cfg, n3, [n4])
; ("normal_succs_n3", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n3, [n4])
; (* ... and backward... *)
("succs_n1_bw", BackwardCfg.fold_preds backward_proc_cfg, n1, [n2])
; ("normal_succs_n1_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n1, [n2])
; ("succs_n2_bw", BackwardCfg.fold_preds backward_proc_cfg, n2, [n4])
; ("normal_succs_n2_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n2, [n4])
; ("succs_n3_bw", BackwardCfg.fold_preds backward_proc_cfg, n3, [n4])
; ("normal_succs_n3_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n3, [n4])
test the of the normal cfg ...
("preds_n2", ProcCfg.Normal.fold_normal_preds normal_proc_cfg, n2, [n1])
; ("normal_preds_n2", ProcCfg.Normal.fold_normal_preds normal_proc_cfg, n2, [n1])
; (* ...and the backward cfg... *)
("preds_n2_bw", BackwardCfg.fold_normal_succs backward_proc_cfg, n2, [n1])
; ("normal_preds_n2_bw", BackwardCfg.fold_normal_succs backward_proc_cfg, n2, [n1])
we should n't see any exn succs or even though we added them
("no_exn_succs_n1", ProcCfg.Normal.fold_exceptional_succs normal_proc_cfg, n1, [])
; ("no_exn_preds_n3", ProcCfg.Normal.fold_exceptional_preds normal_proc_cfg, n3, [])
; (* same in the backward cfg *)
("no_exn_succs_n1_bw", BackwardCfg.fold_exceptional_preds backward_proc_cfg, n1, [])
; ("no_exn_preds_n3_bw", BackwardCfg.fold_exceptional_succs backward_proc_cfg, n3, [])
; (* now, test the exceptional succs in the exceptional cfg. *)
("exn_succs_n1", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n1, [n3])
; ("exn_succs_n2", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n2, [n3])
; ("exn_succs_n3", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n3, [n4])
; (* test exceptional pred links *)
("exn_preds_n3", ProcCfg.Exceptional.fold_exceptional_preds exceptional_proc_cfg, n3, [n2; n1])
; (* succs should return both normal and exceptional successors *)
("exn_all_succs_n1", ProcCfg.Exceptional.fold_succs exceptional_proc_cfg, n1, [n3; n2])
; (* but, should not return duplicates *)
("exn_all_succs_n3", ProcCfg.Exceptional.fold_succs exceptional_proc_cfg, n3, [n4])
similarly , should return both normal and exceptional predecessors
("exn_all_preds_n3", ProcCfg.Exceptional.fold_preds exceptional_proc_cfg, n3, [n2; n1])
; ("exn_all_preds_n4", ProcCfg.Exceptional.fold_preds exceptional_proc_cfg, n4, [n3; n2])
; (* finally, normal_succs/normal_preds shouldn't return exceptional edges *)
("exn_normal_succs_n1", ProcCfg.Exceptional.fold_normal_succs exceptional_proc_cfg, n1, [n2])
; ("exn_normal_preds_n2", ProcCfg.Exceptional.fold_normal_preds exceptional_proc_cfg, n2, [n1])
]
|> List.map ~f:(fun (name, fold, input, expected) -> name >:: create_test ~fold input expected)
in
let tests = instr_test :: graph_tests in
"procCfgSuite" >::: tests
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/unit/procCfgTests.ml | ocaml | let -> represent normal transitions and -*-> represent exceptional transitions
creating graph n1 -> n2, n1 -*-> n3, n2 -> n4, n2 -*-> n3, n3 -> n4 , n3 -*> n4
test the preds/succs using backward + instr cfg
test the succs of the normal cfg. forward...
... and backward...
...and the backward cfg...
same in the backward cfg
now, test the exceptional succs in the exceptional cfg.
test exceptional pred links
succs should return both normal and exceptional successors
but, should not return duplicates
finally, normal_succs/normal_preds shouldn't return exceptional edges |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
module BackwardCfg = ProcCfg.Backward (ProcCfg.Normal)
module InstrCfg = ProcCfg.OneInstrPerNode (ProcCfg.Normal)
module BackwardInstrCfg = ProcCfg.Backward (InstrCfg)
let tests =
let cfg = Cfg.create () in
let test_pdesc =
Cfg.create_proc_desc cfg
(ProcAttributes.default (SourceFile.invalid __FILE__) Procname.empty_block)
in
let dummy_instr1 = Sil.skip_instr in
let dummy_instr2 = Sil.Metadata (Abstract Location.dummy) in
let dummy_instr3 =
Sil.Metadata (ExitScope ([Var.of_id (Ident.create_fresh Ident.knormal)], Location.dummy))
in
let dummy_instr4 = Sil.skip_instr in
let instrs1 = [dummy_instr1; dummy_instr2] in
let instrs2 = [dummy_instr3] in
let instrs3 = [dummy_instr4] in
let instrs4 = [] in
let create_node instrs =
Procdesc.create_node test_pdesc Location.dummy (Procdesc.Node.Stmt_node (Skip "")) instrs
in
let n1 = create_node instrs1 in
let n2 = create_node instrs2 in
let n3 = create_node instrs3 in
let n4 = create_node instrs4 in
Procdesc.set_start_node test_pdesc n1 ;
Procdesc.node_set_succs test_pdesc n1 ~normal:[n2] ~exn:[n3] ;
Procdesc.node_set_succs test_pdesc n2 ~normal:[n4] ~exn:[n3] ;
Procdesc.node_set_succs test_pdesc n3 ~normal:[n4] ~exn:[n4] ;
let normal_proc_cfg = ProcCfg.Normal.from_pdesc test_pdesc in
let exceptional_proc_cfg = ProcCfg.Exceptional.from_pdesc test_pdesc in
let backward_proc_cfg = BackwardCfg.from_pdesc test_pdesc in
let backward_instr_proc_cfg = BackwardInstrCfg.from_pdesc test_pdesc in
let open OUnit2 in
let cmp l1 l2 =
let sort = List.sort ~compare:Procdesc.Node.compare in
List.equal Procdesc.Node.equal (sort l1) (sort l2)
in
let pp_diff fmt (actual, expected) =
let pp_sep fmt _ = F.pp_print_char fmt ',' in
let pp_node_list fmt l = F.pp_print_list ~pp_sep Procdesc.Node.pp fmt l in
F.fprintf fmt "Expected output %a but got %a" pp_node_list expected pp_node_list actual
in
let create_test ~fold input expected _ =
let input = Container.to_list input ~fold in
assert_equal ~cmp ~pp_diff input expected
in
let instr_test =
let instr_test_ _ =
let list_of_instrs instrs = Instrs.fold instrs ~init:[] ~f:(fun l i -> i :: l) |> List.rev in
( match ProcCfg.Normal.instrs n1 |> list_of_instrs with
| [instr1; instr2] ->
assert_bool "First instr should be dummy_instr1" (phys_equal instr1 dummy_instr1) ;
assert_bool "Second instr should be dummy_instr2" (phys_equal instr2 dummy_instr2)
| _ ->
assert_failure "Expected exactly two instructions" ) ;
( match BackwardCfg.instrs n1 |> list_of_instrs with
| [instr1; instr2] ->
assert_bool "First instr should be dummy_instr2" (phys_equal instr1 dummy_instr2) ;
assert_bool "Second instr should be dummy_instr1" (phys_equal instr2 dummy_instr1)
| _ ->
assert_failure "Expected exactly two instructions" ) ;
let instr_n1 = InstrCfg.Node.of_underlying_node n1 in
( match InstrCfg.instrs instr_n1 |> list_of_instrs with
| [instr] ->
assert_bool "Only instr should be dummy_instr1" (phys_equal instr dummy_instr1)
| _ ->
assert_failure "Expected exactly one instruction" ) ;
let n1' = InstrCfg.Node.underlying_node instr_n1 in
assert_bool "underlying_node should return node of underlying CFG type" (phys_equal n1 n1') ;
let backward_instr_n1 = BackwardInstrCfg.Node.of_underlying_node n1 in
( match BackwardInstrCfg.instrs backward_instr_n1 |> list_of_instrs with
| [instr] ->
assert_bool "Only instr should be dummy_instr1" (phys_equal instr dummy_instr1)
| _ ->
assert_failure "Expected exactly one instruction" ) ;
let n1'' = BackwardInstrCfg.Node.underlying_node backward_instr_n1 in
assert_bool "underlying_node should return node of underlying CFG type" (phys_equal n1 n1'') ;
let check_backward_instr_ fold backward_instr_node expected_instrs =
match Container.to_list ~fold:(fold backward_instr_proc_cfg) backward_instr_node with
| [n] ->
assert_equal (BackwardInstrCfg.instrs n) (expected_instrs |> Instrs.reverse_order)
| _ ->
assert_failure "Expected exactly one node"
in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n1
(Instrs.singleton dummy_instr2) ;
let backward_instr_n2 = BackwardInstrCfg.Node.of_underlying_node n2 in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n2 Instrs.empty ;
let backward_instr_n3 = BackwardInstrCfg.Node.of_underlying_node n3 in
check_backward_instr_ BackwardInstrCfg.fold_preds backward_instr_n3 Instrs.empty ;
check_backward_instr_ BackwardInstrCfg.fold_normal_succs backward_instr_n2
(Instrs.singleton dummy_instr2)
in
"instr_test" >:: instr_test_
in
let graph_tests =
("succs_n1", ProcCfg.Normal.fold_succs normal_proc_cfg, n1, [n2])
; ("normal_succs_n1", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n1, [n2])
; ("succs_n2", ProcCfg.Normal.fold_succs normal_proc_cfg, n2, [n4])
; ("normal_succs_n2", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n2, [n4])
; ("succs_n3", ProcCfg.Normal.fold_succs normal_proc_cfg, n3, [n4])
; ("normal_succs_n3", ProcCfg.Normal.fold_normal_succs normal_proc_cfg, n3, [n4])
("succs_n1_bw", BackwardCfg.fold_preds backward_proc_cfg, n1, [n2])
; ("normal_succs_n1_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n1, [n2])
; ("succs_n2_bw", BackwardCfg.fold_preds backward_proc_cfg, n2, [n4])
; ("normal_succs_n2_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n2, [n4])
; ("succs_n3_bw", BackwardCfg.fold_preds backward_proc_cfg, n3, [n4])
; ("normal_succs_n3_bw", BackwardCfg.fold_normal_preds backward_proc_cfg, n3, [n4])
test the of the normal cfg ...
("preds_n2", ProcCfg.Normal.fold_normal_preds normal_proc_cfg, n2, [n1])
; ("normal_preds_n2", ProcCfg.Normal.fold_normal_preds normal_proc_cfg, n2, [n1])
("preds_n2_bw", BackwardCfg.fold_normal_succs backward_proc_cfg, n2, [n1])
; ("normal_preds_n2_bw", BackwardCfg.fold_normal_succs backward_proc_cfg, n2, [n1])
we should n't see any exn succs or even though we added them
("no_exn_succs_n1", ProcCfg.Normal.fold_exceptional_succs normal_proc_cfg, n1, [])
; ("no_exn_preds_n3", ProcCfg.Normal.fold_exceptional_preds normal_proc_cfg, n3, [])
("no_exn_succs_n1_bw", BackwardCfg.fold_exceptional_preds backward_proc_cfg, n1, [])
; ("no_exn_preds_n3_bw", BackwardCfg.fold_exceptional_succs backward_proc_cfg, n3, [])
("exn_succs_n1", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n1, [n3])
; ("exn_succs_n2", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n2, [n3])
; ("exn_succs_n3", ProcCfg.Exceptional.fold_exceptional_succs exceptional_proc_cfg, n3, [n4])
("exn_preds_n3", ProcCfg.Exceptional.fold_exceptional_preds exceptional_proc_cfg, n3, [n2; n1])
("exn_all_succs_n1", ProcCfg.Exceptional.fold_succs exceptional_proc_cfg, n1, [n3; n2])
("exn_all_succs_n3", ProcCfg.Exceptional.fold_succs exceptional_proc_cfg, n3, [n4])
similarly , should return both normal and exceptional predecessors
("exn_all_preds_n3", ProcCfg.Exceptional.fold_preds exceptional_proc_cfg, n3, [n2; n1])
; ("exn_all_preds_n4", ProcCfg.Exceptional.fold_preds exceptional_proc_cfg, n4, [n3; n2])
("exn_normal_succs_n1", ProcCfg.Exceptional.fold_normal_succs exceptional_proc_cfg, n1, [n2])
; ("exn_normal_preds_n2", ProcCfg.Exceptional.fold_normal_preds exceptional_proc_cfg, n2, [n1])
]
|> List.map ~f:(fun (name, fold, input, expected) -> name >:: create_test ~fold input expected)
in
let tests = instr_test :: graph_tests in
"procCfgSuite" >::: tests
|
ea1be4031913c50e757a38a2ffe244917ce6181cc83cfb2138222c85b76308d8 | google-research/dex-lang | Compile.hs | Copyright 2022 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- -source/licenses/bsd
module LLVM.Compile
( compileLLVM, runPasses, standardCompilationPipeline
, LLVMOptLevel (..)) where
#ifdef DEX_DEBUG
import qualified LLVM.Analysis as L
#endif
import qualified LLVM.AST as L
import qualified LLVM.AST.Global as GL
import qualified LLVM.Module as Mod
import qualified LLVM.Internal.Module as Mod
#if MIN_VERSION_llvm_hs(15,0,0)
import qualified LLVM.Passes as P
#else
import qualified LLVM.PassManager as P
import qualified LLVM.Transforms as P
#endif
import qualified LLVM.Target as T
import qualified LLVM.Shims
import LLVM.Context
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B
import System.IO.Unsafe
import Control.Monad
import Logging
import PPrint ()
import Paths_dex (getDataFileName)
import Types.Misc
-- The only reason this module depends on Types.Source is that we pass in the logger,
in order to optionally print out the IRs . mutates its IRs in - place , so
-- we can't just expose a functional API for each stage without taking a
-- performance hit. But maybe the performance hit isn't so bad?
import Types.Source
data LLVMOptLevel = OptALittle -- -O1
| OptAggressively -- -O3, incl. auto vectorization
deriving Show
compileLLVM :: PassLogger -> LLVMOptLevel -> L.Module -> String -> IO BS.ByteString
compileLLVM logger opt ast exportName = do
tm <- LLVM.Shims.newDefaultHostTargetMachine
withContext \c -> do
Mod.withModuleFromAST c ast \m -> do
standardCompilationPipeline opt
logger
[exportName] tm m
Mod.moduleObject tm m
= = = = = =
runDefaultPasses :: LLVMOptLevel -> T.TargetMachine -> Mod.Module -> IO ()
runDefaultPasses opt t m = do
#if MIN_VERSION_llvm_hs(15,0,0)
-- TODO: Modify llvm-hs to request vectorization
P.runPasses (P.PassSetSpec [P.CuratedPassSet lvl] (Just t)) m
where lvl = case opt of OptALittle -> 1; OptAggressively -> 3
#else
P.withPassManager defaultPasses \pm -> void $ P.runPassManager pm m
case extraPasses of
[] -> return ()
_ -> runPasses extraPasses (Just t) m
where
defaultPasses = case opt of
OptALittle ->
P.defaultCuratedPassSetSpec {P.optLevel = Just 1, P.targetMachine = Just t}
OptAggressively ->
P.defaultCuratedPassSetSpec
{ P.optLevel = Just 3
, P.loopVectorize = Just True
, P.superwordLevelParallelismVectorize = Just True
, P.targetMachine = Just t }
extraPasses = []
#endif
#if MIN_VERSION_llvm_hs(15,0,0)
runPasses :: [P.ModulePass] -> Maybe T.TargetMachine -> Mod.Module -> IO ()
runPasses passes mt m = P.runPasses (P.PassSetSpec passes mt) m
#else
runPasses :: [P.Pass] -> Maybe T.TargetMachine -> Mod.Module -> IO ()
runPasses passes mt m = do
dl <- case mt of
Just t -> Just <$> T.getTargetMachineDataLayout t
Nothing -> return Nothing
let passSpec = P.PassSetSpec passes dl Nothing mt
P.withPassManager passSpec \pm -> void $ P.runPassManager pm m
#endif
standardCompilationPipeline :: LLVMOptLevel -> PassLogger -> [String] -> T.TargetMachine -> Mod.Module -> IO ()
standardCompilationPipeline opt logger exports tm m = do
-- TODO: this means we build a copy of dexrt for every function. Is that
-- really necessary?
linkDexrt m
internalize exports m
# SCC showLLVM #
#ifdef DEX_DEBUG
{-# SCC verifyLLVM #-} L.verify m
#endif
# SCC runPasses #
# SCC showOptimizedLLVM #
# SCC showAssembly #
where
logPass :: PassName -> IO String -> IO ()
logPass passName cont = logFiltered logger passName $ cont >>= \s -> return [PassInfo passName s]
# SCC standardCompilationPipeline #
internalize :: [String] -> Mod.Module -> IO ()
internalize names m = runPasses [P.InternalizeFunctions names, P.GlobalDeadCodeElimination] Nothing m
-- === dex runtime ===
# NOINLINE dexrtAST #
dexrtAST :: L.Module
dexrtAST = unsafePerformIO $ do
dexrtBC <- B.readFile =<< getDataFileName "src/lib/dexrt.bc"
withContext \ctx -> do
Mod.withModuleFromBitcode ctx (("dexrt.c" :: String), dexrtBC) \m ->
stripFunctionAnnotations <$> Mod.moduleAST m
where
-- We strip the function annotations for dexrt functions, because clang
-- usually assumes that it's compiling for some generic CPU instead of the
-- target that we select here. That creates a lot of confusion, making
-- optimizations much less effective.
stripFunctionAnnotations ast =
ast { L.moduleDefinitions = stripDef <$> L.moduleDefinitions ast }
stripDef def@(L.GlobalDefinition {..}) = case basicBlocks of
[] -> def
_ -> L.GlobalDefinition $ f { GL.functionAttributes = [] }
stripDef def = def
linkDexrt :: Mod.Module -> IO ()
linkDexrt m = do
ctx <- Mod.moduleContext m
dataLayout <- Mod.getDataLayout =<< Mod.readModule m
targetTriple <- Mod.getTargetTriple =<< Mod.readModule m
let dexrtTargetAST = dexrtAST { L.moduleDataLayout = dataLayout
, L.moduleTargetTriple = targetTriple }
Mod.withModuleFromAST ctx dexrtTargetAST \dexrtm -> do
Mod.linkModules m dexrtm
runPasses [P.AlwaysInline True] Nothing m
-- === printing ===
showModule :: Mod.Module -> IO String
showModule m = B.unpack <$> Mod.moduleLLVMAssembly m
showAsm :: T.TargetMachine -> Mod.Module -> IO String
showAsm t m' = do
ctx <- Mod.moduleContext m'
-- Uncomment this to dump assembly to a file that can be linked to a C benchmark suite:
withModuleClone \m - > Mod.writeObjectToFile t ( Mod . File " asm.o " ) m
withModuleClone ctx m' \m -> B.unpack <$> Mod.moduleTargetAssembly t m
withModuleClone :: Context -> Mod.Module -> (Mod.Module -> IO a) -> IO a
withModuleClone ctx m f = do
-- It would be better to go through bitcode, but apparently that doesn't work...
bc <- Mod.moduleLLVMAssembly m
Mod.withModuleFromLLVMAssembly ctx (("<string>" :: String), bc) f
| null | https://raw.githubusercontent.com/google-research/dex-lang/2a8f44475e95b9bc235bcd8b6eecbab411a91784/src/lib/LLVM/Compile.hs | haskell |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
-source/licenses/bsd
The only reason this module depends on Types.Source is that we pass in the logger,
we can't just expose a functional API for each stage without taking a
performance hit. But maybe the performance hit isn't so bad?
-O1
-O3, incl. auto vectorization
TODO: Modify llvm-hs to request vectorization
TODO: this means we build a copy of dexrt for every function. Is that
really necessary?
# SCC verifyLLVM #
=== dex runtime ===
We strip the function annotations for dexrt functions, because clang
usually assumes that it's compiling for some generic CPU instead of the
target that we select here. That creates a lot of confusion, making
optimizations much less effective.
=== printing ===
Uncomment this to dump assembly to a file that can be linked to a C benchmark suite:
It would be better to go through bitcode, but apparently that doesn't work... | Copyright 2022 Google LLC
module LLVM.Compile
( compileLLVM, runPasses, standardCompilationPipeline
, LLVMOptLevel (..)) where
#ifdef DEX_DEBUG
import qualified LLVM.Analysis as L
#endif
import qualified LLVM.AST as L
import qualified LLVM.AST.Global as GL
import qualified LLVM.Module as Mod
import qualified LLVM.Internal.Module as Mod
#if MIN_VERSION_llvm_hs(15,0,0)
import qualified LLVM.Passes as P
#else
import qualified LLVM.PassManager as P
import qualified LLVM.Transforms as P
#endif
import qualified LLVM.Target as T
import qualified LLVM.Shims
import LLVM.Context
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B
import System.IO.Unsafe
import Control.Monad
import Logging
import PPrint ()
import Paths_dex (getDataFileName)
import Types.Misc
in order to optionally print out the IRs . mutates its IRs in - place , so
import Types.Source
deriving Show
compileLLVM :: PassLogger -> LLVMOptLevel -> L.Module -> String -> IO BS.ByteString
compileLLVM logger opt ast exportName = do
tm <- LLVM.Shims.newDefaultHostTargetMachine
withContext \c -> do
Mod.withModuleFromAST c ast \m -> do
standardCompilationPipeline opt
logger
[exportName] tm m
Mod.moduleObject tm m
= = = = = =
runDefaultPasses :: LLVMOptLevel -> T.TargetMachine -> Mod.Module -> IO ()
runDefaultPasses opt t m = do
#if MIN_VERSION_llvm_hs(15,0,0)
P.runPasses (P.PassSetSpec [P.CuratedPassSet lvl] (Just t)) m
where lvl = case opt of OptALittle -> 1; OptAggressively -> 3
#else
P.withPassManager defaultPasses \pm -> void $ P.runPassManager pm m
case extraPasses of
[] -> return ()
_ -> runPasses extraPasses (Just t) m
where
defaultPasses = case opt of
OptALittle ->
P.defaultCuratedPassSetSpec {P.optLevel = Just 1, P.targetMachine = Just t}
OptAggressively ->
P.defaultCuratedPassSetSpec
{ P.optLevel = Just 3
, P.loopVectorize = Just True
, P.superwordLevelParallelismVectorize = Just True
, P.targetMachine = Just t }
extraPasses = []
#endif
#if MIN_VERSION_llvm_hs(15,0,0)
runPasses :: [P.ModulePass] -> Maybe T.TargetMachine -> Mod.Module -> IO ()
runPasses passes mt m = P.runPasses (P.PassSetSpec passes mt) m
#else
runPasses :: [P.Pass] -> Maybe T.TargetMachine -> Mod.Module -> IO ()
runPasses passes mt m = do
dl <- case mt of
Just t -> Just <$> T.getTargetMachineDataLayout t
Nothing -> return Nothing
let passSpec = P.PassSetSpec passes dl Nothing mt
P.withPassManager passSpec \pm -> void $ P.runPassManager pm m
#endif
standardCompilationPipeline :: LLVMOptLevel -> PassLogger -> [String] -> T.TargetMachine -> Mod.Module -> IO ()
standardCompilationPipeline opt logger exports tm m = do
linkDexrt m
internalize exports m
# SCC showLLVM #
#ifdef DEX_DEBUG
#endif
# SCC runPasses #
# SCC showOptimizedLLVM #
# SCC showAssembly #
where
logPass :: PassName -> IO String -> IO ()
logPass passName cont = logFiltered logger passName $ cont >>= \s -> return [PassInfo passName s]
# SCC standardCompilationPipeline #
internalize :: [String] -> Mod.Module -> IO ()
internalize names m = runPasses [P.InternalizeFunctions names, P.GlobalDeadCodeElimination] Nothing m
# NOINLINE dexrtAST #
dexrtAST :: L.Module
dexrtAST = unsafePerformIO $ do
dexrtBC <- B.readFile =<< getDataFileName "src/lib/dexrt.bc"
withContext \ctx -> do
Mod.withModuleFromBitcode ctx (("dexrt.c" :: String), dexrtBC) \m ->
stripFunctionAnnotations <$> Mod.moduleAST m
where
stripFunctionAnnotations ast =
ast { L.moduleDefinitions = stripDef <$> L.moduleDefinitions ast }
stripDef def@(L.GlobalDefinition {..}) = case basicBlocks of
[] -> def
_ -> L.GlobalDefinition $ f { GL.functionAttributes = [] }
stripDef def = def
linkDexrt :: Mod.Module -> IO ()
linkDexrt m = do
ctx <- Mod.moduleContext m
dataLayout <- Mod.getDataLayout =<< Mod.readModule m
targetTriple <- Mod.getTargetTriple =<< Mod.readModule m
let dexrtTargetAST = dexrtAST { L.moduleDataLayout = dataLayout
, L.moduleTargetTriple = targetTriple }
Mod.withModuleFromAST ctx dexrtTargetAST \dexrtm -> do
Mod.linkModules m dexrtm
runPasses [P.AlwaysInline True] Nothing m
showModule :: Mod.Module -> IO String
showModule m = B.unpack <$> Mod.moduleLLVMAssembly m
showAsm :: T.TargetMachine -> Mod.Module -> IO String
showAsm t m' = do
ctx <- Mod.moduleContext m'
withModuleClone \m - > Mod.writeObjectToFile t ( Mod . File " asm.o " ) m
withModuleClone ctx m' \m -> B.unpack <$> Mod.moduleTargetAssembly t m
withModuleClone :: Context -> Mod.Module -> (Mod.Module -> IO a) -> IO a
withModuleClone ctx m f = do
bc <- Mod.moduleLLVMAssembly m
Mod.withModuleFromLLVMAssembly ctx (("<string>" :: String), bc) f
|
f01f1c38b0d15f89f03dea6dd6bc3bc1d48c6fa2fa4802c1492d9a725c2c7982 | hjcapple/reading-sicp | exercise_3_78.scm | #lang racket
P242 - [ 练习 3.78 ]
(require "stream.scm")
(require "infinite_stream.scm")
(define (integral delayed-integrand initial-value dt)
(define int
(cons-stream initial-value
(let ((integrand (force delayed-integrand)))
(add-streams (scale-stream integrand dt)
int))))
int)
(define (solve-2nd a b dt y0 dy0)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (add-streams (scale-stream dy a)
(scale-stream y b)))
y)
;;;;;;;;;;;;;;;;;
ddy + 2 * dy + y = 0
y(0 ) = 4 , dy(0 ) = -2
(displayln "solve-2nd")
(display-stream-n (solve-2nd -2 -1 0.001 4 -2) 20)
上面微分方程,特解为 y = ( 4 + 2 t ) * exp(-t ) , 直接打印出方程值作对比
(define (solution t)
(* (+ 4 (* 2 t)) (exp (- t))))
(define (solution-steam t dt)
(cons-stream (solution t) (solution-steam (+ t dt) dt)))
(displayln "solution")
(display-stream-n (solution-steam 0 0.001) 20)
| null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_3/exercise_3_78.scm | scheme | #lang racket
P242 - [ 练习 3.78 ]
(require "stream.scm")
(require "infinite_stream.scm")
(define (integral delayed-integrand initial-value dt)
(define int
(cons-stream initial-value
(let ((integrand (force delayed-integrand)))
(add-streams (scale-stream integrand dt)
int))))
int)
(define (solve-2nd a b dt y0 dy0)
(define y (integral (delay dy) y0 dt))
(define dy (integral (delay ddy) dy0 dt))
(define ddy (add-streams (scale-stream dy a)
(scale-stream y b)))
y)
ddy + 2 * dy + y = 0
y(0 ) = 4 , dy(0 ) = -2
(displayln "solve-2nd")
(display-stream-n (solve-2nd -2 -1 0.001 4 -2) 20)
上面微分方程,特解为 y = ( 4 + 2 t ) * exp(-t ) , 直接打印出方程值作对比
(define (solution t)
(* (+ 4 (* 2 t)) (exp (- t))))
(define (solution-steam t dt)
(cons-stream (solution t) (solution-steam (+ t dt) dt)))
(displayln "solution")
(display-stream-n (solution-steam 0 0.001) 20)
|
|
adb1da495241f0ab659f495fe98f51935c72cd5de47b6414c0349b4c08eaf0b1 | auser/beehive | string_utils.erl | -module (string_utils).
-export([sub/3, gsub/3]).
% Mine
-export ([template_command_string/2]).
-import (string, [len/1, str/2, left/2,right/2,concat/2]).
sub(Str,Old,New) when is_list(Str) andalso is_list(Old) ->
Lstr = len(Str),
Lold = len(Old),
Pos = str(Str,Old),
if
Pos =:= 0 -> Str;
true ->
LeftPart = left(Str,Pos-1),
RitePart = right(Str,Lstr-Lold-Pos+1),
concat(concat(LeftPart,New),RitePart)
end;
sub(_Str,_Old,New) -> New.
gsub(Str,Old,New) ->
Acc = sub(Str,Old,New),
subst(Acc,Old,New,Str).
subst(Str,_Old,_New, Str) -> Str;
subst(Acc, Old, New,_Str) ->
Acc1 = sub(Acc,Old,New),
subst(Acc1,Old,New,Acc).
% turn the command string from the comand string with the values
of [ [ KEY ] ] replaced by the corresponding proplist element of
% the format:
{ [ [ PORT ] ] , " 80 " }
template_command_string(OriginalCommand, []) -> OriginalCommand;
template_command_string(OriginalCommand, [{_Str, undefined}|T]) -> template_command_string(OriginalCommand, T);
template_command_string(OriginalCommand, [{Atom, _}|T]) when is_atom(Atom) -> template_command_string(OriginalCommand, T);
template_command_string(OriginalCommand, [{Str, Replace}|T]) ->
NewCommand = string_utils:gsub(OriginalCommand, Str, Replace),
template_command_string(NewCommand, T). | null | https://raw.githubusercontent.com/auser/beehive/dfe257701b21c56a50af73c8203ecac60ed21991/lib/erlang/apps/beehive/src/bh_utils/string_utils.erl | erlang | Mine
turn the command string from the comand string with the values
the format: | -module (string_utils).
-export([sub/3, gsub/3]).
-export ([template_command_string/2]).
-import (string, [len/1, str/2, left/2,right/2,concat/2]).
sub(Str,Old,New) when is_list(Str) andalso is_list(Old) ->
Lstr = len(Str),
Lold = len(Old),
Pos = str(Str,Old),
if
Pos =:= 0 -> Str;
true ->
LeftPart = left(Str,Pos-1),
RitePart = right(Str,Lstr-Lold-Pos+1),
concat(concat(LeftPart,New),RitePart)
end;
sub(_Str,_Old,New) -> New.
gsub(Str,Old,New) ->
Acc = sub(Str,Old,New),
subst(Acc,Old,New,Str).
subst(Str,_Old,_New, Str) -> Str;
subst(Acc, Old, New,_Str) ->
Acc1 = sub(Acc,Old,New),
subst(Acc1,Old,New,Acc).
of [ [ KEY ] ] replaced by the corresponding proplist element of
{ [ [ PORT ] ] , " 80 " }
template_command_string(OriginalCommand, []) -> OriginalCommand;
template_command_string(OriginalCommand, [{_Str, undefined}|T]) -> template_command_string(OriginalCommand, T);
template_command_string(OriginalCommand, [{Atom, _}|T]) when is_atom(Atom) -> template_command_string(OriginalCommand, T);
template_command_string(OriginalCommand, [{Str, Replace}|T]) ->
NewCommand = string_utils:gsub(OriginalCommand, Str, Replace),
template_command_string(NewCommand, T). |
c4e98419cf1b0ea014b27c9ab2957a91e003e6fe5ea6e13a0d83a88eeef3b28a | ndmitchell/catch | ArgElim.hs |
-- Eliminate useless arguments
module Hite.ArgElim(cmd) where
import Hite.Type
import Data.List
import Data.Maybe
cmd = cmdHitePure (const argElim) "arg-elim"
"Eliminate useless arguments"
argElim :: Hite -> Hite
argElim hite@(Hite datas funcs) = Hite datas newfuncs
where
newfuncs = map (newFunc hite) res ++ useFuncs res funcs
res = concatMap deadArgs funcs
useFuncs :: [(FuncName, [Int])] -> [Func] -> [Func]
useFuncs res hite = mapExpr f hite
where
f x@(Call (CallFunc n) xs) =
case lookup n res of
Just dead | last dead < length xs -> Call (CallFunc (n ++ "_ARG")) (dropDead dead xs)
_ -> x
f x = x
deadArgs :: Func -> [(FuncName, [Int])]
deadArgs (Func name args body _) = [(name, unusedPos) | not $ null unused]
where
used = nub [x | Var x <- allExpr body]
unused = args \\ used
unusedPos = map (\x -> fromJust $ elemIndex x args) unused
newFunc :: Hite -> (FuncName, [Int]) -> Func
newFunc hite (name, dead) = Func (name ++ "_ARG") (dropDead dead args) body ex
where (Func _ args body ex) = getFunc hite name
dropDead :: [Int] -> [a] -> [a]
dropDead del xs = [x | (n,x) <- zip [0..] xs, not $ n `elem` del]
| null | https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/src/Hite/ArgElim.hs | haskell | Eliminate useless arguments
|
module Hite.ArgElim(cmd) where
import Hite.Type
import Data.List
import Data.Maybe
cmd = cmdHitePure (const argElim) "arg-elim"
"Eliminate useless arguments"
argElim :: Hite -> Hite
argElim hite@(Hite datas funcs) = Hite datas newfuncs
where
newfuncs = map (newFunc hite) res ++ useFuncs res funcs
res = concatMap deadArgs funcs
useFuncs :: [(FuncName, [Int])] -> [Func] -> [Func]
useFuncs res hite = mapExpr f hite
where
f x@(Call (CallFunc n) xs) =
case lookup n res of
Just dead | last dead < length xs -> Call (CallFunc (n ++ "_ARG")) (dropDead dead xs)
_ -> x
f x = x
deadArgs :: Func -> [(FuncName, [Int])]
deadArgs (Func name args body _) = [(name, unusedPos) | not $ null unused]
where
used = nub [x | Var x <- allExpr body]
unused = args \\ used
unusedPos = map (\x -> fromJust $ elemIndex x args) unused
newFunc :: Hite -> (FuncName, [Int]) -> Func
newFunc hite (name, dead) = Func (name ++ "_ARG") (dropDead dead args) body ex
where (Func _ args body ex) = getFunc hite name
dropDead :: [Int] -> [a] -> [a]
dropDead del xs = [x | (n,x) <- zip [0..] xs, not $ n `elem` del]
|
d3e7bc7c09724d6229771a261a533efe44a3358ff075929fabf21ed85ba1f2f2 | digital-asset/ghc | TcDaml.hs | # LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
module TcDaml where
import GhcPrelude
import qualified Data.Set as S
import InstEnv
import Outputable
import TcRnTypes
import TyCoRep
import TyCon
import OccName
import Name
import Module
import PrelNames
import RdrHsSyn
import RdrName
import SrcLoc
import HsTypes
import HsDecls
import HsExtension
import Type
import FastString
import TcRnMonad
import IfaceSyn
import HscTypes
import Var
import UniqFM
import Util
import qualified Data.Map as M
import Data.Bifunctor
import Data.Maybe
import Data.Either (partitionEithers)
import Data.Function (on)
import Data.List
import qualified Prelude as P ((<>))
import Control.Monad
import Data.Foldable (fold)
check :: NamedThing a => [String] -> String -> a -> Bool
check modules name namedThing
| Just mod <- moduleNameString . moduleName <$> nameModule_maybe (getName namedThing)
, mod `elem` modules
, name == occNameString (getOccName namedThing)
= True
| otherwise
= False
customDamlError :: DamlInfo -> Ct -> Maybe SDoc
customDamlError info ct = do
e <- detectError info ct
m <- displayError info e
pure (vcat [text "Possible Daml-specific reason for the following type error:", m])
data DamlError
= TriedView { target :: Name, result :: Type }
| TriedExercise { target :: Name, choice :: Name, result :: Type }
| TriedImplementMethod { target :: Name, method :: FastString, result :: Type }
| TriedImplementView { target :: Name, triedReturnType :: Type, expectedReturnType :: Type }
| NonExistentFieldAccess { recordType :: Type, expectedReturnType :: Type, fieldName :: FastString }
| FieldAccessWrongReturnType { fieldName :: FastString, recordType :: Type, triedReturnType :: Type, expectedReturnType :: Type }
| NumericScaleOutOfBounds { attemptedScale :: Integer }
| TriedImplementNonInterface { triedIface :: Name }
detectError :: DamlInfo -> Ct -> Maybe DamlError
detectError info ct
| TyConApp con [LitTy (NumTyLit attemptedScale)] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "GHC.Classes"] "NumericScale" con
, attemptedScale > 37 || attemptedScale < 0
= Just $ NumericScaleOutOfBounds { attemptedScale }
| TyConApp con [LitTy (StrTyLit fieldName), recordType, resultType] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" con
= Just $ NonExistentFieldAccess { fieldName, recordType, expectedReturnType = resultType }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [LitTy (StrTyLit fieldName1), recordType1, targetRetType] <- targetPred
, TyConApp instancePredCon [LitTy (StrTyLit fieldName2), recordType2, instanceRetType] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" instancePredCon
, fieldName1 == fieldName2
, eqType recordType1 recordType2
, not (eqType targetRetType instanceRetType)
= Just $ FieldAccessWrongReturnType { fieldName = fieldName1, recordType = recordType1, triedReturnType = targetRetType, expectedReturnType = instanceRetType }
| TyConApp con [TyConApp target []] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceTypeRep" con
= Just $ TriedImplementNonInterface { triedIface = tyConName target }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [TyConApp iface1 [], targetRetType] <- targetPred
, TyConApp instancePredCon [TyConApp iface2 [], instanceRetType] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" instancePredCon
, let iface1Name = tyConName iface1
, let iface2Name = tyConName iface2
, synEq info iface1Name iface2Name
, not (eqType targetRetType instanceRetType)
= Just $ TriedImplementView { target = iface1Name, triedReturnType = targetRetType, expectedReturnType = instanceRetType }
| TyConApp con [TyConApp target [], viewType] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" con
= Just $ TriedView { target = tyConName target, result = viewType }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon (_ `Snoc` TyConApp targetCon [] `Snoc` LitTy (StrTyLit targetMethodName) `Snoc` targetResult) <- targetPred
, TyConApp instancePredCon (_ `Snoc` TyConApp instanceCon [] `Snoc` LitTy (StrTyLit instanceMethodName) `Snoc` instanceResult) <- instancePred
, check ["DA.Internal.Desugar"] "HasMethod" targetPredCon
, check ["DA.Internal.Desugar"] "HasMethod" instancePredCon
, let targetConName = tyConName targetCon
, let instanceConName = tyConName instanceCon
, synEq info targetConName instanceConName
, targetMethodName == instanceMethodName
, not (eqType targetResult instanceResult)
= Just $ TriedImplementMethod { target = targetConName, method = targetMethodName, result = targetResult }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [TyConApp targetCon [], TyConApp targetChoice [], targetResult] <- targetPred
, TyConApp instancePredCon [TyConApp instanceCon [], TyConApp instanceChoice [], instanceResult] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" instancePredCon
, let targetConName = tyConName targetCon
, let instanceConName = tyConName instanceCon
, let targetChoiceName = tyConName targetChoice
, let instanceChoiceName = tyConName instanceChoice
, synEq info targetConName instanceConName
, synEq info targetChoiceName instanceChoiceName
, not (eqType targetResult instanceResult)
= Just $ TriedExercise { target = instanceConName, choice = instanceChoiceName, result = targetResult }
| TyConApp con [TyConApp target [], TyConApp choice [], result] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" con
= Just $ TriedExercise { target = tyConName target, choice = tyConName choice, result }
| TyConApp con (_ `Snoc` TyConApp target [] `Snoc` LitTy (StrTyLit methodName) `Snoc` result) <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar"] "HasMethod" con
= Just $ TriedImplementMethod { target = tyConName target, method = methodName, result }
| otherwise
= Nothing
snoc :: [a] -> Maybe ([a], a)
snoc [] = Nothing
snoc xs = Just (init xs, last xs)
pattern Snoc xs x <- (snoc -> Just (xs, x)) where
Snoc xs x = xs ++ [x]
printListWithHeader :: SDoc -> SDoc -> [SDoc] -> SDoc
printListWithHeader emptyMsg _ [] = emptyMsg
printListWithHeader _ nonEmptyMsg outs = nonEmptyMsg <+> hcat (punctuate (text ", ") outs)
displayError :: DamlInfo -> DamlError -> Maybe SDoc
displayError info TriedView { target, result }
| isTemplate info target
= pure
$ vcat [ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from template" <+> pprSynName info target
, text "Cast template" <+> pprq target <+> text "to an interface before getting its view."
, printListWithHeader
(text "Template" <+> pprq target <+> text "does not have any known interface implementations.")
(text "Template" <+> pprq target <+> text "has the following interfaces:")
(map pprq (allImplementedInterfaces info target))
]
| isInterface info target
, Just view <- interfaceView info target
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from interface" <+> pprSynName info target <+> text "but that interface's view is of type" <+> pprSynName info view
| isInterface info target
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from interface" <+> pprSynName info target <+> text "but that interface's view is not of type" <+> pprSynType info result
| otherwise
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from type" <+> pprSynName info target <+> text "which is neither an interface nor a template"
displayError info TriedExercise { target, result, choice }
| Just implementor <- choiceImplementor info choice
, isInterface info implementor
, implements info target implementor
, target /= implementor -- since interfaces implement themselves, we ignore if the target is itself
= pure
$ vcat [ text "Tried to exercise a choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target
, text "The choice" <+> pprq choice <+> text "belongs to" <+> variantNameSyn info implementor <+> text "which" <+> pprq target <+> text "implements."
, text "Cast" <+> variantName info target <+> text "to" <+> variantName info implementor <+> text "before exercising the choice."
]
| Just implementor <- choiceImplementor info choice
, Just expectedReturnType <- choiceType info choice
, not (result `eqType` expectedReturnType)
= pure
$ text "Tried to get a result of type" <+> pprSynType info result <+> text "by exercising choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target
<+> text "but exercising choice" <+> pprq choice <+> text "should return type" <+> pprq expectedReturnType <+> text "instead."
| otherwise
= pure
$ vcat [ text "Tried to exercise a choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target <+> text "but no choice of that name exists on" <+> variantName info target
, printListWithHeader
empty
(text "Choice" <+> pprq choice <+> text "belongs only to the following types:")
(map (variantNameSyn info) (maybeToList (choiceImplementor info choice)))
]
displayError info TriedImplementMethod { target, method, result }
| [(_, expectedResult)] <- methodOn info method target
, not (eqType expectedResult result)
= pure $ text "Implementation of method" <+> pprq method <+> text "on interface" <+> pprSynName info target <+> text "should return" <+> pprq expectedResult <+> text "but instead returns " <+> pprq result
| [] <- methodOn info method target
= pure
$ vcat [ text "Tried to implement method" <+> pprq method <> text ", but interface" <+> pprSynName info target <+> text "does not have a method with that name."
, printListWithHeader
empty
(text "Method" <+> pprq method <+> text "is only a method on the following interfaces:")
(map (pprq . fst) (methodsNamed info method))
]
| otherwise
= Nothing
displayError info TriedImplementView { target, triedReturnType, expectedReturnType } =
pure $ text "Tried to implement a view of type" <+> pprSynType info triedReturnType <+> text "on interface" <+> pprSynName info target
<> text ", but the definition of interface" <+> pprq target <+> text "requires a view of type" <+> pprSynType info expectedReturnType
displayError info NonExistentFieldAccess { recordType, expectedReturnType, fieldName } =
pure $ text "Tried to access nonexistent field" <+> pprq fieldName
<+> text "with type" <+> pprSynType info expectedReturnType
<+> text "on value of type" <+> pprSynType info recordType
displayError info FieldAccessWrongReturnType { recordType, triedReturnType, expectedReturnType, fieldName } =
pure $ text "Tried to get field" <+> pprq fieldName
<+> text "with type" <+> pprSynType info triedReturnType
<+> text "on value of type" <+> pprSynType info recordType
<> text ", but that field has type" <+> pprSynType info expectedReturnType
displayError info NumericScaleOutOfBounds { attemptedScale } =
pure $ text "Tried to define a Numeric with a scale of" <+> ppr attemptedScale <> text ", but only scales between 0 and 37 are supported."
displayError info TriedImplementNonInterface { triedIface }
| isTemplate info triedIface
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "is a template, not an interface."
| isInterface info triedIface
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "does not have an instance of HasInterfaceTypeRep. This should not happen, please contact support."
| otherwise
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "is not an interface."
dedupe :: DamlInfo -> DamlInfo
dedupe (DamlInfo x0 x1 x2 x3 x4 x5 x6) =
DamlInfo
x0
x1
x2
(nubSortBy (\(mName, (cName, type_)) -> (mName, cName)) x3)
(nubSort x4)
x5
x6
where
nubSortBy :: Ord b => (a -> b) -> [a] -> [a]
nubSortBy f xs = M.elems $ M.fromList $ map (\x -> (f x, x)) xs
pprq :: Outputable a => a -> SDoc
pprq = quotes . ppr
synEq :: DamlInfo -> Name -> Name -> Bool
synEq info n1 n2 = resolveSynonym info n1 == resolveSynonym info n2
isTemplate, isInterface, isSynonym :: DamlInfo -> Name -> Bool
isTemplate info name = resolveSynonym info name `S.member` templates info
isInterface info name = resolveSynonym info name `S.member` interfaces info
isSynonym info name = resolveSynonym info name `M.member` synonyms info
variantNameSyn :: DamlInfo -> Name -> SDoc
variantNameSyn info name
| isTemplate info name = text "template" <+> pprSynName info name
| isInterface info name = text "interface" <+> pprSynName info name
| otherwise = text "type" <+> pprSynName info name
variantName :: DamlInfo -> Name -> SDoc
variantName info name
| isTemplate info name = text "template" <+> pprq name
| isInterface info name = text "interface" <+> pprq name
| otherwise = text "type" <+> pprq name
allImplementedInterfaces, allImplementingTemplates :: DamlInfo -> Name -> [Name]
allImplementedInterfaces info name = [iface | (tpl, iface) <- implementations info, synEq info name tpl]
allImplementingTemplates info name = [tpl | (tpl, iface) <- implementations info, synEq info name iface]
implements :: DamlInfo -> Name -> Name -> Bool
implements info tpl iface = any (\(t, i) -> synEq info tpl t && synEq info iface i) (implementations info)
choiceImplementor :: DamlInfo -> Name -> Maybe Name
choiceImplementor info name = fst <$> M.lookup (resolveSynonym info name) (choices info)
choiceType :: DamlInfo -> Name -> Maybe Type
choiceType info name = snd <$> M.lookup (resolveSynonym info name) (choices info)
interfaceView :: DamlInfo -> Name -> Maybe Name
interfaceView info name = M.lookup (resolveSynonym info name) (views info)
methodsNamed :: DamlInfo -> FastString -> [(Name, Type)]
methodsNamed info method = [(name, type_) | (m, (name, type_)) <- methods info, m == method]
methodOn :: DamlInfo -> FastString -> Name -> [(Name, Type)]
methodOn info method target =
[(name, type_) | (m, (name, type_)) <- methods info, m == method, synEq info target name]
resolveSynonym :: DamlInfo -> Name -> Name
resolveSynonym info name =
case name `M.lookup` synonyms info of
Just (resolvedName, _) -> resolvedName
Nothing -> name
-- For unparameterised type aliases, we extract the name and print the alias
pprSynType :: DamlInfo -> Type -> SDoc
pprSynType info (TyConApp (getName -> name) []) = pprSynName info name
pprSynType _ ty = pprq ty
pprSynName :: DamlInfo -> Name -> SDoc
pprSynName info name =
let synName = resolveSynonym info name
in if name == synName
then pprq name
else pprq name <+> parens (text "Type synonym of" <+> pprq synName)
instance Monoid DamlInfo where
mempty = DamlInfo S.empty S.empty M.empty [] [] M.empty M.empty
instance Semigroup DamlInfo where
(<>) (DamlInfo a0 a1 a2 a3 a4 a5 a6) (DamlInfo b0 b1 b2 b3 b4 b5 b6) =
DamlInfo (a0 P.<> b0) (a1 P.<> b1) (a2 P.<> b2) (a3 P.<> b3) (a4 P.<> b4) (a5 P.<> b5) (a6 P.<> b6)
instance Outputable DamlInfo where
ppr info =
hang (text "DamlInfo {") 2 $
vcat [ text "templates =" <+> ppr (templates info)
, text "interfaces =" <+> ppr (interfaces info)
, text "choices =" <+> ppr (choices info)
, text "methods =" <+> ppr (methods info)
, text "implementations =" <+> ppr (implementations info)
, text "views =" <+> ppr (views info)
, text "synonyms =" <+> ppr (synonyms info)
, text "}"
]
resolveAllSynonyms :: DamlInfo -> DamlInfo
resolveAllSynonyms info@DamlInfo {..} =
DamlInfo
{ templates = S.map (resolveSynonym info) templates
, interfaces = S.map (resolveSynonym info) interfaces
, choices = (fmap . first) (resolveSynonym info) $ M.mapKeys (resolveSynonym info) choices
, methods = (fmap . second . first) (resolveSynonym info) methods
, implementations = (fmap . (\f -> bimap f f)) (resolveSynonym info) implementations
, views = M.foldMapWithKey (M.singleton `on` resolveSynonym info) views
, synonyms = synonyms
}
getEnvDaml :: TcM DamlInfo
getEnvDaml = do
env <- getEnv
mb_daml <- readMutVar (env_daml env)
case mb_daml of
Nothing -> do
eps <- readMutVar $ hsc_EPS $ env_top env
let tcg_tythings = foldMap extractDamlInfoFromTyThing (typeEnvElts $ tcg_type_env $ env_gbl env)
let tcg_insts = foldMap extractDamlInfoFromClsInst (instEnvElts $ tcg_inst_env $ env_gbl env)
let eps_tythings = foldMap extractDamlInfoFromTyThing (typeEnvElts $ eps_PTE eps)
let eps_insts = foldMap extractDamlInfoFromClsInst (instEnvElts $ eps_inst_env eps)
traceTc "DamlInfo tcg_tythings extracted" $ ppr tcg_tythings
traceTc "DamlInfo tcg_insts extracted" $ ppr tcg_insts
traceTc "DamlInfo eps_tythings extracted" $ ppr eps_tythings
traceTc "DamlInfo eps_insts extracted" $ ppr eps_insts
let new_info = dedupe (fold [tcg_tythings, tcg_insts, eps_tythings, eps_insts])
traceTc "DamlInfo new_info" $ ppr new_info
let all_tythings = typeEnvElts (tcg_type_env (env_gbl env)) ++ typeEnvElts (eps_PTE eps)
let new_info_with_synonyms = extractSynonymsFromTyThings new_info all_tythings
traceTc "DamlInfo new_info_with_synonyms" $ ppr new_info_with_synonyms
let finalDamlInfo = resolveAllSynonyms new_info_with_synonyms
writeMutVar (env_daml env) (Just finalDamlInfo)
pure finalDamlInfo
Just info -> pure info
extractDamlInfoFromTyThing :: TyThing -> DamlInfo
extractDamlInfoFromTyThing tything =
case tything of
ATyCon tycon ->
mempty
{ templates = S.fromList $ mapMaybe matchTemplate [tycon]
, interfaces = S.fromList $ mapMaybe matchInterface [tycon]
}
_ -> mempty
where
matchTemplate, matchInterface :: TyCon -> Maybe Name
matchTemplate = tyconWithConstraint "DamlTemplate"
matchInterface = tyconWithConstraint "DamlInterface"
tyconWithConstraint :: String -> TyCon -> Maybe Name
tyconWithConstraint targetName tycon
| isAlgTyCon tycon
, let isMatchingLoneConstraint type_
| Just (loneConstraint, []) <- splitTyConApp_maybe type_
= similarName targetName (tyConName loneConstraint)
| otherwise
= False
, any isMatchingLoneConstraint (tyConStupidTheta tycon)
= Just $ tyConName tycon
| otherwise
= Nothing
extractSynonymsFromTyThings :: DamlInfo -> [TyThing] -> DamlInfo
extractSynonymsFromTyThings existing tythings = go existing (mapMaybe getSynonym tythings)
where
synonymsToInfo :: [(Name, (Name, DamlSynonym))] -> DamlInfo
synonymsToInfo syn = mempty { synonyms = M.fromList syn }
getSynonym :: TyThing -> Maybe (Name, Name)
getSynonym tything = do
ATyCon msynonym <- pure tything
TyConApp out [] <- synTyConRhs_maybe msynonym
let outName = tyConName out
pure (tyConName msynonym, outName)
targetsToSynonyms :: [(Name, Name)]
targetsToSynonyms = mapMaybe getSynonym tythings
go :: DamlInfo -> [(Name, Name)] -> DamlInfo
go info unusedSynonyms =
let (matching, nonmatching) = partitionEithers $ map categorise unusedSynonyms
categorise link@(synonym, value)
| value `S.member` templates info = Left (synonym, (value, TemplateSyn))
| value `S.member` interfaces info = Left (synonym, (value, InterfaceSyn))
| value `M.member` choices info = Left (synonym, (value, ChoiceSyn))
| (==value) `any` views info = Left (synonym, (value, ViewSyn))
| Just result <- value `M.lookup` synonyms info = Left (synonym, result)
| otherwise = Right (synonym, value)
in
if null matching
then info
else go (info P.<> synonymsToInfo matching) nonmatching
extractDamlInfoFromClsInst :: ClsInst -> DamlInfo
extractDamlInfoFromClsInst inst =
mempty
{ choices = M.fromList $ mapMaybe matchChoice [inst]
, methods = mapMaybe matchMethod [inst]
, implementations = mapMaybe matchImplements [inst]
, views = M.fromList $ mapMaybe matchView [inst]
}
where
matchChoice :: ClsInst -> Maybe (Name, (Name, Type))
matchChoice clsInst = do
[contractType, choiceType, returnType] <-
clsInstMatch "HasExercise" clsInst
(contractTyCon, []) <- splitTyConApp_maybe contractType
(choiceTyCon, []) <- splitTyConApp_maybe choiceType
pure (tyConName choiceTyCon, (tyConName contractTyCon, returnType))
matchMethod :: ClsInst -> Maybe (FastString, (Name, Type))
matchMethod clsInst = do
(_ `Snoc` contractType `Snoc` methodNameType `Snoc` returnType) <-
clsInstMatch "HasMethod" clsInst
(StrTyLit methodName) <- isLitTy methodNameType
(contractTyCon, []) <- splitTyConApp_maybe contractType
pure (methodName, (tyConName contractTyCon, returnType))
matchImplements :: ClsInst -> Maybe (Name, Name)
matchImplements clsInst = do
[templateType, interfaceType] <-
clsInstMatch "HasToInterface" clsInst
(templateTyCon, []) <- splitTyConApp_maybe templateType
(interfaceTyCon, []) <- splitTyConApp_maybe interfaceType
pure (tyConName templateTyCon, tyConName interfaceTyCon)
matchView :: ClsInst -> Maybe (Name, Name)
matchView clsInst = do
[ifaceType, viewType] <-
clsInstMatch "HasInterfaceView" clsInst
(ifaceTyCon, []) <- splitTyConApp_maybe ifaceType
(viewTyCon, []) <- splitTyConApp_maybe viewType
pure (tyConName ifaceTyCon, tyConName viewTyCon)
clsInstMatch :: String -> ClsInst -> Maybe [Type]
clsInstMatch targetName clsInst = do
guard $ similarName targetName (is_cls_nm clsInst)
pure $ is_tys clsInst
similarName :: String -> Name -> Bool
similarName target name = occNameString (nameOccName name) == target
| null | https://raw.githubusercontent.com/digital-asset/ghc/7be2c87f191abb4a13d77171968dcdbe9a25b40e/compiler/typecheck/TcDaml.hs | haskell | since interfaces implement themselves, we ignore if the target is itself
For unparameterised type aliases, we extract the name and print the alias | # LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
module TcDaml where
import GhcPrelude
import qualified Data.Set as S
import InstEnv
import Outputable
import TcRnTypes
import TyCoRep
import TyCon
import OccName
import Name
import Module
import PrelNames
import RdrHsSyn
import RdrName
import SrcLoc
import HsTypes
import HsDecls
import HsExtension
import Type
import FastString
import TcRnMonad
import IfaceSyn
import HscTypes
import Var
import UniqFM
import Util
import qualified Data.Map as M
import Data.Bifunctor
import Data.Maybe
import Data.Either (partitionEithers)
import Data.Function (on)
import Data.List
import qualified Prelude as P ((<>))
import Control.Monad
import Data.Foldable (fold)
check :: NamedThing a => [String] -> String -> a -> Bool
check modules name namedThing
| Just mod <- moduleNameString . moduleName <$> nameModule_maybe (getName namedThing)
, mod `elem` modules
, name == occNameString (getOccName namedThing)
= True
| otherwise
= False
customDamlError :: DamlInfo -> Ct -> Maybe SDoc
customDamlError info ct = do
e <- detectError info ct
m <- displayError info e
pure (vcat [text "Possible Daml-specific reason for the following type error:", m])
data DamlError
= TriedView { target :: Name, result :: Type }
| TriedExercise { target :: Name, choice :: Name, result :: Type }
| TriedImplementMethod { target :: Name, method :: FastString, result :: Type }
| TriedImplementView { target :: Name, triedReturnType :: Type, expectedReturnType :: Type }
| NonExistentFieldAccess { recordType :: Type, expectedReturnType :: Type, fieldName :: FastString }
| FieldAccessWrongReturnType { fieldName :: FastString, recordType :: Type, triedReturnType :: Type, expectedReturnType :: Type }
| NumericScaleOutOfBounds { attemptedScale :: Integer }
| TriedImplementNonInterface { triedIface :: Name }
detectError :: DamlInfo -> Ct -> Maybe DamlError
detectError info ct
| TyConApp con [LitTy (NumTyLit attemptedScale)] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "GHC.Classes"] "NumericScale" con
, attemptedScale > 37 || attemptedScale < 0
= Just $ NumericScaleOutOfBounds { attemptedScale }
| TyConApp con [LitTy (StrTyLit fieldName), recordType, resultType] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" con
= Just $ NonExistentFieldAccess { fieldName, recordType, expectedReturnType = resultType }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [LitTy (StrTyLit fieldName1), recordType1, targetRetType] <- targetPred
, TyConApp instancePredCon [LitTy (StrTyLit fieldName2), recordType2, instanceRetType] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Record"] "HasField" instancePredCon
, fieldName1 == fieldName2
, eqType recordType1 recordType2
, not (eqType targetRetType instanceRetType)
= Just $ FieldAccessWrongReturnType { fieldName = fieldName1, recordType = recordType1, triedReturnType = targetRetType, expectedReturnType = instanceRetType }
| TyConApp con [TyConApp target []] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceTypeRep" con
= Just $ TriedImplementNonInterface { triedIface = tyConName target }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [TyConApp iface1 [], targetRetType] <- targetPred
, TyConApp instancePredCon [TyConApp iface2 [], instanceRetType] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" instancePredCon
, let iface1Name = tyConName iface1
, let iface2Name = tyConName iface2
, synEq info iface1Name iface2Name
, not (eqType targetRetType instanceRetType)
= Just $ TriedImplementView { target = iface1Name, triedReturnType = targetRetType, expectedReturnType = instanceRetType }
| TyConApp con [TyConApp target [], viewType] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Interface"] "HasInterfaceView" con
= Just $ TriedView { target = tyConName target, result = viewType }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon (_ `Snoc` TyConApp targetCon [] `Snoc` LitTy (StrTyLit targetMethodName) `Snoc` targetResult) <- targetPred
, TyConApp instancePredCon (_ `Snoc` TyConApp instanceCon [] `Snoc` LitTy (StrTyLit instanceMethodName) `Snoc` instanceResult) <- instancePred
, check ["DA.Internal.Desugar"] "HasMethod" targetPredCon
, check ["DA.Internal.Desugar"] "HasMethod" instancePredCon
, let targetConName = tyConName targetCon
, let instanceConName = tyConName instanceCon
, synEq info targetConName instanceConName
, targetMethodName == instanceMethodName
, not (eqType targetResult instanceResult)
= Just $ TriedImplementMethod { target = targetConName, method = targetMethodName, result = targetResult }
| FunDepOrigin2 targetPred _ instancePred _ <- ctOrigin ct
, TyConApp targetPredCon [TyConApp targetCon [], TyConApp targetChoice [], targetResult] <- targetPred
, TyConApp instancePredCon [TyConApp instanceCon [], TyConApp instanceChoice [], instanceResult] <- instancePred
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" targetPredCon
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" instancePredCon
, let targetConName = tyConName targetCon
, let instanceConName = tyConName instanceCon
, let targetChoiceName = tyConName targetChoice
, let instanceChoiceName = tyConName instanceChoice
, synEq info targetConName instanceConName
, synEq info targetChoiceName instanceChoiceName
, not (eqType targetResult instanceResult)
= Just $ TriedExercise { target = instanceConName, choice = instanceChoiceName, result = targetResult }
| TyConApp con [TyConApp target [], TyConApp choice [], result] <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar", "DA.Internal.Template.Functions"] "HasExercise" con
= Just $ TriedExercise { target = tyConName target, choice = tyConName choice, result }
| TyConApp con (_ `Snoc` TyConApp target [] `Snoc` LitTy (StrTyLit methodName) `Snoc` result) <- ctev_pred (ctEvidence ct)
, check ["DA.Internal.Desugar"] "HasMethod" con
= Just $ TriedImplementMethod { target = tyConName target, method = methodName, result }
| otherwise
= Nothing
snoc :: [a] -> Maybe ([a], a)
snoc [] = Nothing
snoc xs = Just (init xs, last xs)
pattern Snoc xs x <- (snoc -> Just (xs, x)) where
Snoc xs x = xs ++ [x]
printListWithHeader :: SDoc -> SDoc -> [SDoc] -> SDoc
printListWithHeader emptyMsg _ [] = emptyMsg
printListWithHeader _ nonEmptyMsg outs = nonEmptyMsg <+> hcat (punctuate (text ", ") outs)
displayError :: DamlInfo -> DamlError -> Maybe SDoc
displayError info TriedView { target, result }
| isTemplate info target
= pure
$ vcat [ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from template" <+> pprSynName info target
, text "Cast template" <+> pprq target <+> text "to an interface before getting its view."
, printListWithHeader
(text "Template" <+> pprq target <+> text "does not have any known interface implementations.")
(text "Template" <+> pprq target <+> text "has the following interfaces:")
(map pprq (allImplementedInterfaces info target))
]
| isInterface info target
, Just view <- interfaceView info target
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from interface" <+> pprSynName info target <+> text "but that interface's view is of type" <+> pprSynName info view
| isInterface info target
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from interface" <+> pprSynName info target <+> text "but that interface's view is not of type" <+> pprSynType info result
| otherwise
= pure
$ text "Tried to get an interface view of type" <+> pprSynType info result <+> text "from type" <+> pprSynName info target <+> text "which is neither an interface nor a template"
displayError info TriedExercise { target, result, choice }
| Just implementor <- choiceImplementor info choice
, isInterface info implementor
, implements info target implementor
= pure
$ vcat [ text "Tried to exercise a choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target
, text "The choice" <+> pprq choice <+> text "belongs to" <+> variantNameSyn info implementor <+> text "which" <+> pprq target <+> text "implements."
, text "Cast" <+> variantName info target <+> text "to" <+> variantName info implementor <+> text "before exercising the choice."
]
| Just implementor <- choiceImplementor info choice
, Just expectedReturnType <- choiceType info choice
, not (result `eqType` expectedReturnType)
= pure
$ text "Tried to get a result of type" <+> pprSynType info result <+> text "by exercising choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target
<+> text "but exercising choice" <+> pprq choice <+> text "should return type" <+> pprq expectedReturnType <+> text "instead."
| otherwise
= pure
$ vcat [ text "Tried to exercise a choice" <+> pprSynName info choice <+> text "on" <+> variantNameSyn info target <+> text "but no choice of that name exists on" <+> variantName info target
, printListWithHeader
empty
(text "Choice" <+> pprq choice <+> text "belongs only to the following types:")
(map (variantNameSyn info) (maybeToList (choiceImplementor info choice)))
]
displayError info TriedImplementMethod { target, method, result }
| [(_, expectedResult)] <- methodOn info method target
, not (eqType expectedResult result)
= pure $ text "Implementation of method" <+> pprq method <+> text "on interface" <+> pprSynName info target <+> text "should return" <+> pprq expectedResult <+> text "but instead returns " <+> pprq result
| [] <- methodOn info method target
= pure
$ vcat [ text "Tried to implement method" <+> pprq method <> text ", but interface" <+> pprSynName info target <+> text "does not have a method with that name."
, printListWithHeader
empty
(text "Method" <+> pprq method <+> text "is only a method on the following interfaces:")
(map (pprq . fst) (methodsNamed info method))
]
| otherwise
= Nothing
displayError info TriedImplementView { target, triedReturnType, expectedReturnType } =
pure $ text "Tried to implement a view of type" <+> pprSynType info triedReturnType <+> text "on interface" <+> pprSynName info target
<> text ", but the definition of interface" <+> pprq target <+> text "requires a view of type" <+> pprSynType info expectedReturnType
displayError info NonExistentFieldAccess { recordType, expectedReturnType, fieldName } =
pure $ text "Tried to access nonexistent field" <+> pprq fieldName
<+> text "with type" <+> pprSynType info expectedReturnType
<+> text "on value of type" <+> pprSynType info recordType
displayError info FieldAccessWrongReturnType { recordType, triedReturnType, expectedReturnType, fieldName } =
pure $ text "Tried to get field" <+> pprq fieldName
<+> text "with type" <+> pprSynType info triedReturnType
<+> text "on value of type" <+> pprSynType info recordType
<> text ", but that field has type" <+> pprSynType info expectedReturnType
displayError info NumericScaleOutOfBounds { attemptedScale } =
pure $ text "Tried to define a Numeric with a scale of" <+> ppr attemptedScale <> text ", but only scales between 0 and 37 are supported."
displayError info TriedImplementNonInterface { triedIface }
| isTemplate info triedIface
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "is a template, not an interface."
| isInterface info triedIface
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "does not have an instance of HasInterfaceTypeRep. This should not happen, please contact support."
| otherwise
= pure $ text "Tried to make an interface implementation of" <+> pprSynName info triedIface <>
text ", but" <+> pprq triedIface <+> text "is not an interface."
dedupe :: DamlInfo -> DamlInfo
dedupe (DamlInfo x0 x1 x2 x3 x4 x5 x6) =
DamlInfo
x0
x1
x2
(nubSortBy (\(mName, (cName, type_)) -> (mName, cName)) x3)
(nubSort x4)
x5
x6
where
nubSortBy :: Ord b => (a -> b) -> [a] -> [a]
nubSortBy f xs = M.elems $ M.fromList $ map (\x -> (f x, x)) xs
pprq :: Outputable a => a -> SDoc
pprq = quotes . ppr
synEq :: DamlInfo -> Name -> Name -> Bool
synEq info n1 n2 = resolveSynonym info n1 == resolveSynonym info n2
isTemplate, isInterface, isSynonym :: DamlInfo -> Name -> Bool
isTemplate info name = resolveSynonym info name `S.member` templates info
isInterface info name = resolveSynonym info name `S.member` interfaces info
isSynonym info name = resolveSynonym info name `M.member` synonyms info
variantNameSyn :: DamlInfo -> Name -> SDoc
variantNameSyn info name
| isTemplate info name = text "template" <+> pprSynName info name
| isInterface info name = text "interface" <+> pprSynName info name
| otherwise = text "type" <+> pprSynName info name
variantName :: DamlInfo -> Name -> SDoc
variantName info name
| isTemplate info name = text "template" <+> pprq name
| isInterface info name = text "interface" <+> pprq name
| otherwise = text "type" <+> pprq name
allImplementedInterfaces, allImplementingTemplates :: DamlInfo -> Name -> [Name]
allImplementedInterfaces info name = [iface | (tpl, iface) <- implementations info, synEq info name tpl]
allImplementingTemplates info name = [tpl | (tpl, iface) <- implementations info, synEq info name iface]
implements :: DamlInfo -> Name -> Name -> Bool
implements info tpl iface = any (\(t, i) -> synEq info tpl t && synEq info iface i) (implementations info)
choiceImplementor :: DamlInfo -> Name -> Maybe Name
choiceImplementor info name = fst <$> M.lookup (resolveSynonym info name) (choices info)
choiceType :: DamlInfo -> Name -> Maybe Type
choiceType info name = snd <$> M.lookup (resolveSynonym info name) (choices info)
interfaceView :: DamlInfo -> Name -> Maybe Name
interfaceView info name = M.lookup (resolveSynonym info name) (views info)
methodsNamed :: DamlInfo -> FastString -> [(Name, Type)]
methodsNamed info method = [(name, type_) | (m, (name, type_)) <- methods info, m == method]
methodOn :: DamlInfo -> FastString -> Name -> [(Name, Type)]
methodOn info method target =
[(name, type_) | (m, (name, type_)) <- methods info, m == method, synEq info target name]
resolveSynonym :: DamlInfo -> Name -> Name
resolveSynonym info name =
case name `M.lookup` synonyms info of
Just (resolvedName, _) -> resolvedName
Nothing -> name
pprSynType :: DamlInfo -> Type -> SDoc
pprSynType info (TyConApp (getName -> name) []) = pprSynName info name
pprSynType _ ty = pprq ty
pprSynName :: DamlInfo -> Name -> SDoc
pprSynName info name =
let synName = resolveSynonym info name
in if name == synName
then pprq name
else pprq name <+> parens (text "Type synonym of" <+> pprq synName)
instance Monoid DamlInfo where
mempty = DamlInfo S.empty S.empty M.empty [] [] M.empty M.empty
instance Semigroup DamlInfo where
(<>) (DamlInfo a0 a1 a2 a3 a4 a5 a6) (DamlInfo b0 b1 b2 b3 b4 b5 b6) =
DamlInfo (a0 P.<> b0) (a1 P.<> b1) (a2 P.<> b2) (a3 P.<> b3) (a4 P.<> b4) (a5 P.<> b5) (a6 P.<> b6)
instance Outputable DamlInfo where
ppr info =
hang (text "DamlInfo {") 2 $
vcat [ text "templates =" <+> ppr (templates info)
, text "interfaces =" <+> ppr (interfaces info)
, text "choices =" <+> ppr (choices info)
, text "methods =" <+> ppr (methods info)
, text "implementations =" <+> ppr (implementations info)
, text "views =" <+> ppr (views info)
, text "synonyms =" <+> ppr (synonyms info)
, text "}"
]
resolveAllSynonyms :: DamlInfo -> DamlInfo
resolveAllSynonyms info@DamlInfo {..} =
DamlInfo
{ templates = S.map (resolveSynonym info) templates
, interfaces = S.map (resolveSynonym info) interfaces
, choices = (fmap . first) (resolveSynonym info) $ M.mapKeys (resolveSynonym info) choices
, methods = (fmap . second . first) (resolveSynonym info) methods
, implementations = (fmap . (\f -> bimap f f)) (resolveSynonym info) implementations
, views = M.foldMapWithKey (M.singleton `on` resolveSynonym info) views
, synonyms = synonyms
}
getEnvDaml :: TcM DamlInfo
getEnvDaml = do
env <- getEnv
mb_daml <- readMutVar (env_daml env)
case mb_daml of
Nothing -> do
eps <- readMutVar $ hsc_EPS $ env_top env
let tcg_tythings = foldMap extractDamlInfoFromTyThing (typeEnvElts $ tcg_type_env $ env_gbl env)
let tcg_insts = foldMap extractDamlInfoFromClsInst (instEnvElts $ tcg_inst_env $ env_gbl env)
let eps_tythings = foldMap extractDamlInfoFromTyThing (typeEnvElts $ eps_PTE eps)
let eps_insts = foldMap extractDamlInfoFromClsInst (instEnvElts $ eps_inst_env eps)
traceTc "DamlInfo tcg_tythings extracted" $ ppr tcg_tythings
traceTc "DamlInfo tcg_insts extracted" $ ppr tcg_insts
traceTc "DamlInfo eps_tythings extracted" $ ppr eps_tythings
traceTc "DamlInfo eps_insts extracted" $ ppr eps_insts
let new_info = dedupe (fold [tcg_tythings, tcg_insts, eps_tythings, eps_insts])
traceTc "DamlInfo new_info" $ ppr new_info
let all_tythings = typeEnvElts (tcg_type_env (env_gbl env)) ++ typeEnvElts (eps_PTE eps)
let new_info_with_synonyms = extractSynonymsFromTyThings new_info all_tythings
traceTc "DamlInfo new_info_with_synonyms" $ ppr new_info_with_synonyms
let finalDamlInfo = resolveAllSynonyms new_info_with_synonyms
writeMutVar (env_daml env) (Just finalDamlInfo)
pure finalDamlInfo
Just info -> pure info
extractDamlInfoFromTyThing :: TyThing -> DamlInfo
extractDamlInfoFromTyThing tything =
case tything of
ATyCon tycon ->
mempty
{ templates = S.fromList $ mapMaybe matchTemplate [tycon]
, interfaces = S.fromList $ mapMaybe matchInterface [tycon]
}
_ -> mempty
where
matchTemplate, matchInterface :: TyCon -> Maybe Name
matchTemplate = tyconWithConstraint "DamlTemplate"
matchInterface = tyconWithConstraint "DamlInterface"
tyconWithConstraint :: String -> TyCon -> Maybe Name
tyconWithConstraint targetName tycon
| isAlgTyCon tycon
, let isMatchingLoneConstraint type_
| Just (loneConstraint, []) <- splitTyConApp_maybe type_
= similarName targetName (tyConName loneConstraint)
| otherwise
= False
, any isMatchingLoneConstraint (tyConStupidTheta tycon)
= Just $ tyConName tycon
| otherwise
= Nothing
extractSynonymsFromTyThings :: DamlInfo -> [TyThing] -> DamlInfo
extractSynonymsFromTyThings existing tythings = go existing (mapMaybe getSynonym tythings)
where
synonymsToInfo :: [(Name, (Name, DamlSynonym))] -> DamlInfo
synonymsToInfo syn = mempty { synonyms = M.fromList syn }
getSynonym :: TyThing -> Maybe (Name, Name)
getSynonym tything = do
ATyCon msynonym <- pure tything
TyConApp out [] <- synTyConRhs_maybe msynonym
let outName = tyConName out
pure (tyConName msynonym, outName)
targetsToSynonyms :: [(Name, Name)]
targetsToSynonyms = mapMaybe getSynonym tythings
go :: DamlInfo -> [(Name, Name)] -> DamlInfo
go info unusedSynonyms =
let (matching, nonmatching) = partitionEithers $ map categorise unusedSynonyms
categorise link@(synonym, value)
| value `S.member` templates info = Left (synonym, (value, TemplateSyn))
| value `S.member` interfaces info = Left (synonym, (value, InterfaceSyn))
| value `M.member` choices info = Left (synonym, (value, ChoiceSyn))
| (==value) `any` views info = Left (synonym, (value, ViewSyn))
| Just result <- value `M.lookup` synonyms info = Left (synonym, result)
| otherwise = Right (synonym, value)
in
if null matching
then info
else go (info P.<> synonymsToInfo matching) nonmatching
extractDamlInfoFromClsInst :: ClsInst -> DamlInfo
extractDamlInfoFromClsInst inst =
mempty
{ choices = M.fromList $ mapMaybe matchChoice [inst]
, methods = mapMaybe matchMethod [inst]
, implementations = mapMaybe matchImplements [inst]
, views = M.fromList $ mapMaybe matchView [inst]
}
where
matchChoice :: ClsInst -> Maybe (Name, (Name, Type))
matchChoice clsInst = do
[contractType, choiceType, returnType] <-
clsInstMatch "HasExercise" clsInst
(contractTyCon, []) <- splitTyConApp_maybe contractType
(choiceTyCon, []) <- splitTyConApp_maybe choiceType
pure (tyConName choiceTyCon, (tyConName contractTyCon, returnType))
matchMethod :: ClsInst -> Maybe (FastString, (Name, Type))
matchMethod clsInst = do
(_ `Snoc` contractType `Snoc` methodNameType `Snoc` returnType) <-
clsInstMatch "HasMethod" clsInst
(StrTyLit methodName) <- isLitTy methodNameType
(contractTyCon, []) <- splitTyConApp_maybe contractType
pure (methodName, (tyConName contractTyCon, returnType))
matchImplements :: ClsInst -> Maybe (Name, Name)
matchImplements clsInst = do
[templateType, interfaceType] <-
clsInstMatch "HasToInterface" clsInst
(templateTyCon, []) <- splitTyConApp_maybe templateType
(interfaceTyCon, []) <- splitTyConApp_maybe interfaceType
pure (tyConName templateTyCon, tyConName interfaceTyCon)
matchView :: ClsInst -> Maybe (Name, Name)
matchView clsInst = do
[ifaceType, viewType] <-
clsInstMatch "HasInterfaceView" clsInst
(ifaceTyCon, []) <- splitTyConApp_maybe ifaceType
(viewTyCon, []) <- splitTyConApp_maybe viewType
pure (tyConName ifaceTyCon, tyConName viewTyCon)
clsInstMatch :: String -> ClsInst -> Maybe [Type]
clsInstMatch targetName clsInst = do
guard $ similarName targetName (is_cls_nm clsInst)
pure $ is_tys clsInst
similarName :: String -> Name -> Bool
similarName target name = occNameString (nameOccName name) == target
|
782320053eb713f7bcda10ca46f379cbf681ee67fe0d016c955533bd18212ca9 | ocaml-ppx/ocamlformat | disabled_attr.ml | let _ =
let disabled = {|
|}[@ocamlformat "disable"] in
()
let _ =
let disabled = "
"[@ocamlformat "disable"] in
()
let _ =
let disabled =
begin
(* xxx
xxx *)
y
end[@ocamlformat "disable"]
in
()
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/134d89608748592d3e42c02b2459a2106878b1f3/test/passing/tests/disabled_attr.ml | ocaml | xxx
xxx | let _ =
let disabled = {|
|}[@ocamlformat "disable"] in
()
let _ =
let disabled = "
"[@ocamlformat "disable"] in
()
let _ =
let disabled =
begin
y
end[@ocamlformat "disable"]
in
()
|
64e1addaef65e6c6cf53b6819e8654a67e278106a6989cb153583907a3cd2f68 | jkvor/log_roller | log_roller_server.erl | Copyright ( c ) 2009 < >
%%
%% Permission is hereby granted, free of charge, to any person
%% obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
%% restriction, including without limitation the rights to use,
%% copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the
%% Software is furnished to do so, subject to the following
%% conditions:
%%
%% The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
%% OTHER DEALINGS IN THE SOFTWARE.
-module(log_roller_server).
-author('').
-behaviour(application).
-export([
start/0, start/2, stop/1, init/1,
start_phase/3, build_rel/1, compile_templates/0
]).
-include("log_roller.hrl").
%%%
%%% Application API
%%%
start() ->
application:start(?MODULE).
%% @doc start the application
start(_StartType, _StartArgs) ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% @doc stop the application
stop(_) ->
ok.
%%%
Internal functions
%%%
init(_) ->
Logs = lr_config:get_log_configs(),
{ok, {{one_for_one, 10, 10}, [
{erlang:make_ref(), {lr_write_to_disk, start_link, [LogConfig]}, permanent, 5000, worker, [lr_write_to_disk]}
|| LogConfig <- Logs] ++ [
{lr_hooks, {lr_hooks, start_link, []}, permanent, 5000, worker, [lr_hooks]},
{lr_web_server, {lr_web_server, start_link, [[]]}, permanent, 5000, worker, [lr_web_server]},
{lr_tail, {lr_tail, start_link, []}, permanent, 5000, worker, [lr_tail]}
]
}}.
start_phase(world, _, _) ->
net_adm:world(),
ok;
start_phase(pg2, _, _) ->
pg2:which_groups(),
ok.
build_rel(AppVsn) ->
Apps = [kernel,stdlib],
{ok, FD} = file:open("bin/" ++ atom_to_list(?MODULE) ++ ".rel", [write]),
RelInfo = {release,
{atom_to_list(?MODULE), AppVsn},
log_roller_utils:get_app_version(erts),
[log_roller_utils:get_app_version(AppName) || AppName <- Apps] ++ [
{mochiweb, "0.01"},
{?MODULE, AppVsn}
]
},
io:format(FD, "~p.", [RelInfo]),
file:close(FD),
systools:make_script("bin/" ++ atom_to_list(?MODULE), [local]),
ok.
compile_templates() ->
{ok, Filenames} = file:list_dir("templates"),
[erltl:compile("templates/" ++ Filename, [{outdir, "ebin"}, report_errors, report_warnings, nowarn_unused_vars])
|| Filename <- Filenames],
ok. | null | https://raw.githubusercontent.com/jkvor/log_roller/1f072ab74532314f94bdc94dd5a8572d5ceb8d4e/src/log_roller_server.erl | erlang |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Application API
@doc start the application
@doc stop the application
| Copyright ( c ) 2009 < >
files ( the " Software " ) , to deal in the Software without
copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
-module(log_roller_server).
-author('').
-behaviour(application).
-export([
start/0, start/2, stop/1, init/1,
start_phase/3, build_rel/1, compile_templates/0
]).
-include("log_roller.hrl").
start() ->
application:start(?MODULE).
start(_StartType, _StartArgs) ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
stop(_) ->
ok.
Internal functions
init(_) ->
Logs = lr_config:get_log_configs(),
{ok, {{one_for_one, 10, 10}, [
{erlang:make_ref(), {lr_write_to_disk, start_link, [LogConfig]}, permanent, 5000, worker, [lr_write_to_disk]}
|| LogConfig <- Logs] ++ [
{lr_hooks, {lr_hooks, start_link, []}, permanent, 5000, worker, [lr_hooks]},
{lr_web_server, {lr_web_server, start_link, [[]]}, permanent, 5000, worker, [lr_web_server]},
{lr_tail, {lr_tail, start_link, []}, permanent, 5000, worker, [lr_tail]}
]
}}.
start_phase(world, _, _) ->
net_adm:world(),
ok;
start_phase(pg2, _, _) ->
pg2:which_groups(),
ok.
build_rel(AppVsn) ->
Apps = [kernel,stdlib],
{ok, FD} = file:open("bin/" ++ atom_to_list(?MODULE) ++ ".rel", [write]),
RelInfo = {release,
{atom_to_list(?MODULE), AppVsn},
log_roller_utils:get_app_version(erts),
[log_roller_utils:get_app_version(AppName) || AppName <- Apps] ++ [
{mochiweb, "0.01"},
{?MODULE, AppVsn}
]
},
io:format(FD, "~p.", [RelInfo]),
file:close(FD),
systools:make_script("bin/" ++ atom_to_list(?MODULE), [local]),
ok.
compile_templates() ->
{ok, Filenames} = file:list_dir("templates"),
[erltl:compile("templates/" ++ Filename, [{outdir, "ebin"}, report_errors, report_warnings, nowarn_unused_vars])
|| Filename <- Filenames],
ok. |
8c36fd094590bbdb70c5127d0900cf45622e5dbba62075a2a8b42b8eecbe539a | GoNZooo/gotyno-hs | Spec.hs | module Main where
import qualified HaskellOutputSpec
import qualified ParsingSpec
import Qtility
import Test.Hspec
main :: IO ()
main = do
tsReferenceOutput <- ParsingSpec.typeScriptReferenceOutput
hsReferenceOutput <- ParsingSpec.haskellReferenceOutput
fsReferenceOutput <- ParsingSpec.fSharpReferenceOutput
pyReferenceOutput <- ParsingSpec.pythonReferenceOutput
ktReferenceOutput <- ParsingSpec.kotlinReferenceOutput
dLangReferenceOutput <- ParsingSpec.dLangReferenceOutput
hspec $ do
ParsingSpec.spec
tsReferenceOutput
hsReferenceOutput
fsReferenceOutput
pyReferenceOutput
ktReferenceOutput
dLangReferenceOutput
HaskellOutputSpec.spec
| null | https://raw.githubusercontent.com/GoNZooo/gotyno-hs/0b70ba901ebb7c50b650eadc8104a708b5345a48/test/Spec.hs | haskell | module Main where
import qualified HaskellOutputSpec
import qualified ParsingSpec
import Qtility
import Test.Hspec
main :: IO ()
main = do
tsReferenceOutput <- ParsingSpec.typeScriptReferenceOutput
hsReferenceOutput <- ParsingSpec.haskellReferenceOutput
fsReferenceOutput <- ParsingSpec.fSharpReferenceOutput
pyReferenceOutput <- ParsingSpec.pythonReferenceOutput
ktReferenceOutput <- ParsingSpec.kotlinReferenceOutput
dLangReferenceOutput <- ParsingSpec.dLangReferenceOutput
hspec $ do
ParsingSpec.spec
tsReferenceOutput
hsReferenceOutput
fsReferenceOutput
pyReferenceOutput
ktReferenceOutput
dLangReferenceOutput
HaskellOutputSpec.spec
|
|
1d4294710c53bcb5ace4ea892d1d6a77cc6bd0650ca783e4dadb1cd2e4378523 | mark-watson/haskell_tutorial_cookbook_examples | CommonWords.hs | module Main where
import Data.Set (fromList, toList, intersection)
import Data.Char (toLower)
fileToWords fileName = do
fileText <- readFile fileName
return $ (fromList . words) (map toLower fileText)
commonWords file1 file2 = do
words1 <- fileToWords file1
words2 <- fileToWords file2
return $ toList $ intersection words1 words2
commonWords2 file1 file2 =
fileToWords file1 >>= \f1 ->
fileToWords file2 >>= \f2 ->
return $ toList $ intersection f1 f2
commonWords3 file1 file2 =
(\f1 f2 -> toList $ intersection f1 f2)
<$> fileToWords file1
<*> fileToWords file2
main = do
cw <- commonWords "text1.txt" "text2.txt"
print cw
cw2 <- commonWords2 "text1.txt" "text2.txt"
print cw2
cw3 <- commonWords3 "text1.txt" "text2.txt"
print cw3
| null | https://raw.githubusercontent.com/mark-watson/haskell_tutorial_cookbook_examples/b4ddfc7cc0290f4f1617fca9c363260f43ab66cf/ImPure/CommonWords.hs | haskell | module Main where
import Data.Set (fromList, toList, intersection)
import Data.Char (toLower)
fileToWords fileName = do
fileText <- readFile fileName
return $ (fromList . words) (map toLower fileText)
commonWords file1 file2 = do
words1 <- fileToWords file1
words2 <- fileToWords file2
return $ toList $ intersection words1 words2
commonWords2 file1 file2 =
fileToWords file1 >>= \f1 ->
fileToWords file2 >>= \f2 ->
return $ toList $ intersection f1 f2
commonWords3 file1 file2 =
(\f1 f2 -> toList $ intersection f1 f2)
<$> fileToWords file1
<*> fileToWords file2
main = do
cw <- commonWords "text1.txt" "text2.txt"
print cw
cw2 <- commonWords2 "text1.txt" "text2.txt"
print cw2
cw3 <- commonWords3 "text1.txt" "text2.txt"
print cw3
|
|
074135da8165e471c14258524abc9bfc89f8e36b43159cd9a61ed5a52f27bc35 | 0install/0install | test.ml | Copyright ( C ) 2013 , the README file for details , or visit .
* See the README file for details, or visit .
*)
Unix.putenv "TZ" "Europe/London"
open OUnit
open Zeroinstall
open Zeroinstall.General
open Support
open Support.Common
open Fake_system
let ( ) = Support.Logging.threshold : = Support . Logging . Info
let () =
Unix.putenv "http_proxy" "localhost:8000"; (* Prevent accidents *)
Unix.putenv "https_proxy" "localhost:1112";
Unix.putenv "ZEROINSTALL_UNITTESTS" "true";
Unix.putenv "ZEROINSTALL_CRASH_LOGS" ""
let test_basedir () =
skip_if (Sys.os_type = "Win32") "Don't work on Windows";
let system = new fake_system None in
let open Support.Basedir in
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"No $HOME1" ["/root/.config"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"No $HOME2" ["/root/.cache"; "/var/cache"] bd.cache;
equal_str_lists ~msg:"No $HOME3" ["/root/.local/share"; "/usr/local/share"; "/usr/share"] bd.data;
system#putenv "HOME" "/home/bob";
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"$HOME1" ["/home/bob/.config"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"$HOME2" ["/home/bob/.cache"; "/var/cache"] bd.cache;
equal_str_lists ~msg:"$HOME3" ["/home/bob/.local/share"; "/usr/local/share"; "/usr/share"] bd.data;
system#putenv "XDG_CONFIG_HOME" "/home/bob/prefs";
system#putenv "XDG_CACHE_DIRS" "";
system#putenv "XDG_DATA_DIRS" "/data1:/data2";
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"XDG1" ["/home/bob/prefs"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"XDG2" ["/home/bob/.cache"] bd.cache;
equal_str_lists ~msg:"XDG3" ["/home/bob/.local/share"; "/data1"; "/data2"] bd.data
let test_portable_base () =
skip_if (Sys.os_type = "Win32") "Tests Unix paths";
let system = new fake_system None in
system#putenv "HOME" "/home/bob";
let paths = Paths.get_default (system :> system) in
(* Check paths when not using portable base... *)
equal_str_lists ~msg:"XDG-1"
["/home/bob/.config/0install.net/injector/global"; "/etc/xdg/0install.net/injector/global"]
(Paths.Config.(all_paths global) paths);
equal_str_lists ~msg:"XDG-2"
["/home/bob/.local/share/0install.net/site-packages/http/example.com/hello";
"/usr/local/share/0install.net/site-packages/http/example.com/hello";
"/usr/share/0install.net/site-packages/http/example.com/hello"]
(Paths.Data.(all_paths (site_packages "")) paths);
equal_str_lists ~msg:"XDG-3"
["/home/bob/.cache/0install.net/interface_icons/%2fmy%20prog";
"/var/cache/0install.net/interface_icons/%2fmy%20prog"]
(Paths.Cache.(all_paths (icon (`Local_feed "/my prog"))) paths);
(* Now try with portable base... *)
system#putenv "ZEROINSTALL_PORTABLE_BASE" "/mnt/0install";
let paths = Paths.get_default (system :> system) in
equal_str_lists ~msg:"PORT-1"
["/mnt/0install/config/injector/global"]
(Paths.Config.(all_paths global) paths);
equal_str_lists ~msg:"PORT-2"
["/mnt/0install/data/site-packages/http/example.com/hello"]
(Paths.Data.(all_paths (site_packages "")) paths);
equal_str_lists ~msg:"PORT-3"
["/mnt/0install/cache/interface_icons/%2fmy%20prog"]
(Paths.Cache.(all_paths (icon (`Local_feed "/my prog"))) paths)
let as_list flags =
let lst = ref [] in
Support.Argparse.iter_options flags (fun v -> lst := v :: !lst);
List.rev !lst
let test_option_parsing () =
Support.Logging.threshold := Support.Logging.Warning;
let config, _fake_system = get_fake_config None in
let open Options in
let stdout = Buffer.create 100 in
let p_full raw_args =
let (raw_options, args, complete) = Support.Argparse.read_args Cli.spec raw_args in
assert (complete = Support.Argparse.CompleteNothing);
let _, subcommand, _ =
if args = [] then ([], Cli.no_command, [])
else Command_tree.(lookup (make_group Cli.commands)) args in
match subcommand with
| Command_tree.Group _ -> assert false
| Command_tree.Command subcommand ->
let flags = Support.Argparse.parse_options (Command_tree.options subcommand) raw_options in
let options = Cli.get_default_options ~stdout:(Format.formatter_of_buffer stdout) config in
let process = function
| #common_option as flag -> Common_options.process_common_option options flag
| _ -> () in
Support.Argparse.iter_options flags process;
(options, flags, args) in
let p args = let (options, _flags, _args) = p_full args in options in
assert_equal `Auto (p ["select"]).tools#use_gui;
assert_equal `No (p ["--console"; "select"]).tools#use_gui;
let _, _, args = p_full ["--with-store"; "/data/store"; "run"; "foo"] in
assert_equal "/data/store" (List.nth config.stores @@ List.length config.stores - 1);
equal_str_lists ["run"; "foo"] args;
config.stores <- [];
let _, _, args = p_full ["--with-store=/data/s1"; "run"; "--with-store=/data/s2"; "foo"; "--with-store=/data/s3"] in
equal_str_lists ["/data/s1"; "/data/s2"] config.stores;
equal_str_lists ["run"; "foo"; "--with-store=/data/s3"] args;
assert_raises_safe "Option does not take an argument in '--console=true'" (lazy (ignore @@ p ["--console=true"]));
assert (List.length (fake_log#get) = 0);
let s = p ["-cvv"; "run"] in
assert_equal `No s.tools#use_gui;
assert_equal 2 s.verbosity;
assert (List.length (fake_log#get) > 0);
let _, flags, args = p_full ["run"; "-wgdb"; "foo"] in
equal_str_lists ["run"; "foo"] args;
assert_equal [`Wrapper "gdb"] (as_list flags);
begin try
Support.Argparse.iter_options flags (fun _ -> Safe_exn.failf "Error!");
assert false
with Safe_exn.T e ->
let msg = Format.asprintf "%a" Safe_exn.pp e in
assert_str_equal "Error!\n... processing option '-w'" msg end;
Buffer.reset stdout;
begin
try ignore @@ p ["-c"; "--version"]; assert false;
with System_exit 0 -> ()
end;
let v = Buffer.contents stdout in
assert (Str.string_match (Str.regexp_string "0install (zero-install)") v 0);
let _, flags, args = p_full ["--version"; "1.2"; "run"; "foo"] in
equal_str_lists ["run"; "foo"] args;
assert_equal [`RequireVersion "1.2"] (as_list flags);
let _, flags, args = p_full ["digest"; "-m"; "archive.tgz"] in
equal_str_lists ["digest"; "archive.tgz"] args;
assert_equal [`ShowManifest] (as_list flags);
let _, flags, args = p_full ["run"; "-m"; "main"; "app"] in
equal_str_lists ["run"; "app"] args;
assert_equal [`MainExecutable "main"] (as_list flags)
let test_run_real tmpdir =
Unix.putenv "ZEROINSTALL_PORTABLE_BASE" tmpdir;
let sels_path =
if on_windows then "data\\test_selections_win.xml"
else "data/test_selections.xml" in
let argv = [Fake_system.tests_dir +/ "0install"; "run"; sels_path] in
let line = Support.Utils.check_output real_system input_all argv in
assert_str_equal "Hello World\n" line
(* This is really just for the coverage testing, which test_run_real doesn't do. *)
let test_run_fake tmpdir =
let (config, fake_system) = Fake_system.get_fake_config (Some tmpdir) in
let sels_path = Support.Utils.abspath Fake_system.real_system (
if on_windows then "data\\test_selections_win.xml"
else "data/test_selections.xml"
) in
fake_system#add_file sels_path sels_path;
try
Fake_system.check_no_output @@ fun stdout ->
Cli.handle ~stdout config ["run"; sels_path; "--"; "--arg"]; assert false
with Fake_system.Would_exec (search, _env, args) ->
assert (not search);
if on_windows then equal_str_lists ["c:\\cygwin\\bin\\env.exe"; "my-prog"; "Hello World"; "--"; "--arg"] args
else equal_str_lists ["/usr/bin/env"; "my-prog"; "Hello World"; "--"; "--arg"] args
let test_escaping () =
let open Zeroinstall.Escape in
let wfile s = if on_windows then "file%3a" ^ s else "file:" ^ s in
List.iter (fun (a, b) -> assert_str_equal a b) [
(* Escaping *)
("", escape "");
("hello", escape "hello");
("%20", escape " ");
("file%3a%2f%2ffoo%7ebar", escape "file~bar");
("file%3a%2f%2ffoo%25bar", escape "file");
(wfile "##foo%7ebar", pretty "file~bar");
(wfile "##foo%25bar", pretty "file");
(* Unescaping *)
("", unescape "");
("hello", unescape "hello");
(" ", unescape "%20");
("file~bar", unescape "file%3a%2f%2ffoo%7ebar");
("file", unescape "file%3a%2f%2ffoo%25bar");
("file", unescape "file:##foo");
("file~bar", unescape "file:##foo%7ebar");
("file", unescape "file:##foo%25bar");
];
assert_str_equal "http_3a_____example.com" @@ underscore_escape "";
assert_str_equal "_25_20_25_21_7e__26__21__22_£_20__3a__40__3b__2c_.___7b__7d__24__25__5e__26__28__29_" @@ underscore_escape "%20%21~&!\"£ :@;,./{}$%^&()";
let check str =
assert_str_equal str @@ unescape @@ escape str;
assert_str_equal str @@ unescape @@ pretty str;
assert_str_equal str @@ ununderscore_escape @@ underscore_escape str in
check "";
check "";
check "";
check "http:##example#com";
check "";
check "%20%21~&!\"£ :@;,./{}$%^&()";
check "-50%á.xml";
check "_one__two___three____four_____";
check "_1_and_2_";
assert_str_equal "_2e_" @@ underscore_escape ".";
assert_str_equal "_2e_." @@ underscore_escape "..";
equal_str_lists ["http"; "example.com"; "foo.xml"] @@ escape_interface_uri "";
equal_str_lists ["http"; "example.com"; "foo__.bar.xml"] @@ escape_interface_uri "";
equal_str_lists ["file"; "root__foo.xml"] @@ escape_interface_uri "/root/foo.xml";
assert_raises_safe "Invalid interface path 'ftp'" (lazy (
ignore @@ escape_interface_uri "ftp"
))
(* Name the test cases and group them together *)
let suite =
"0install">:::[
Test_completion.suite;
Test_versions.suite;
Test_utils.suite;
Test_sat.suite;
Test_solver.suite;
Test_distro.suite;
Test_0install.suite;
Test_apps.suite;
Test_driver.suite;
Test_gpg.suite;
Test_trust.suite;
Test_feed.suite;
Test_feed_cache.suite;
Test_selections.suite;
Test_stores.suite;
Test_0store.suite;
Test_fetch.suite;
Test_download.suite;
Test_archive.suite;
Test_manifest.suite;
Test_packagekit.suite;
Test_qdom.suite;
Test_run.suite;
Test_bug_reporter.suite;
"test_basedir">:: test_basedir;
"test_portable_base">:: test_portable_base;
"test_option_parsing">:: (fun () -> collect_logging test_option_parsing);
"test_run_real">:: (fun () -> collect_logging (with_tmpdir test_run_real));
"test_run_fake">:: (fun () -> collect_logging (with_tmpdir test_run_fake));
"test_escaping">:: test_escaping;
"test_canonical">:: (fun () ->
let system = (new fake_system None :> system) in
let check arg uri =
assert_str_equal uri (Generic_select.canonical_iface_uri system arg) in
let check_err arg =
try (ignore @@ Generic_select.canonical_iface_uri system arg); assert false
with Safe_exn.T _ -> () in
check "" "";
check "alias:./data/v1-alias" "";
check "alias:./data/v2-alias" "";
check_err "";
);
"test_locale">:: (fun () ->
let test expected vars =
let system = new fake_system None in
List.iter (fun (k, v) -> system#putenv k v) vars;
equal_str_lists expected @@ List.map Support.Locale.format_lang @@ Support.Locale.get_langs (system :> system) in
test ["en_GB"] [];
test ["fr_FR"; "en_GB"] [("LANG", "fr_FR")];
test ["en_GB"] [("LANG", "en_GB")];
test ["de_DE"; "en_GB"] [("LANG", "de_DE@euro")];
test ["en_GB"] [("LANGUAGE", "de_DE@euro:fr")];
test ["de_DE"; "fr"; "en_GB"] [("LANG", "de_DE@euro"); ("LANGUAGE", "de_DE@euro:fr")];
test ["de_DE"; "en_GB"] [("LANG", "fr_FR"); ("LC_ALL", "de_DE")];
test ["de_DE"; "en_GB"] [("LANG", "fr_FR"); ("LC_MESSAGES", "de_DE")];
);
]
let orig_stderr = Unix.out_channel_of_descr @@ Unix.dup Unix.stderr
let async_exception = ref None
let show_log_on_failure fn () =
Support.Logging.threshold := Support.Logging.Debug;
async_exception := None;
Zeroinstall.Downloader.interceptor := None;
Fake_system.forward_to_real_log := true;
Update.wait_for_network := (fun () -> `Connected);
try
Fake_system.fake_log#reset;
fn ();
Fake_system.release ();
(* Gc.full_major (); *)
!async_exception |> if_some (fun ex -> raise ex)
with ex ->
if XString.starts_with (Printexc.to_string ex) "OUnitTest.Skip" then ()
else (
Fake_system.fake_log#dump;
log_warning ~ex "Test failed"; (* Useful if you want a stack-trace *)
);
raise ex
let () =
Lwt.async_exception_hook := (fun ex ->
async_exception := Some ex;
Printf.fprintf orig_stderr "Async exception: %s" (Printexc.to_string ex);
flush orig_stderr
)
let is_error = function
| RFailure _ | RError _ -> true
| _ -> false
let () =
Printexc.record_backtrace true;
let results = run_test_tt_main @@ test_decorate show_log_on_failure suite in
Format.print_newline ();
if List.exists is_error results then exit 1
| null | https://raw.githubusercontent.com/0install/0install/22eebdbe51a9f46cda29eed3e9e02e37e36b2d18/src/tests/test.ml | ocaml | Prevent accidents
Check paths when not using portable base...
Now try with portable base...
This is really just for the coverage testing, which test_run_real doesn't do.
Escaping
Unescaping
Name the test cases and group them together
Gc.full_major ();
Useful if you want a stack-trace | Copyright ( C ) 2013 , the README file for details , or visit .
* See the README file for details, or visit .
*)
Unix.putenv "TZ" "Europe/London"
open OUnit
open Zeroinstall
open Zeroinstall.General
open Support
open Support.Common
open Fake_system
let ( ) = Support.Logging.threshold : = Support . Logging . Info
let () =
Unix.putenv "https_proxy" "localhost:1112";
Unix.putenv "ZEROINSTALL_UNITTESTS" "true";
Unix.putenv "ZEROINSTALL_CRASH_LOGS" ""
let test_basedir () =
skip_if (Sys.os_type = "Win32") "Don't work on Windows";
let system = new fake_system None in
let open Support.Basedir in
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"No $HOME1" ["/root/.config"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"No $HOME2" ["/root/.cache"; "/var/cache"] bd.cache;
equal_str_lists ~msg:"No $HOME3" ["/root/.local/share"; "/usr/local/share"; "/usr/share"] bd.data;
system#putenv "HOME" "/home/bob";
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"$HOME1" ["/home/bob/.config"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"$HOME2" ["/home/bob/.cache"; "/var/cache"] bd.cache;
equal_str_lists ~msg:"$HOME3" ["/home/bob/.local/share"; "/usr/local/share"; "/usr/share"] bd.data;
system#putenv "XDG_CONFIG_HOME" "/home/bob/prefs";
system#putenv "XDG_CACHE_DIRS" "";
system#putenv "XDG_DATA_DIRS" "/data1:/data2";
let bd = get_default_config (system :> system) in
equal_str_lists ~msg:"XDG1" ["/home/bob/prefs"; "/etc/xdg"] bd.config;
equal_str_lists ~msg:"XDG2" ["/home/bob/.cache"] bd.cache;
equal_str_lists ~msg:"XDG3" ["/home/bob/.local/share"; "/data1"; "/data2"] bd.data
let test_portable_base () =
skip_if (Sys.os_type = "Win32") "Tests Unix paths";
let system = new fake_system None in
system#putenv "HOME" "/home/bob";
let paths = Paths.get_default (system :> system) in
equal_str_lists ~msg:"XDG-1"
["/home/bob/.config/0install.net/injector/global"; "/etc/xdg/0install.net/injector/global"]
(Paths.Config.(all_paths global) paths);
equal_str_lists ~msg:"XDG-2"
["/home/bob/.local/share/0install.net/site-packages/http/example.com/hello";
"/usr/local/share/0install.net/site-packages/http/example.com/hello";
"/usr/share/0install.net/site-packages/http/example.com/hello"]
(Paths.Data.(all_paths (site_packages "")) paths);
equal_str_lists ~msg:"XDG-3"
["/home/bob/.cache/0install.net/interface_icons/%2fmy%20prog";
"/var/cache/0install.net/interface_icons/%2fmy%20prog"]
(Paths.Cache.(all_paths (icon (`Local_feed "/my prog"))) paths);
system#putenv "ZEROINSTALL_PORTABLE_BASE" "/mnt/0install";
let paths = Paths.get_default (system :> system) in
equal_str_lists ~msg:"PORT-1"
["/mnt/0install/config/injector/global"]
(Paths.Config.(all_paths global) paths);
equal_str_lists ~msg:"PORT-2"
["/mnt/0install/data/site-packages/http/example.com/hello"]
(Paths.Data.(all_paths (site_packages "")) paths);
equal_str_lists ~msg:"PORT-3"
["/mnt/0install/cache/interface_icons/%2fmy%20prog"]
(Paths.Cache.(all_paths (icon (`Local_feed "/my prog"))) paths)
let as_list flags =
let lst = ref [] in
Support.Argparse.iter_options flags (fun v -> lst := v :: !lst);
List.rev !lst
let test_option_parsing () =
Support.Logging.threshold := Support.Logging.Warning;
let config, _fake_system = get_fake_config None in
let open Options in
let stdout = Buffer.create 100 in
let p_full raw_args =
let (raw_options, args, complete) = Support.Argparse.read_args Cli.spec raw_args in
assert (complete = Support.Argparse.CompleteNothing);
let _, subcommand, _ =
if args = [] then ([], Cli.no_command, [])
else Command_tree.(lookup (make_group Cli.commands)) args in
match subcommand with
| Command_tree.Group _ -> assert false
| Command_tree.Command subcommand ->
let flags = Support.Argparse.parse_options (Command_tree.options subcommand) raw_options in
let options = Cli.get_default_options ~stdout:(Format.formatter_of_buffer stdout) config in
let process = function
| #common_option as flag -> Common_options.process_common_option options flag
| _ -> () in
Support.Argparse.iter_options flags process;
(options, flags, args) in
let p args = let (options, _flags, _args) = p_full args in options in
assert_equal `Auto (p ["select"]).tools#use_gui;
assert_equal `No (p ["--console"; "select"]).tools#use_gui;
let _, _, args = p_full ["--with-store"; "/data/store"; "run"; "foo"] in
assert_equal "/data/store" (List.nth config.stores @@ List.length config.stores - 1);
equal_str_lists ["run"; "foo"] args;
config.stores <- [];
let _, _, args = p_full ["--with-store=/data/s1"; "run"; "--with-store=/data/s2"; "foo"; "--with-store=/data/s3"] in
equal_str_lists ["/data/s1"; "/data/s2"] config.stores;
equal_str_lists ["run"; "foo"; "--with-store=/data/s3"] args;
assert_raises_safe "Option does not take an argument in '--console=true'" (lazy (ignore @@ p ["--console=true"]));
assert (List.length (fake_log#get) = 0);
let s = p ["-cvv"; "run"] in
assert_equal `No s.tools#use_gui;
assert_equal 2 s.verbosity;
assert (List.length (fake_log#get) > 0);
let _, flags, args = p_full ["run"; "-wgdb"; "foo"] in
equal_str_lists ["run"; "foo"] args;
assert_equal [`Wrapper "gdb"] (as_list flags);
begin try
Support.Argparse.iter_options flags (fun _ -> Safe_exn.failf "Error!");
assert false
with Safe_exn.T e ->
let msg = Format.asprintf "%a" Safe_exn.pp e in
assert_str_equal "Error!\n... processing option '-w'" msg end;
Buffer.reset stdout;
begin
try ignore @@ p ["-c"; "--version"]; assert false;
with System_exit 0 -> ()
end;
let v = Buffer.contents stdout in
assert (Str.string_match (Str.regexp_string "0install (zero-install)") v 0);
let _, flags, args = p_full ["--version"; "1.2"; "run"; "foo"] in
equal_str_lists ["run"; "foo"] args;
assert_equal [`RequireVersion "1.2"] (as_list flags);
let _, flags, args = p_full ["digest"; "-m"; "archive.tgz"] in
equal_str_lists ["digest"; "archive.tgz"] args;
assert_equal [`ShowManifest] (as_list flags);
let _, flags, args = p_full ["run"; "-m"; "main"; "app"] in
equal_str_lists ["run"; "app"] args;
assert_equal [`MainExecutable "main"] (as_list flags)
let test_run_real tmpdir =
Unix.putenv "ZEROINSTALL_PORTABLE_BASE" tmpdir;
let sels_path =
if on_windows then "data\\test_selections_win.xml"
else "data/test_selections.xml" in
let argv = [Fake_system.tests_dir +/ "0install"; "run"; sels_path] in
let line = Support.Utils.check_output real_system input_all argv in
assert_str_equal "Hello World\n" line
let test_run_fake tmpdir =
let (config, fake_system) = Fake_system.get_fake_config (Some tmpdir) in
let sels_path = Support.Utils.abspath Fake_system.real_system (
if on_windows then "data\\test_selections_win.xml"
else "data/test_selections.xml"
) in
fake_system#add_file sels_path sels_path;
try
Fake_system.check_no_output @@ fun stdout ->
Cli.handle ~stdout config ["run"; sels_path; "--"; "--arg"]; assert false
with Fake_system.Would_exec (search, _env, args) ->
assert (not search);
if on_windows then equal_str_lists ["c:\\cygwin\\bin\\env.exe"; "my-prog"; "Hello World"; "--"; "--arg"] args
else equal_str_lists ["/usr/bin/env"; "my-prog"; "Hello World"; "--"; "--arg"] args
let test_escaping () =
let open Zeroinstall.Escape in
let wfile s = if on_windows then "file%3a" ^ s else "file:" ^ s in
List.iter (fun (a, b) -> assert_str_equal a b) [
("", escape "");
("hello", escape "hello");
("%20", escape " ");
("file%3a%2f%2ffoo%7ebar", escape "file~bar");
("file%3a%2f%2ffoo%25bar", escape "file");
(wfile "##foo%7ebar", pretty "file~bar");
(wfile "##foo%25bar", pretty "file");
("", unescape "");
("hello", unescape "hello");
(" ", unescape "%20");
("file~bar", unescape "file%3a%2f%2ffoo%7ebar");
("file", unescape "file%3a%2f%2ffoo%25bar");
("file", unescape "file:##foo");
("file~bar", unescape "file:##foo%7ebar");
("file", unescape "file:##foo%25bar");
];
assert_str_equal "http_3a_____example.com" @@ underscore_escape "";
assert_str_equal "_25_20_25_21_7e__26__21__22_£_20__3a__40__3b__2c_.___7b__7d__24__25__5e__26__28__29_" @@ underscore_escape "%20%21~&!\"£ :@;,./{}$%^&()";
let check str =
assert_str_equal str @@ unescape @@ escape str;
assert_str_equal str @@ unescape @@ pretty str;
assert_str_equal str @@ ununderscore_escape @@ underscore_escape str in
check "";
check "";
check "";
check "http:##example#com";
check "";
check "%20%21~&!\"£ :@;,./{}$%^&()";
check "-50%á.xml";
check "_one__two___three____four_____";
check "_1_and_2_";
assert_str_equal "_2e_" @@ underscore_escape ".";
assert_str_equal "_2e_." @@ underscore_escape "..";
equal_str_lists ["http"; "example.com"; "foo.xml"] @@ escape_interface_uri "";
equal_str_lists ["http"; "example.com"; "foo__.bar.xml"] @@ escape_interface_uri "";
equal_str_lists ["file"; "root__foo.xml"] @@ escape_interface_uri "/root/foo.xml";
assert_raises_safe "Invalid interface path 'ftp'" (lazy (
ignore @@ escape_interface_uri "ftp"
))
let suite =
"0install">:::[
Test_completion.suite;
Test_versions.suite;
Test_utils.suite;
Test_sat.suite;
Test_solver.suite;
Test_distro.suite;
Test_0install.suite;
Test_apps.suite;
Test_driver.suite;
Test_gpg.suite;
Test_trust.suite;
Test_feed.suite;
Test_feed_cache.suite;
Test_selections.suite;
Test_stores.suite;
Test_0store.suite;
Test_fetch.suite;
Test_download.suite;
Test_archive.suite;
Test_manifest.suite;
Test_packagekit.suite;
Test_qdom.suite;
Test_run.suite;
Test_bug_reporter.suite;
"test_basedir">:: test_basedir;
"test_portable_base">:: test_portable_base;
"test_option_parsing">:: (fun () -> collect_logging test_option_parsing);
"test_run_real">:: (fun () -> collect_logging (with_tmpdir test_run_real));
"test_run_fake">:: (fun () -> collect_logging (with_tmpdir test_run_fake));
"test_escaping">:: test_escaping;
"test_canonical">:: (fun () ->
let system = (new fake_system None :> system) in
let check arg uri =
assert_str_equal uri (Generic_select.canonical_iface_uri system arg) in
let check_err arg =
try (ignore @@ Generic_select.canonical_iface_uri system arg); assert false
with Safe_exn.T _ -> () in
check "" "";
check "alias:./data/v1-alias" "";
check "alias:./data/v2-alias" "";
check_err "";
);
"test_locale">:: (fun () ->
let test expected vars =
let system = new fake_system None in
List.iter (fun (k, v) -> system#putenv k v) vars;
equal_str_lists expected @@ List.map Support.Locale.format_lang @@ Support.Locale.get_langs (system :> system) in
test ["en_GB"] [];
test ["fr_FR"; "en_GB"] [("LANG", "fr_FR")];
test ["en_GB"] [("LANG", "en_GB")];
test ["de_DE"; "en_GB"] [("LANG", "de_DE@euro")];
test ["en_GB"] [("LANGUAGE", "de_DE@euro:fr")];
test ["de_DE"; "fr"; "en_GB"] [("LANG", "de_DE@euro"); ("LANGUAGE", "de_DE@euro:fr")];
test ["de_DE"; "en_GB"] [("LANG", "fr_FR"); ("LC_ALL", "de_DE")];
test ["de_DE"; "en_GB"] [("LANG", "fr_FR"); ("LC_MESSAGES", "de_DE")];
);
]
let orig_stderr = Unix.out_channel_of_descr @@ Unix.dup Unix.stderr
let async_exception = ref None
let show_log_on_failure fn () =
Support.Logging.threshold := Support.Logging.Debug;
async_exception := None;
Zeroinstall.Downloader.interceptor := None;
Fake_system.forward_to_real_log := true;
Update.wait_for_network := (fun () -> `Connected);
try
Fake_system.fake_log#reset;
fn ();
Fake_system.release ();
!async_exception |> if_some (fun ex -> raise ex)
with ex ->
if XString.starts_with (Printexc.to_string ex) "OUnitTest.Skip" then ()
else (
Fake_system.fake_log#dump;
);
raise ex
let () =
Lwt.async_exception_hook := (fun ex ->
async_exception := Some ex;
Printf.fprintf orig_stderr "Async exception: %s" (Printexc.to_string ex);
flush orig_stderr
)
let is_error = function
| RFailure _ | RError _ -> true
| _ -> false
let () =
Printexc.record_backtrace true;
let results = run_test_tt_main @@ test_decorate show_log_on_failure suite in
Format.print_newline ();
if List.exists is_error results then exit 1
|
b3cb6fbeddde98c03ce96c0e26fb207cc0f75ca94557dddacfa25446190e35f2 | fredokun/arbogen | frontend.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Arbogen - lib : fast uniform random generation of trees *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Module : ParseUtil *
* ------- *
* Options Parser *
* ------- *
* ( C ) 2011 , , *
* , *
* *
* under the *
* GNU GPL v.3 licence ( cf . LICENSE file ) *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Arbogen-lib : fast uniform random generation of trees *
*********************************************************
* Module: ParseUtil *
* ------- *
* Options Parser *
* ------- *
* (C) 2011, Xuming Zhan, Frederic Peschanski *
* Antonine Genitrini, Matthieu Dien *
* Marwan Ghanem *
* under the *
* GNU GPL v.3 licence (cf. LICENSE file) *
*********************************************************)
(** Specification parsing and configuration options management *)
* { 2 Configuration options management }
(** Configuration options available on the command line of the executable, and
in specification files in the form of `set option value` directives. *)
module Options = Options
* { 2 Parsing functions }
* a specification , possibly preceded by configuration options , given via
an stdlib input channel .
an stdlib input channel. *)
let parse_from_channel chan =
let lexbuf = Lexing.from_channel chan in
let options, parsetree = Parser.start Lexer.token lexbuf in
(options, ParseTree.to_grammar parsetree)
* a specification , possibly preceded by configuration options , given via
its file name .
its file name. *)
let parse_from_file filename =
let chan = open_in filename in
let res = parse_from_channel chan in
close_in chan; res
module ParseTree = ParseTree
(** A user-friendly representation of grammars. *)
| null | https://raw.githubusercontent.com/fredokun/arbogen/1c348767fbc5f40d32b4b83865c1b33ba04acc30/src/lib/frontend/frontend.ml | ocaml | * Specification parsing and configuration options management
* Configuration options available on the command line of the executable, and
in specification files in the form of `set option value` directives.
* A user-friendly representation of grammars. | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Arbogen - lib : fast uniform random generation of trees *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Module : ParseUtil *
* ------- *
* Options Parser *
* ------- *
* ( C ) 2011 , , *
* , *
* *
* under the *
* GNU GPL v.3 licence ( cf . LICENSE file ) *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Arbogen-lib : fast uniform random generation of trees *
*********************************************************
* Module: ParseUtil *
* ------- *
* Options Parser *
* ------- *
* (C) 2011, Xuming Zhan, Frederic Peschanski *
* Antonine Genitrini, Matthieu Dien *
* Marwan Ghanem *
* under the *
* GNU GPL v.3 licence (cf. LICENSE file) *
*********************************************************)
* { 2 Configuration options management }
module Options = Options
* { 2 Parsing functions }
* a specification , possibly preceded by configuration options , given via
an stdlib input channel .
an stdlib input channel. *)
let parse_from_channel chan =
let lexbuf = Lexing.from_channel chan in
let options, parsetree = Parser.start Lexer.token lexbuf in
(options, ParseTree.to_grammar parsetree)
* a specification , possibly preceded by configuration options , given via
its file name .
its file name. *)
let parse_from_file filename =
let chan = open_in filename in
let res = parse_from_channel chan in
close_in chan; res
module ParseTree = ParseTree
|
ba0972af8b89e387322bd5141d719d20e72ee5befd363eeac4076afaf5fe850f | may-liu/qtalk | cyrsasl_anonymous.erl | %%%----------------------------------------------------------------------
%%% File : cyrsasl_anonymous.erl
Author : < >
%%% Purpose : ANONYMOUS SASL mechanism
%%% See -drafts/draft-ietf-sasl-anon-05.txt
Created : 23 Aug 2005 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(cyrsasl_anonymous).
-export([start/1, stop/0, mech_new/4, mech_step/2]).
-behaviour(cyrsasl).
-record(state, {server = <<"">> :: binary()}).
start(_Opts) ->
cyrsasl:register_mechanism(<<"ANONYMOUS">>, ?MODULE, plain),
ok.
stop() -> ok.
mech_new(Host, _GetPassword, _CheckPassword, _CheckPasswordDigest) ->
{ok, #state{server = Host}}.
mech_step(#state{server = Server}, _ClientIn) ->
User = iolist_to_binary([randoms:get_string()
| [jlib:integer_to_binary(X)
|| X <- tuple_to_list(now())]]),
case ejabberd_auth:is_user_exists(User, Server) of
true -> {error, <<"not-authorized">>};
false -> {ok, [{username, User}, {auth_module, ejabberd_auth_anonymous}]}
end.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/cyrsasl_anonymous.erl | erlang | ----------------------------------------------------------------------
File : cyrsasl_anonymous.erl
Purpose : ANONYMOUS SASL mechanism
See -drafts/draft-ietf-sasl-anon-05.txt
This program is free software; you can redistribute it and/or
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.
---------------------------------------------------------------------- | Author : < >
Created : 23 Aug 2005 by < >
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(cyrsasl_anonymous).
-export([start/1, stop/0, mech_new/4, mech_step/2]).
-behaviour(cyrsasl).
-record(state, {server = <<"">> :: binary()}).
start(_Opts) ->
cyrsasl:register_mechanism(<<"ANONYMOUS">>, ?MODULE, plain),
ok.
stop() -> ok.
mech_new(Host, _GetPassword, _CheckPassword, _CheckPasswordDigest) ->
{ok, #state{server = Host}}.
mech_step(#state{server = Server}, _ClientIn) ->
User = iolist_to_binary([randoms:get_string()
| [jlib:integer_to_binary(X)
|| X <- tuple_to_list(now())]]),
case ejabberd_auth:is_user_exists(User, Server) of
true -> {error, <<"not-authorized">>};
false -> {ok, [{username, User}, {auth_module, ejabberd_auth_anonymous}]}
end.
|
9c10ad7fffa403b8fdbd6e6ac17d8b3156caaf73e3c7ef6e13ada63e92b1bd18 | kafka4beam/kflow | kflow_wf_sysmon_receiver.erl | %%%===================================================================
2020 Klarna Bank AB ( publ )
%%%
%%% @doc This workflow receives `system_monitor' messages and puts
%%% them to postgres tables.
%%%
%%% == Configuration ==
%%%
%%% The following parameters are mandatory:
%%%
= = = kafka_topic = = =
%%%
%%% Type: `brod:topic()'.
%%%
%%% === group_id ===
%%%
Type : ` binary ( ) ' . group consumer ID used by the workflow .
%%%
%%% === database ===
%%%
%%% Type: `epgsql:connect_opts()'. See
[ #L63 ]
%%%
%%% @end
%%%
%%% This module is made out of recycled old sequalizer code, answers
%%% to why everything was desinged like that are lost in history.
%%%
%%%===================================================================
-module(kflow_wf_sysmon_receiver).
-include("kflow_int.hrl").
%% API
-export([workflow/2]).
%% Internal exports:
-export([ nullable/1
, timestamp/1
, to_string/2
, format_function/1
, format_stacktrace/1
]).
-export_type([config/0]).
%%%===================================================================
%%% Types
%%%===================================================================
-type config() ::
#{ kafka_topic := brod:topic()
, group_id := binary()
, database := epgsql:connect_opts()
, retention => non_neg_integer()
, partition_days => non_neg_integer()
}.
%%%===================================================================
%%% API
%%%===================================================================
%% @doc Create a workflow specification
-spec workflow(atom(), config()) -> kflow:workflow().
workflow(Id, Config) ->
Config1 = Config#{ auto_commit => false
, flush_interval => 1000
},
kflow:mk_kafka_workflow(Id, pipe_spec(Config), Config1).
%%%===================================================================
Field transform functions copied from Seqializer
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
Transform undefined to " null "
%% @end
%%--------------------------------------------------------------------
-spec nullable(term()) -> term().
nullable(undefined) ->
[];
nullable(A) ->
A.
%%--------------------------------------------------------------------
%% @doc
%% erlang timestamp to epgsql timestamp
%% @end
%%--------------------------------------------------------------------
-spec timestamp(erlang:timestamp()) -> tuple().
timestamp(Timestamp = {_, _, _}) ->
Timestamp.
%%--------------------------------------------------------------------
%% @doc
Convert arbitrary term to string
%% @end
%%--------------------------------------------------------------------
-spec to_string(term(), integer()) -> string().
to_string(Term, Limit) ->
case io_lib:printable_latin1_list(Term) of
true ->
Str = Term;
false ->
Str = lists:flatten(io_lib:format("~p", [Term]))
end,
lists:sublist(Str, Limit).
%%--------------------------------------------------------------------
%% @doc
%% Convert function definition to string
%% @end
%%--------------------------------------------------------------------
-spec format_function({module(), atom(), arity()}) -> string().
format_function({Mod, Fun, Arity}) ->
Module = lists:sublist(atom_to_list(Mod), 30),
Function = lists:sublist(atom_to_list(Fun), 40),
lists:flatten(io_lib:format("~s:~s/~p", [Module, Function, Arity]));
format_function(_) ->
"no data".
-spec format_stacktrace(list()) -> string().
format_stacktrace(Stacktrace) ->
io_lib:format("~p", [Stacktrace]).
%%%===================================================================
Internal functions
%%%===================================================================
-spec pipe_spec(config()) -> kflow:pipe().
pipe_spec(Config = #{database := DbOpts}) ->
[ {mfd, fun parse_sysmon_message/2}
, {aggregate, kflow_buffer, #{}}
, {route_dependent,
fun(Record) ->
{Table, Fields0} = record_specs(Record),
Fields = [case I of
{A, _, _} -> A;
{A, _} -> A;
A -> A
end || I <- Fields0],
MapConfig = #{ database => DbOpts
, table => Table
, fields => Fields
, partitioning =>
#{ days => maps:get(partition_days, Config, 1)
, retention => maps:get(retention, Config, 30)
, index_fields => [ts]
}
},
{map, kflow_postgres, MapConfig}
end}
].
@private
-spec parse_sysmon_message(kflow:offset(), #{value := binary()}) ->
{true, atom(), map()} | false.
parse_sysmon_message(_Offset, #{value := Bin}) ->
try
[Record|Fields] = tuple_to_list(binary_to_term(Bin)),
case record_specs(Record) of
{_, FieldSpecs} when length(Fields) =:= length(FieldSpecs) ->
Ret = [case FieldSpec of
{Field, Fun, Arg} ->
{Field, ?MODULE:Fun(Val, Arg)};
{Field, Fun} ->
{Field, ?MODULE:Fun(Val)};
Field when is_atom(Field) ->
{Field, Val}
end || {FieldSpec, Val} <- lists:zip(FieldSpecs, Fields)],
{true, Record, Ret};
_ ->
?slog(warning, #{ what => "Unknown record"
, record => Record
, fields => Fields
}),
false
end
catch EC:Err:Stack ->
?slog(warning, #{ what => "Badly formatted sysmon message"
, message => Bin
, error_class => EC
, error => Err
, stacktrace => Stack
}),
false
end.
@private " Schema " of system monitor data
-spec record_specs(atom()) -> {_Table :: string(), _Fields :: list()} | undefined.
record_specs(op_stat_kafka_msg1) ->
{"opstat",
[ {name, to_string, 60}
, {data, to_string, 50}
, {unit, to_string, 10}
, {sess, nullable}
, node
, {ts, timestamp}
]};
record_specs(erl_top) ->
{"prc",
[ node
, {ts, timestamp}
, {pid, to_string, 34}
, dreductions
, dmemory
, reductions
, memory
, message_queue_len
, {current_function, format_function}
, {initial_call, format_function}
, {registered_name, to_string, 39}
, stack_size
, heap_size
, total_heap_size
, {current_stacktrace, format_stacktrace}
, group_leader
]};
record_specs(fun_top) ->
{"fun_top",
[ node
, {ts, timestamp}
, {'fun', format_function}
, fun_type
, num_processes
]};
record_specs(app_top) ->
{"app_top",
[ node
, {ts, timestamp}
, {application, to_string, 60}
, {unit, to_string, 60}
, value
]};
record_specs(node_role) ->
{"node_role",
[ node
, {ts, timestamp}
, data
]};
record_specs(_) ->
undefined.
| null | https://raw.githubusercontent.com/kafka4beam/kflow/2c44379a2934385a17fb504e7a933c859da7ab06/src/workflows/kflow_wf_sysmon_receiver.erl | erlang | ===================================================================
@doc This workflow receives `system_monitor' messages and puts
them to postgres tables.
== Configuration ==
The following parameters are mandatory:
Type: `brod:topic()'.
=== group_id ===
=== database ===
Type: `epgsql:connect_opts()'. See
@end
This module is made out of recycled old sequalizer code, answers
to why everything was desinged like that are lost in history.
===================================================================
API
Internal exports:
===================================================================
Types
===================================================================
===================================================================
API
===================================================================
@doc Create a workflow specification
===================================================================
===================================================================
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
erlang timestamp to epgsql timestamp
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Convert function definition to string
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | 2020 Klarna Bank AB ( publ )
= = = kafka_topic = = =
Type : ` binary ( ) ' . group consumer ID used by the workflow .
[ #L63 ]
-module(kflow_wf_sysmon_receiver).
-include("kflow_int.hrl").
-export([workflow/2]).
-export([ nullable/1
, timestamp/1
, to_string/2
, format_function/1
, format_stacktrace/1
]).
-export_type([config/0]).
-type config() ::
#{ kafka_topic := brod:topic()
, group_id := binary()
, database := epgsql:connect_opts()
, retention => non_neg_integer()
, partition_days => non_neg_integer()
}.
-spec workflow(atom(), config()) -> kflow:workflow().
workflow(Id, Config) ->
Config1 = Config#{ auto_commit => false
, flush_interval => 1000
},
kflow:mk_kafka_workflow(Id, pipe_spec(Config), Config1).
Field transform functions copied from Seqializer
Transform undefined to " null "
-spec nullable(term()) -> term().
nullable(undefined) ->
[];
nullable(A) ->
A.
-spec timestamp(erlang:timestamp()) -> tuple().
timestamp(Timestamp = {_, _, _}) ->
Timestamp.
Convert arbitrary term to string
-spec to_string(term(), integer()) -> string().
to_string(Term, Limit) ->
case io_lib:printable_latin1_list(Term) of
true ->
Str = Term;
false ->
Str = lists:flatten(io_lib:format("~p", [Term]))
end,
lists:sublist(Str, Limit).
-spec format_function({module(), atom(), arity()}) -> string().
format_function({Mod, Fun, Arity}) ->
Module = lists:sublist(atom_to_list(Mod), 30),
Function = lists:sublist(atom_to_list(Fun), 40),
lists:flatten(io_lib:format("~s:~s/~p", [Module, Function, Arity]));
format_function(_) ->
"no data".
-spec format_stacktrace(list()) -> string().
format_stacktrace(Stacktrace) ->
io_lib:format("~p", [Stacktrace]).
Internal functions
-spec pipe_spec(config()) -> kflow:pipe().
pipe_spec(Config = #{database := DbOpts}) ->
[ {mfd, fun parse_sysmon_message/2}
, {aggregate, kflow_buffer, #{}}
, {route_dependent,
fun(Record) ->
{Table, Fields0} = record_specs(Record),
Fields = [case I of
{A, _, _} -> A;
{A, _} -> A;
A -> A
end || I <- Fields0],
MapConfig = #{ database => DbOpts
, table => Table
, fields => Fields
, partitioning =>
#{ days => maps:get(partition_days, Config, 1)
, retention => maps:get(retention, Config, 30)
, index_fields => [ts]
}
},
{map, kflow_postgres, MapConfig}
end}
].
@private
-spec parse_sysmon_message(kflow:offset(), #{value := binary()}) ->
{true, atom(), map()} | false.
parse_sysmon_message(_Offset, #{value := Bin}) ->
try
[Record|Fields] = tuple_to_list(binary_to_term(Bin)),
case record_specs(Record) of
{_, FieldSpecs} when length(Fields) =:= length(FieldSpecs) ->
Ret = [case FieldSpec of
{Field, Fun, Arg} ->
{Field, ?MODULE:Fun(Val, Arg)};
{Field, Fun} ->
{Field, ?MODULE:Fun(Val)};
Field when is_atom(Field) ->
{Field, Val}
end || {FieldSpec, Val} <- lists:zip(FieldSpecs, Fields)],
{true, Record, Ret};
_ ->
?slog(warning, #{ what => "Unknown record"
, record => Record
, fields => Fields
}),
false
end
catch EC:Err:Stack ->
?slog(warning, #{ what => "Badly formatted sysmon message"
, message => Bin
, error_class => EC
, error => Err
, stacktrace => Stack
}),
false
end.
@private " Schema " of system monitor data
-spec record_specs(atom()) -> {_Table :: string(), _Fields :: list()} | undefined.
record_specs(op_stat_kafka_msg1) ->
{"opstat",
[ {name, to_string, 60}
, {data, to_string, 50}
, {unit, to_string, 10}
, {sess, nullable}
, node
, {ts, timestamp}
]};
record_specs(erl_top) ->
{"prc",
[ node
, {ts, timestamp}
, {pid, to_string, 34}
, dreductions
, dmemory
, reductions
, memory
, message_queue_len
, {current_function, format_function}
, {initial_call, format_function}
, {registered_name, to_string, 39}
, stack_size
, heap_size
, total_heap_size
, {current_stacktrace, format_stacktrace}
, group_leader
]};
record_specs(fun_top) ->
{"fun_top",
[ node
, {ts, timestamp}
, {'fun', format_function}
, fun_type
, num_processes
]};
record_specs(app_top) ->
{"app_top",
[ node
, {ts, timestamp}
, {application, to_string, 60}
, {unit, to_string, 60}
, value
]};
record_specs(node_role) ->
{"node_role",
[ node
, {ts, timestamp}
, data
]};
record_specs(_) ->
undefined.
|
7804400ef941e68ad67f334f87436486b3a7a06936d766427138fa9e76eeb0d5 | clj-kondo/clj-kondo | interop.cljc | (ns interop
{:no-doc true}
(:refer-clojure :exclude [eval demunge var?])
(:require [clojure.string :as str]
[sci.impl.macros :as macros]
[sci.impl.types :as t]
[sci.impl.vars :as vars]
[sci.lang :as lang]))
(defn dynamic-var
([name]
(dynamic-var name nil (meta name)))
([name init-val]
(dynamic-var name init-val (meta name)))
([name init-val meta]
(let [meta (assoc meta :dynamic true :name (identity name))]
(sci.lang.Var. init-val name meta false false))))
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo/c273b5d3f516556d38add478191260ecb9d03223/corpus/aliased_namespaces/interop.cljc | clojure | (ns interop
{:no-doc true}
(:refer-clojure :exclude [eval demunge var?])
(:require [clojure.string :as str]
[sci.impl.macros :as macros]
[sci.impl.types :as t]
[sci.impl.vars :as vars]
[sci.lang :as lang]))
(defn dynamic-var
([name]
(dynamic-var name nil (meta name)))
([name init-val]
(dynamic-var name init-val (meta name)))
([name init-val meta]
(let [meta (assoc meta :dynamic true :name (identity name))]
(sci.lang.Var. init-val name meta false false))))
|
|
bf04adcdf8724f47d0a26cebd0ad237f2299c72b8090f96ad57488b18a64e464 | lukaszcz/coqhammer | msg.ml |
open Feedback
let error s = msg_notice (Pp.str ("Error: " ^ s))
let notice s = msg_notice (Pp.str s)
let info s = msg_info (Pp.str s)
| null | https://raw.githubusercontent.com/lukaszcz/coqhammer/fe83fb0eaf33f56da9ea1983114d0d94a2c41b9b/src/plugin/msg.ml | ocaml |
open Feedback
let error s = msg_notice (Pp.str ("Error: " ^ s))
let notice s = msg_notice (Pp.str s)
let info s = msg_info (Pp.str s)
|
|
32d50651998efe839b266e882f819ea8de96b37543575ccce9f6a0cfd734b1ba | rbardou/red | command.ml | open Misc
module H = Help
(* Built-in command definitions. *)
type command =
{
name: string;
help: (Help.maker -> unit) option;
partial: Redl.Typing.command Redl.Typing.partial;
}
(* List of all built-in commands. *)
let commands: command list ref = ref []
type _ typ =
| Command: Redl.Typing.command typ
| Function: { parameter_name: string; parameter_type: ('p, 'p) Redl.Typing.typ; result: 'r typ } -> ('p -> 'r) typ
(* Make a parameterized command type. *)
let (@->) (parameter_name, parameter_type) result =
Function { parameter_name; parameter_type; result }
let (-:) name (typ: (_, _) Redl.Typing.typ) =
name, typ
(* Add a command, parameterized or not, to the list of built-in commands. *)
let define (type f) name ?help (typ: f typ) (f: f) =
(* Declare command. *)
let rec make_type: type f. f typ -> (f, Redl.Typing.command) Redl.Typing.typ = function
| Command ->
Command
| Function { parameter_type; result } ->
Function (parameter_type, make_type result)
in
let command =
{
name;
help;
partial = Partial { typ = make_type typ; value = Constant f };
}
in
commands := command :: !commands;
(* Declare help page. *)
let rec get_parameters: type f. _ -> f typ -> _ = fun acc typ ->
match typ with
| Command ->
List.rev acc
| Function { parameter_name; parameter_type; result } ->
get_parameters ((parameter_name, Redl.Typing.Type parameter_type) :: acc) result
in
Help.overload_command name ?help (get_parameters [] typ)
let setup_initial_env overload_command =
let add command = overload_command command.name command.partial in
List.iter add !commands
let bind (context: State.Context.t) (state: State.t) (key: Key.t) (command: string) =
let ast = Redl.parse_string command in
let command =
Parse , type , but do not execute yet .
state.run_string command
in
let context_bindings = State.get_context_bindings context state in
let context_bindings = Key.Map.add key command context_bindings in
state.bindings <- State.Context_map.add context context_bindings state.bindings;
Help.bind context key ast
(******************************************************************************)
(* Helpers *)
(******************************************************************************)
let abort = State.abort
let abort_with_error = State.abort_with_error
Change cursor position ( apply [ f ] to get new coordinates ) .
Update [ ] unless [ vertical ] .
Reset selection if [ reset_selection ] .
Update [preferred_x] unless [vertical].
Reset selection if [reset_selection]. *)
let move_cursor reset_selection vertical (view: File.view) (cursor: File.cursor) f =
let position = cursor.position in
let x, y = f view.file.text (if vertical then cursor.preferred_x else position.x) position.y in
if reset_selection then (
let selection_start = cursor.selection_start in
selection_start.x <- x;
selection_start.y <- y;
);
position.x <- x;
position.y <- y;
cursor.preferred_x <- if vertical then cursor.preferred_x else x
Change cursor position ( apply [ f ] to get new coordinates ) .
Update [ ] unless [ vertical ] .
Reset selection if [ reset_selection ] .
Update [preferred_x] unless [vertical].
Reset selection if [reset_selection]. *)
let move reset_selection vertical f (state: State.t) =
let view = State.get_focused_view state in
(
File.foreach_cursor view @@ fun cursor ->
move_cursor reset_selection vertical view cursor f
);
File.recenter_if_needed view
let focus_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
State.set_focus state panel
let swap_view_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
let panel_view = Panel.get_current_main_view panel in
Panel.set_current_view panel (File.copy_view (Panel.get_current_main_view state.focus));
Panel.set_current_view state.focus (File.copy_view panel_view);
State.set_focus state panel
let copy_view_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
Panel.set_current_view panel (File.copy_view (Panel.get_current_main_view state.focus))
let move_after_scroll (view: File.view) old_scroll =
let delta = view.scroll_y - old_scroll in
let text = view.file.text in
let max_y = Text.get_line_count text - 1 in
File.if_only_one_cursor view @@ fun cursor ->
cursor.position.y <- max 0 (min max_y (cursor.position.y + delta));
cursor.position.x <- min (Text.get_line_length cursor.position.y text) cursor.preferred_x;
cursor.selection_start.x <- cursor.position.x;
cursor.selection_start.y <- cursor.position.y
let select_all view =
File.foreach_cursor view @@ fun cursor ->
cursor.selection_start.x <- 0;
cursor.selection_start.y <- 0;
let text = view.file.text in
let max_y = Text.get_line_count text - 1 in
cursor.position.y <- max_y;
cursor.position.x <- Text.get_line_length max_y text
let save (file: File.t) filename =
if filename <> "" then (
file.name <- filename;
File.set_filename file (Some filename);
if not (System.file_exists filename) then
Text.output_file filename file.text
else
(
let perm =
match Unix.stat filename with
| exception Unix.Unix_error _ ->
None
| stat ->
Some stat.st_perm
in
let temporary_filename = System.find_temporary_filename filename in
Text.output_file ?perm temporary_filename file.text;
System.move_file temporary_filename filename;
);
Log.info "Wrote: %s" filename;
file.modified <- false;
(* Clear undo stack (at the very least we should set the modified flags in all undo points). *)
file.undo_stack <- [];
file.redo_stack <- [];
)
let prompt ?history ?(default = "") (prompt_text: string) (state: State.t) (validate_prompt: string -> unit) =
let view = State.get_focused_main_view state in
let prompt_view = File.create_view Prompt (File.create ?history prompt_text (Text.of_utf8_string default)) in
select_all prompt_view;
view.prompt <-
Some {
prompt_text;
validate_prompt;
prompt_view;
}
let rec prompt_confirmation ?(repeated = 0) message state confirm =
let message = if repeated = 1 then "Please answer yes or no. " ^ message else message in
prompt ~default: "no" message state @@ fun response ->
if String.lowercase_ascii response = "yes" then
confirm ()
else if String.lowercase_ascii response = "no" then
()
else
prompt_confirmation ~repeated: (min 2 (repeated + 1)) message state confirm
let deduplicate_choices (choices: File.choice_item list): File.choice_item list =
let rec loop exists_before acc choices =
match choices with
| [] ->
List.rev acc
| ((_, choice) as item) :: tail ->
if String_set.mem choice exists_before then
loop exists_before acc tail
else
loop (String_set.add choice exists_before) (item :: acc) tail
in
loop String_set.empty [] choices
let choose_from_list ?(default = "") ?(choice = -1) (choice_prompt_text: string)
(choices: File.choice_item list) (state: State.t)
(validate_choice: string -> unit) =
let choices = deduplicate_choices choices in
(* Create choice file and view. *)
let choice_view =
let file = File.create choice_prompt_text (Text.of_utf8_string default) in
let view = File.create_view (List_choice { choice_prompt_text; validate_choice; choices; choice }) file in
select_all view;
view
in
(* Replace current view with choice view. *)
State.set_focused_view state choice_view
let compare_names a b =
(* By using uppercase instead of lowercase, symbols like _ are higher in the choice list. *)
String.compare (String.uppercase_ascii a) (String.uppercase_ascii b)
let sort_names list =
List.sort compare_names list
let choose_from_file_system ?default (prompt: string) (state: State.t) (validate: string -> unit) =
let append_dir_sep_if_needed filename =
let length = String.length filename in
let sep_length = String.length Filename.dir_sep in
if
length < sep_length ||
String.sub filename (length - sep_length) sep_length <> Filename.dir_sep
then
filename ^ Filename.dir_sep
else
filename
in
let starting_directory, default =
match default with
| None ->
System.get_cwd (), None
| Some default ->
let base = Filename.basename default in
let base =
if
base = Filename.current_dir_name ||
System.is_root_directory base
then
None
else
Some base
in
let dir =
let dir = Filename.dirname default in
if dir = Filename.current_dir_name then
System.get_cwd ()
else
System.make_filename_absolute dir
in
dir, base
in
let starting_directory = append_dir_sep_if_needed starting_directory in
let rec browse ?default directory =
let choices =
let directories, files =
List.partition
(fun filename -> System.is_directory (Filename.concat directory filename))
(System.ls directory)
in
let directories =
directories
|> sort_names
|> List.map (fun name -> File.Directory, name ^ Filename.dir_sep)
in
let files =
files
|> sort_names
|> List.map (fun name -> File.Other, name)
in
(File.Directory, Filename.parent_dir_name) ::
directories @
files
in
let choice =
match default with
| None ->
(* The filter starts empty. Let's select the parent directory by default. *)
Some 0
| Some _ ->
None
in
choose_from_list ?default ?choice (prompt ^ directory) choices state @@ fun choice ->
if choice = "" then
()
else if choice = Filename.current_dir_name then
browse directory
else if choice = Filename.parent_dir_name || choice = append_dir_sep_if_needed Filename.parent_dir_name then
browse (append_dir_sep_if_needed (Filename.dirname directory))
else
let filename = Filename.concat directory choice in
if System.is_directory filename then
browse filename
else
validate filename
in
browse ?default (append_dir_sep_if_needed starting_directory)
let display_help (state: State.t) make_page =
let topic, text, style, links = make_page state in
let file = File.create ~read_only: true "help" text in (* TODO: include topic in name? *)
let view = File.create_view (Help { topic; links }) file in
view.style <- style;
State.set_focused_view state view
let ocaml_stylist =
File.Stylist_module {
equivalent = Ocaml.Stylist.equivalent;
start = Ocaml.Stylist.start;
add_char = Ocaml.Stylist.add_char;
end_of_file = Ocaml.Stylist.end_of_file;
}
let redl_stylist =
File.Stylist_module {
equivalent = Redl.Stylist.equivalent;
start = Redl.Stylist.start;
add_char = Redl.Stylist.add_char;
end_of_file = Redl.Stylist.end_of_file;
}
let set_stylist (view: File.view) =
if view.kind = File then (
let stylist =
match view.file.filename with
| None ->
None
| Some filename ->
if Filename.check_suffix filename ".ml" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mli" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mll" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mly" then
Some ocaml_stylist
else if Filename.check_suffix filename ".red" then
Some redl_stylist
else
None
in
File.set_stylist_module view stylist
)
let () = File.choose_stylist_automatically := set_stylist
let split_panel direction pos (state: State.t) =
let view = State.get_focused_main_view state in
let new_view =
match view.kind with
| Prompt | Search _ | List_choice _ | Help _ ->
State.get_default_view state
| File ->
File.copy_view view
in
match
Layout.replace_panel state.focus (
Layout.split direction ~pos ~sep: (direction = Horizontal)
(Layout.single state.focus)
(Layout.single (Panel.create new_view))
) state.layout
with
| None ->
abort_with_error "failed to replace current panel: panel not found in current layout"
| Some new_layout ->
State.set_layout state new_layout
(******************************************************************************)
(* Definitions *)
(******************************************************************************)
let help { H.add } =
add "Do nothing."
let () = define "noop" ~help Command @@ fun state ->
()
let help { H.line; par } =
line "Exit the editor.";
par ();
line "Prompt for confirmation if there are modified files."
let () = define "quit" ~help Command @@ fun state ->
let modified_files = List.filter (fun (file: File.t) -> file.modified) state.files in
let modified_file_count = List.length modified_files in
if modified_file_count = 0 then
raise State.Exit
else
let message =
if modified_file_count = 1 then
"There is 1 modified file, really exit? "
else
"There are " ^ string_of_int modified_file_count ^ " modified file(s), really exit? "
in
prompt_confirmation message state @@ fun () ->
raise State.Exit
let help { H.line; add; add_link; nl; add_parameter; par } =
line "Open help.";
par ();
add "Open help page specified by "; add_parameter "page"; add "."; nl ();
line "It can be a command name or a topic.";
add "If "; add_parameter "page"; add " is not specified, prompt for page name."; nl ();
par ();
line "Press Q to go back to what you were doing."
let () = define "help" ~help Command @@ fun state ->
let pages =
List.map (fun page -> File.Recent, page) (State.get_history Help_page state) @
List.map (fun page -> File.Other, page) (Help.make_page_list ())
in
choose_from_list ~choice: 0 "Open help page: " pages state @@ fun page ->
State.add_history Help_page page state;
display_help state (Help.page page)
let () = define "help" ("page" -: String @-> Command) @@ fun page state ->
display_help state (Help.page page)
let help { H.line } =
line "Follow a link to another help page to get more information."
let () = define "follow_link" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.kind with
| Help { links } ->
File.if_only_one_cursor view @@ fun cursor ->
(
match Text.get cursor.position.x cursor.position.y links with
| None | Some None ->
()
| Some (Some link) ->
display_help state (Help.page link)
)
| _ ->
()
let help { H.line; par } =
line "Cancel what you are doing.";
par ();
line "If you currently have multiple cursors, remove all but one.";
line "Else, if you are in a prompt, a list of choices or in a help panel, close it."
let () = define "cancel" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.prompt with
| Some _ ->
view.prompt <- None
| None ->
match view.search with
| Some _ ->
(* TODO: restore cursor positions *)
view.search <- None
| None ->
match view.cursors with
| first :: _ :: _ ->
view.cursors <- [ first ]
| _ ->
match view.kind with
| Prompt | Search _ | Help _ | List_choice _ ->
if not (Panel.kill_current_view state.focus) then
let view = State.get_default_view state in
State.set_focused_view state view
| File ->
()
let help { H.line; par; see_also } =
line "Save file.";
par ();
line "If current file has no name, prompt for a filename.";
see_also [ "save_as" ]
let () = define "save" ~help Command @@ fun state ->
let file_to_save = State.get_focused_file state in
match file_to_save.filename with
| None ->
choose_from_file_system "Save as: " state (save file_to_save)
| Some filename ->
save file_to_save filename
let help { H.line; par; see_also } =
line "Save file.";
par ();
line "Prompt for a filename even if current file already has one.";
line "Existing file is not deleted.";
see_also [ "save" ]
let () = define "save_as" ~help Command @@ fun state ->
let file_to_save = State.get_focused_file state in
choose_from_file_system ?default: file_to_save.filename "Save as: " state (save file_to_save)
let help { H.line; par; see_also } =
line "Open a file in the current panel.";
par ();
line "Prompt for the filename to open.";
see_also [ "new"; "switch_file" ]
let () = define "open" ~help Command @@ fun state ->
let panel = state.focus in
choose_from_file_system "Open: " state @@ fun filename ->
if not (System.file_exists filename) then abort "File does not exist: %S" filename;
let file = State.create_file_loading state filename in
let view = File.create_view File file in
Panel.set_current_view panel view
let help { H.line; par; see_also } =
line "Create a new empty file.";
par ();
line "The file is not actually created on disk until you save.";
see_also [ "open"; "switch_file" ]
let () = define "new" ~help Command @@ fun state ->
let file = State.create_empty_file state in
let view = File.create_view File file in
State.set_focused_view state view
let help { H.line; see_also } =
line "Remove current panel from current layout.";
see_also [ "split_panel_vertically"; "split_panel_horizontally"; "close_file" ]
let () = define "close_panel" ~help Command @@ fun state ->
State.remove_panel state.focus state
let help { H.line; par; see_also } =
line "Close current file.";
par ();
line "Remove it from all panels.";
par ();
line "Prompt for confirmation if file has been modified.";
see_also [ "close_panel" ]
let () = define "close_file" ~help Command @@ fun state ->
let file = State.get_focused_file state in
if file.modified then
prompt_confirmation "File has been modified, really close it? " state @@ fun () ->
State.close_file file state
else
State.close_file file state
let help { H.line; par; see_also } =
line "Move cursor to the right.";
par ();
line "All cursors move one character to the right.";
line "If there is no character to the right in the current line,";
line "move to the beginning of the next line instead;";
line "if there is no next line, don't move at all.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_left"; "move_down"; "move_up";
"select_right"; "move_end_of_line"; "move_right_word";
]
let () = define "move_right" ~help Command @@ move true false File.move_right
let help { H.line; par; see_also } =
line "Move cursor to the left.";
par ();
line "All cursors move one character to the left.";
line "If there is no character to the left in the current line,";
line "move to the end of the previous line instead;";
line "if there is no previous line, don't move at all.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_right"; "move_down"; "move_up";
"select_left"; "move_beginning_of_line"; "move_left_word";
]
let () = define "move_left" ~help Command @@ move true false File.move_left
let help { H.line; par; see_also } =
line "Move cursor to the next line.";
par ();
line "All cursors move one line down.";
line "If there is no line below do nothing.";
line "Cursors move to their preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
par ();
line "Reset selection.";
see_also [
"move_up"; "move_right"; "move_left";
"select_down"; "move_end_of_file"; "move_down_paragraph";
]
let () = define "move_down" ~help Command @@ move true true File.move_down
let help { H.line; par; see_also } =
line "Move cursor to the previous line.";
par ();
line "All cursors move one line up.";
line "If there is no line above do nothing.";
line "Cursors move to their preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
par ();
line "Reset selection.";
see_also [
"move_down"; "move_right"; "move_left";
"select_down"; "move_beginning_of_file"; "move_up_paragraph";
]
let () = define "move_up" ~help Command @@ move true true File.move_up
let help { H.line; par; see_also } =
line "Move cursor to the end of the current line.";
par ();
line "All cursors move just after the character at the end of the current line.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_right"; "select_end_of_line";
"move_beginning_of_line"; "move_end_of_file";
]
let () = define "move_end_of_line" ~help Command @@ move true false File.move_end_of_line
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the current line.";
par ();
line "All cursors move to the first character of the current line.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_left"; "select_beginning_of_line";
"move_end_of_line"; "move_beginning_of_file";
]
let () = define "move_beginning_of_line" ~help Command @@ move true false File.move_beginning_of_line
let help { H.line; par; see_also } =
line "Move cursor to the end of the current file.";
par ();
line "All cursors move just after the last character of the last line.";
par ();
line "Reset selection and preferred column.";
see_also [
"select_end_of_file"; "move_end_of_line"; "move_beginning_of_file";
]
let () = define "move_end_of_file" ~help Command @@ move true false File.move_end_of_file
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the current file.";
par ();
line "All cursors move to the first character of the first line.";
par ();
line "Reset selection and preferred column.";
see_also [
"select_beginning_of_file"; "move_beginning_of_line"; "move_end_of_file";
]
let () = define "move_beginning_of_file" ~help Command @@ move true false File.move_beginning_of_file
let help { H.line; par; see_also } =
line "Move cursor to the end of the word.";
par ();
line "All cursors move to the first character after the current word,";
line "or of the next word if they are not in a word.";
par ();
line "A word is a sequence of letters or digits.";
par ();
line "Reset selection and preferred column.";
see_also [ "select_right_word"; "move_left_word" ]
let () = define "move_right_word" ~help Command @@ move true false File.move_right_word
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the word.";
par ();
line "All cursors move to the first character of the current word,";
line "or of the previous word if they are not in a word.";
par ();
line "A word is a sequence of letters or digits.";
par ();
line "Reset selection and preferred column.";
see_also [ "select_left_word"; "move_right_word" ]
let () = define "move_left_word" ~help Command @@ move true false File.move_left_word
let help { H.line; par; see_also } =
line "Move cursor to the end of the paragraph.";
par ();
line "All cursors move to the first line after the current paragraph,";
line "or of the next paragraph if they are not in a paragraph.";
par ();
line "A paragraph is a sequence of non-empty lines.";
par ();
line "Reset selection.";
see_also [ "select_down_paragraph"; "move_up_paragraph" ]
let () = define "move_down_paragraph" ~help Command @@ move true false File.move_down_paragraph
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the paragraph.";
par ();
line "All cursors move to the first line before the current paragraph,";
line "or of the previous paragraph if they are not in a paragraph.";
par ();
line "A paragraph is a sequence of non-empty lines.";
par ();
line "Reset selection.";
see_also [ "select_up_paragraph"; "move_down_paragraph" ]
let () = define "move_up_paragraph" ~help Command @@ move true false File.move_up_paragraph
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_right"; add " but does not reset selection."; nl ()
let () = define "select_right" ~help Command @@ move false false File.move_right
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_left"; add " but does not reset selection."; nl ()
let () = define "select_left" ~help Command @@ move false false File.move_left
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_down"; add " but does not reset selection."; nl ()
let () = define "select_down" ~help Command @@ move false true File.move_down
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_up"; add " but does not reset selection."; nl ()
let () = define "select_up" ~help Command @@ move false true File.move_up
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_end_of_line"; add " but does not reset selection."; nl ()
let () = define "select_end_of_line" ~help Command @@ move false false File.move_end_of_line
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_beginning_of_line"; add " but does not reset selection."; nl ()
let () = define "select_beginning_of_line" ~help Command @@ move false false File.move_beginning_of_line
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_end_of_file"; add " but does not reset selection."; nl ()
let () = define "select_end_of_file" ~help Command @@ move false false File.move_end_of_file
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_beginning_of_file"; add " but does not reset selection."; nl ()
let () = define "select_beginning_of_file" ~help Command @@ move false false File.move_beginning_of_file
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_right_word"; add " but does not reset selection."; nl ()
let () = define "select_right_word" ~help Command @@ move false false File.move_right_word
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_left_word"; add " but does not reset selection."; nl ()
let () = define "select_left_word" ~help Command @@ move false false File.move_left_word
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_down_paragraph"; add " but does not reset selection."; nl ()
let () = define "select_down_paragraph" ~help Command @@ move false false File.move_down_paragraph
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_up_paragraph"; add " but does not reset selection."; nl ()
let () = define "select_up_paragraph" ~help Command @@ move false false File.move_up_paragraph
let help { H.line; par; see_also } =
line "Select all text.";
par ();
line "Set selection of all cursors to start at the beginning of the file.";
line "Set position of all cursors to the end of the file.";
line "Reset preferred column.";
see_also [
"select_right";
"select_end_of_line";
"select_end_of_file";
"select_right_word";
"select_down_paragraph";
]
let () = define "select_all" ~help Command @@ fun state ->
select_all (State.get_focused_view state)
let help { H.line; par; see_also } =
line "Give focus to the panel at the right of the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_left"; "focus_down"; "focus_up";
"swap_view_right"; "copy_view_right";
"split_panel_horizontally";
]
let () = define "focus_right" ~help Command @@ focus_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Give focus to the panel at the left of the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_down"; "focus_up";
"swap_view_left"; "copy_view_left";
"split_panel_horizontally";
]
let () = define "focus_left" ~help Command @@ focus_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Give focus to the panel below the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_left"; "focus_up";
"swap_view_down"; "copy_view_down";
"split_panel_vertically";
]
let () = define "focus_down" ~help Command @@ focus_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Give focus to the panel above the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_left"; "focus_down";
"swap_view_up"; "copy_view_up";
"split_panel_vertically";
]
let () = define "focus_up" ~help Command @@ focus_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel at its right.";
see_also [
"swap_view_left"; "swap_view_down"; "swap_view_up";
"copy_view_right";
"focus_right"; "split_panel_horizontally";
]
let () = define "swap_view_right" ~help Command @@ swap_view_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel at its left.";
see_also [
"swap_view_right"; "swap_view_down"; "swap_view_up";
"copy_view_left";
"focus_left"; "split_panel_horizontally";
]
let () = define "swap_view_left" ~help Command @@ swap_view_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel below it.";
see_also [
"swap_view_up"; "swap_view_right"; "swap_view_left";
"copy_view_down";
"focus_down"; "split_panel_vertically";
]
let () = define "swap_view_down" ~help Command @@ swap_view_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel above it.";
see_also [
"swap_view_down"; "swap_view_right"; "swap_view_left";
"copy_view_up";
"focus_up"; "split_panel_vertically";
]
let () = define "swap_view_up" ~help Command @@ swap_view_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Copy current view into the panel at its right.";
see_also [
"copy_view_left"; "copy_view_down"; "copy_view_up";
"swap_view_right";
"focus_right"; "split_panel_horizontally";
]
let () = define "copy_view_right" ~help Command @@ copy_view_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Copy current view into the panel at its left.";
see_also [
"copy_view_right"; "copy_view_down"; "copy_view_up";
"swap_view_left";
"focus_left"; "split_panel_horizontally";
]
let () = define "copy_view_left" ~help Command @@ copy_view_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Copy current view into the panel below it.";
see_also [
"copy_view_up"; "copy_view_right"; "copy_view_left";
"swap_view_down";
"focus_down"; "split_panel_vertically";
]
let () = define "copy_view_down" ~help Command @@ copy_view_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Copy current view into the panel above it.";
see_also [
"copy_view_down"; "copy_view_right"; "copy_view_left";
"swap_view_up";
"focus_up"; "split_panel_vertically";
]
let () = define "copy_view_up" ~help Command @@ copy_view_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Scroll half a page down.";
par ();
line "If there is only one cursor, also move it half a page down.";
line "It moves to its preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
see_also [ "scroll_up" ]
let () = define "scroll_down" ~help Command @@ fun state ->
let view = State.get_focused_view state in
let text = view.file.text in
(* Scroll. *)
let max_y = Text.get_line_count text - 1 in
let max_scroll =
Last line is often empty , so we want to see at least the line before that , unless panel height is 1 .
if view.height <= 1 then max_y else max_y - 1
in
let old_scroll = view.scroll_y in
view.scroll_y <- min max_scroll (view.scroll_y + view.height / 2);
(* Move cursor. *)
move_after_scroll view old_scroll
let help { H.line; par; see_also } =
line "Scroll half a page up.";
par ();
line "If there is only one cursor, also move it half a page up.";
line "It moves to its preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
see_also [ "scroll_down" ]
let () = define "scroll_up" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(* Scroll. *)
let old_scroll = view.scroll_y in
view.scroll_y <- max 0 (view.scroll_y - view.height / 2);
(* Move cursor. *)
move_after_scroll view old_scroll
let help { H.line; par; see_also } =
line "Split line at cursor.";
par ();
line "The end of the line moves to a new line below.";
line "Cursor moves to the beginning of this new line."
let () = define "insert_new_line" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.replace_selection_by_new_line view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the next character.";
par ();
line "If cursor is at the end of a line, merge the next line instead.";
line "If selection is not empty, delete it instead.";
line "Reset preferred column.";
see_also [
"delete_character_backwards";
"delete_end_of_line";
"delete_end_of_word";
]
let () = define "delete_character" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.delete_selection_or_character view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the previous character.";
par ();
line "If cursor is at the beginning of a line, merge this line";
line "into the previous line instead.";
line "If selection is not empty, delete it instead.";
line "Reset preferred column.";
see_also [
"delete_character";
"delete_beginning_of_word";
]
let () = define "delete_character_backwards" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.delete_selection_or_character_backwards view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the end of the current line.";
par ();
line "If cursor is at the end of a line, merge the next line instead.";
see_also [
"delete_character";
"delete_end_of_word";
]
let () = define "delete_end_of_line" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
Can not just use [ move_end_of_line ] here because we want to delete the if we are at the end of the line .
let x = cursor.position.x in
let y = cursor.position.y in
let length = Text.get_line_length y text in
if x >= length then
0, y + 1
else
length, y
);
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the end of the current word.";
par ();
line "If cursor is not in a word, delete until the end of the next word.";
see_also [
"move_right_word";
"delete_character";
"delete_beginning_of_word";
]
let () = define "delete_end_of_word" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
File.move_right_word text cursor.position.x cursor.position.y
);
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the beginning of the current word.";
par ();
line "If cursor is not in a word, delete until the beginning of the previous word.";
see_also [
"move_left_word";
"delete_character_backwards";
"delete_end_of_word";
]
let () = define "delete_beginning_of_word" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
File.move_left_word text cursor.position.x cursor.position.y
);
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link } =
line "Create one cursor per selected line.";
par ();
add "Use "; add_link "cancel"; add " to go back to one cursor."; nl ();
par ();
add "Commands which apply to cursors, such as "; add_link "move_right_word";
add " or "; add_link "delete_word"; add ","; nl ();
line "are applied to all cursors.";
par ();
add "Clipboard commands, such as "; add_link "copy"; add " and "; add_link "paste";
add ", use the cursor clipboard instead"; nl ();
line "of the global clipboard. This means that you can have each cursor copy its";
line "own selection, and paste it somewhere else.";
par ();
add "Other commands, such as "; add_link "save_as"; add ", are only run once."; nl ()
let () = define "create_cursors_from_selection" ~help Command @@ fun state ->
let view = State.get_focused_view state in
let create_cursors_from_cursor (cursor: File.cursor) =
let first, last, reverse =
let sel_y = cursor.selection_start.y in
let cur_y = cursor.position.y in
if sel_y <= cur_y then
sel_y, cur_y, true
else
cur_y, sel_y, false
in
let rec range acc first last =
if last < first then
acc
else
range (last :: acc) first (last - 1)
in
let text = view.file.text in
let create_cursor y = File.create_cursor (min (Text.get_line_length y text) cursor.position.x) y in
let cursors = List.map create_cursor (range [] first last) in
if reverse then List.rev cursors else cursors
in
let cursors = List.map create_cursors_from_cursor view.cursors in
File.set_cursors view (List.flatten cursors)
let help { H.add; line; nl; par; add_link; see_also } =
line "Copy selection to clipboard.";
par ();
line "If there is only one cursor, selection is copied to the global clipboard.";
line "It can be pasted from any view, in any file.";
par ();
add "If there are several cursor (see "; add_link "create_cursors_from_selection";
add "),"; nl ();
line "the selection of each cursor is copied to the local clipboard of each cursor.";
see_also [ "cut"; "paste" ]
let () = define "copy" ~help Command @@ fun state -> File.copy state.clipboard (State.get_focused_view state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Copy selection to clipboard, then delete selection.";
see_also [ "copy"; "paste" ]
let () = define "cut" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.cut state.clipboard view;
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link; see_also } =
line "Paste from clipboard.";
par ();
line "Selection is deleted before pasting.";
par ();
line "If there is only one cursor, paste selection from the global clipboard.";
add "If there are several cursor (see "; add_link "create_cursors_from_selection";
add "),"; nl ();
line "for each cursor, paste the clipboard of this cursor at its position.";
see_also [ "cut"; "paste" ]
let () = define "paste" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.paste state.clipboard view;
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link; see_also } =
line "Undo recent edits.";
par ();
line "You can undo repeatedly until the point where the current file was last saved.";
see_also [ "redo" ]
let () = define "undo" ~help Command @@ fun state -> File.undo (State.get_focused_file state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Redo what was recently undone.";
par ();
line "You can redo repeatedly until you come back to the point of the first undo";
line "of the last undo sequence.";
par ();
line "Any edit which is not a redo or an undo will remove the possibility to redo.";
see_also [ "undo" ]
let () = define "redo" ~help Command @@ fun state -> File.redo (State.get_focused_file state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Validate selected choice.";
par ();
add "In a prompt, such as the one which appears when you "; add_link "quit"; add ","; nl ();
line "validate the text you typed.";
par ();
add "In a list of choices, such as the one which appears when you "; add_link "save_as"; add ","; nl ();
line "validate selected choice. If you did not select anything,";
line "validate the text you typed instead."
let () = define "validate" ~help Command @@ fun state ->
let panel = state.focus in
let view = Panel.get_current_main_view panel in
match view.prompt with
| Some { validate_prompt; prompt_view } ->
view.prompt <- None;
validate_prompt (Text.to_string prompt_view.file.text)
| None ->
match view.search with
| Some _ ->
view.search <- None
| None ->
match view.kind with
| List_choice { validate_choice; choice; choices } ->
let filter = Text.to_string view.file.text in
if not (Panel.kill_current_view panel) then
(* User killed the file from which we spawned the list choice?
This should be a rare occurrence. *)
(* TODO: if validation results in opening a file, do not create a new empty file *)
(
let view = State.get_default_view state in
Panel.set_current_view panel view;
);
(
match List.nth (filter_choices filter choices) choice with
| exception (Invalid_argument _ | Failure _) ->
validate_choice filter
| _, choice ->
validate_choice choice
)
| _ ->
abort "Focused panel has no prompt."
let help { H.add; line; nl; par; add_link; see_also } =
line "Execute a command.";
par ();
add "Prompt for a command name, such as "; add_link "save_as"; add " or "; add_link "move_left"; add ","; nl ();
line "and execute this command.";
see_also [ "execute_process" ]
let () = define "execute_command" ~help Command @@ fun state ->
let commands =
(* We use [Help.command_page_list] instead of [!commands], because [!commands] contains duplicates.
So this is more efficient.
Also, if we decide to hide a command from the help panel, we can also hide it from auto-completion. *)
List.map (fun page -> File.Recent, page) (State.get_history Command state) @
List.map (fun page -> File.Other, page) (Help.command_page_list ())
in
choose_from_list ~choice: 0 "Execute command: " commands state @@ fun command ->
State.add_history Command command state;
state.run_string command state
let help { H.add; line; nl; par; add_link; see_also } =
line "Execute an external command.";
par ();
add "Prompt for a program name and its arguments, such as ";
add ~style: (Style.bold ()) "ls -la"; add ", and execute it."; nl();
par ();
line "Run the process in the background. Display program output in the current panel.";
see_also [ "execute_command" ]
let () = define "execute_process" ~help Command @@ fun state ->
let panel = state.focus in
prompt "Execute process: " ~history: External_command state @@ fun command ->
State.add_history External_command command state;
match Shell_lexer.items [] [] (Lexing.from_string command) with
| exception Failure reason ->
abort "Parse error in command: %s" reason
| [] ->
()
| program :: arguments ->
let file = State.create_file state ("<" ^ command ^ ">") Text.empty in
Panel.set_current_view panel (File.create_view File file);
File.create_process file program arguments
let help { H.line; par; see_also } =
line "Switch to another already-opened file.";
par ();
line "Prompt for the filename to switch to.";
see_also [ "new"; "open" ]
let () = define "switch_file" ~help Command @@ fun state ->
let panel = state.focus in
let choices =
let make_choice_item_from_file not_modified modified (file: File.t): File.choice_item =
(if file.modified then modified else not_modified),
File.get_name file
in
let make_choice_item_from_view not_modified modified (view: File.view) =
make_choice_item_from_file not_modified modified view.file
in
List.map (make_choice_item_from_view Recent Recent_modified) (Panel.get_previous_views panel) @
(
state.files
|> List.sort (fun (a: File.t) (b: File.t) -> compare_names (File.get_name a) (File.get_name b))
|> List.map (make_choice_item_from_file Other Modified)
)
in
choose_from_list ~choice: 0 "Switch to file: " choices state @@ fun choice ->
match List.find (File.has_name choice) state.files with
| exception Not_found ->
abort "No such file: %s" choice
| file ->
Panel.set_current_file panel file
let help { H.line; add; nl; add_link; par; see_also } =
line "Select the item above the currently selected one.";
par ();
add "If you "; add_link "validate"; add " and an item is selected, choose this item"; nl ();
line "instead of what you typed.";
par ();
line "If no item is selected, select the first one, i.e. the one at the bottom.";
see_also [ "choose_previous" ]
let () = define "choose_next" ~help Command @@ fun state ->
let view = State.get_focused_view state in
match view.kind with
| List_choice choice ->
let choices = filter_choices (Text.to_string view.file.text) choice.choices in
choice.choice <- choice.choice + 1;
let max_choice = List.length choices - 1 in
if choice.choice > max_choice then choice.choice <- max_choice
| _ ->
abort "Focused panel has no prompt."
let help { H.line; add; nl; add_link; par; see_also } =
line "Select the item below the currently selected one.";
par ();
add "If you "; add_link "validate"; add " and an item is selected, choose this item"; nl ();
line "instead of what you typed.";
par ();
line "If the first item is selected, i.e. the one at the bottom, unselect it instead.";
see_also [ "choose_next" ]
let () = define "choose_previous" ~help Command @@ fun state ->
match (State.get_focused_view state).kind with
| List_choice choice ->
choice.choice <- choice.choice - 1;
if choice.choice < -1 then choice.choice <- -1
| _ ->
abort "Focused panel has no prompt."
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Split current panel vertically (top and bottom).";
par ();
add "If "; add_parameter "position"; add " is a positive integer, it specifies the height of the top panel."; nl ();
add "If "; add_parameter "position"; add " is a negative integer, it specifies the height of the bottom panel.";
nl ();
add "If "; add_parameter "position"; add " is a float, it is a ratio of the current panel height."; nl ();
add "Default "; add_parameter "position"; add " is 0.5 (half of current panel)."; nl ();
see_also [ "split_panel_horizontally"; "focus_down"; "focus_up"; "remove_panel" ]
let () = define "split_panel_vertically" ~help Command @@ fun state ->
split_panel Vertical (Layout.Ratio (1, 2)) state
let () = define "split_panel_vertically" ~help ("position" -: Int @-> Command) @@ fun position state ->
let position =
if position >= 0 then
Layout.Absolute_first position
else
Layout.Absolute_second (- position)
in
split_panel Vertical position state
let () = define "split_panel_vertically" ~help ("position" -: Float @-> Command) @@ fun position state ->
if position >= 0. && position < 1. then
let position = Layout.Ratio (int_of_float (position *. 100_000.), 100_000) in
split_panel Vertical position state
else
abort "Invalid position to split panel: %F" position
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Split current panel horizontally (top and bottom).";
par ();
add "If "; add_parameter "position";
add " is a positive integer, it specifies the height of the panel at the left."; nl ();
add "If "; add_parameter "position";
add " is a negative integer, it specifies the height of the panel at the right."; nl ();
add "If "; add_parameter "position"; add " is a float, it is a ratio of the current panel height."; nl ();
add "Default "; add_parameter "position"; add " is 0.5 (half of current panel)."; nl ();
see_also [ "split_panel_vertically"; "focus_right"; "focus_left"; "remove_panel" ]
let () = define "split_panel_horizontally" ~help Command @@ fun state ->
split_panel Horizontal (Layout.Ratio (1, 2)) state
let () = define "split_panel_horizontally" ~help ("position" -: Int @-> Command) @@ fun position state ->
let position =
if position >= 0 then
Layout.Absolute_first position
else
Layout.Absolute_second (- position)
in
split_panel Horizontal position state
let () = define "split_panel_horizontally" ~help ("position" -: Float @-> Command) @@ fun position state ->
if position >= 0. && position < 1. then
let position = Layout.Ratio (int_of_float (position *. 100_000.), 100_000) in
split_panel Horizontal position state
else
abort "Invalid position to split panel: %F" position
let get_selected_text_or_empty (view: File.view) =
match view.cursors with
| [] ->
Text.empty
| [ cursor ] ->
File.get_cursor_subtext cursor view.file.text
| _ :: _ :: _ ->
Text.empty
let search replace_by backwards case_sensitive (state: State.t) =
let view = State.get_focused_main_view state in
let search_from_cursor subtext (cursor: File.cursor) =
match
let equal_characters = if case_sensitive then Character.equals else Character.case_insensitive_equals in
if backwards then
Text.search_backwards
equal_characters
~x2: (cursor.search_start.x - 1) ~y2: cursor.search_start.y
~subtext view.file.text
else
Text.search_forwards
equal_characters
~x1: cursor.search_start.x ~y1: cursor.search_start.y
~subtext view.file.text
with
| None ->
false
| Some (x1, y1, x2, y2) ->
cursor.selection_start.x <- x1;
cursor.selection_start.y <- y1;
cursor.position.x <- x2 + 1;
cursor.position.y <- y2;
cursor.preferred_x <- x2 + 1;
true
in
let search_from_all_cursors ?(set_starting_position = false) ?subtext ?replace_by () =
(* If we are going to replace text, enter edit mode. *)
(
match replace_by with
| None ->
(fun f -> f ())
| Some _ ->
File.edit true view.file
) @@ fun () ->
(* Search for all cursors. *)
let exists_not_found = ref false in
(
File.foreach_cursor view @@ fun cursor ->
(* Get text to search (before replacing it). *)
let subtext =
match subtext with
| None ->
File.get_cursor_subtext cursor view.file.text
| Some subtext ->
subtext
in
(* Replace text. *)
(
match replace_by with
| None ->
()
| Some replacement ->
File.replace_selection_with_text_for_cursor view cursor replacement;
);
(* Set starting position (after replacing, to not search in the replacement). *)
if set_starting_position then (
let position =
let left, right = File.selection_boundaries cursor in
if backwards then left else right
in
cursor.search_start.x <- position.x;
cursor.search_start.y <- position.y;
);
(* Search and move cursor. *)
if not (search_from_cursor subtext cursor) then exists_not_found := true
);
File.recenter_if_needed view;
(* If text was not found, say it. *)
Log.info "Text not found."
in
(* Get default subtext to search. *)
let default = get_selected_text_or_empty view in
(* Create search file and view. *)
let search_file = File.create "search" default in
let search_view = File.create_view (Search { backwards; case_sensitive }) search_file in
(
File.foreach_cursor search_view @@ fun cursor ->
move_cursor true false search_view cursor File.move_end_of_line
);
let replacement =
match replace_by, view.search with
| None, None ->
None
| Some _, _ ->
(* Override previous replacement text. *)
replace_by
| None, Some search ->
(* Keep previous replacement text. *)
search.replacement
in
view.search <-
Some {
search_view;
replacement;
};
(* When the search file is edited, search again, but using search_file.text instead of cursor selections.
And this time, do not set starting position. *)
search_file.on_edit <- (fun () -> search_from_all_cursors ~subtext: search_file.text ());
(* Search once at the start using the text selected by each cursor. *)
search_from_all_cursors ~set_starting_position: true ?replace_by ()
let help { H.line; par; add; nl; add_parameter; add_link; see_also } =
line "Search for fixed text.";
par ();
line "Search for the next occurrence of the selected text.";
line "Edit text to search for in the search prompt.";
add "Exit search prompt using "; add_link "validate"; add " or "; add_link "cancel"; add "."; nl ();
par ();
line "When an occurrence is found, it is selected.";
line "Runnning this command again will thus search for the next occurrence.";
par ();
line "In multiple cursor mode, each cursor searches for his own selection.";
line "Editing the text to search in the search prompt will cause all cursors";
line "to search for this text instead.";
par ();
add "If "; add_parameter "case_sensitive"; add " is true, search for an exact match."; nl ();
line "Else, ignore case. Default is false.";
par ();
add "If "; add_parameter "backwards"; add " is true, search for the first occurrence before the cursor."; nl ();
line "Else, search for the first occurrence after the cursor. Default is false.";
see_also [ "replace"; "create_cursor_from_search" ]
let () = define "search" ~help ("backwards" -: Bool @-> "case_sensitive" -: Bool @-> Command) (search None)
let () = define "search" ~help Command (search None false false)
let help { H.line; par; add; nl; add_parameter; add_link; see_also } =
line "Replace selected text, then search.";
par ();
line "If already replacing text, use current replacement text.";
line "Else, prompt for a replacement text.";
par ();
line "Replace selection by replacement text.";
add "Then "; add_link "search"; add " for the next occurrence of the selected text before it was replaced."; nl ();
see_also [ "search"; "create_cursor_from_search" ]
let replace backwards case_sensitive (state: State.t) =
let view = State.get_focused_main_view state in
(* Get previous replacement text, or prompt for one. *)
(
fun continue ->
match view.search with
| Some { replacement = Some replacement } ->
continue replacement
| None | Some { replacement = None } ->
let default = get_selected_text_or_empty view in
prompt ~history: Replacement_text ~default: (Text.to_string default) "Replace by: " state
@@ fun replacement ->
State.add_history Replacement_text replacement state;
continue (Text.of_utf8_string replacement)
) @@ fun replace_by ->
(* Replace and search. *)
search (Some replace_by) backwards case_sensitive state
let () = define "replace" ~help ("backwards" -: Bool @-> "case_sensitive" -: Bool @-> Command) replace
let () = define "replace" ~help Command (replace false false)
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Create a cursor by searching for another occurrence of the selected text.";
nl ();
add "If "; add_parameter "backwards"; add " is true, search for the first occurrence of the"; nl ();
line "text selected by the left-most cursor, before this cursor.";
line "Else, search for the first occurrence of the text selected";
line "by the right-most cursor, after this cursor. Default is false.";
see_also [ "search"; "replace" ]
let create_cursor_from_search backwards (state: State.t) =
let view = State.get_focused_view state in
(* Get text to search for, and starting point. *)
let subtext, start =
match view.cursors with
| [] ->
abort "View has no cursor."
| head :: tail ->
let (<%) = File.(<%) in
let cursor =
if backwards then
let left_most (acc: File.cursor) (candidate: File.cursor) =
let acc_min = File.min_mark acc.selection_start acc.position in
let candidate_min = File.min_mark candidate.selection_start candidate.position in
if candidate_min <% acc_min then candidate else acc
in
List.fold_left left_most head tail
else
let right_most (acc: File.cursor) (candidate: File.cursor) =
let acc_max = File.max_mark acc.selection_start acc.position in
let candidate_max = File.max_mark candidate.selection_start candidate.position in
if candidate_max <% acc_max then acc else candidate
in
List.fold_left right_most head tail
in
let pattern = File.get_selected_text view.file.text cursor in
let start =
if backwards then
File.min_mark cursor.selection_start cursor.position
else
File.max_mark cursor.selection_start cursor.position
in
pattern, start
in
(* Search for another occurrence of the selected text. *)
match
if backwards then
Text.search_backwards
Character.equals
~x2: (start.x - 1) ~y2: start.y
~subtext view.file.text
else
Text.search_forwards
Character.equals
~x1: start.x ~y1: start.y
~subtext view.file.text
with
| None ->
abort "Text not found."
| Some (x1, y1, x2, y2) ->
let cursor = File.create_cursor x1 y1 in
cursor.position.x <- x2 + 1;
cursor.position.y <- y2;
cursor.preferred_x <- x2 + 1;
File.set_cursors view (cursor :: view.cursors)
let () = define "create_cursor_from_search" ~help ("backwards" -: Bool @-> Command) create_cursor_from_search
let () = define "create_cursor_from_search" ~help Command (create_cursor_from_search false)
let help { H.line } =
line "Open prompt history."
let () = define "choose_from_history" ~help Command @@ fun state ->
let main_view = State.get_focused_main_view state in
match main_view.prompt with
| None ->
abort "No history here (no prompt)."
| Some { prompt_text; validate_prompt; prompt_view } ->
match prompt_view.file.history_context with
| None ->
abort "No history here."
| Some history_context ->
let choices = List.map (fun choice -> File.Other, choice) (State.get_history history_context state) in
choose_from_list ~choice: 0 prompt_text choices state @@ fun choice ->
main_view.prompt <- None;
validate_prompt choice
let help { H.line } =
line "Copy selected choice into prompt so you can edit it."
let () = define "edit_selected_choice" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.kind with
| List_choice { choice; choices } ->
let filter = Text.to_string view.file.text in
(
match List.nth (filter_choices filter choices) choice with
| exception (Invalid_argument _ | Failure _) ->
abort "No selected choice."
| _, choice ->
select_all view;
File.replace_selection_with_text view (Text.of_utf8_string choice)
)
| _ ->
abort "Not selecting from a list."
let with_autocompletion view f =
match File.get_autocompletion view with
| No_cursor_to_autocomplete ->
abort "No cursor to autocomplete."
| Too_many_cursors_to_autocomplete ->
abort "Too many cursors to autocomplete."
| Nothing_to_autocomplete ->
abort_with_error "Nothing to autocomplete here."
| Word_is_on_multiple_lines ->
abort_with_error "Word is on multiple lines."
| May_autocomplete autocompletion ->
f autocompletion
let help { H.line; par; see_also } =
line "Open list of autocompletions.";
par ();
line "Autocompletions are big words which start with the one at cursor position.";
line "Big words are like words, but underscore is also part of big words.";
line "Candidate completions are found in open files.";
par ();
line "Has no effect if there are more than one cursors.";
see_also [ "autocomplete" ]
let () = define "choose_autocompletion" ~help Command @@ fun state ->
let view = State.get_focused_view state in
with_autocompletion view @@ fun { y; start_x; end_x; prefix; suffixes } ->
let choices =
Trie.to_list suffixes
|> List.map (fun (word, _) -> File.Other, String.concat "" (prefix @ word))
in
choose_from_list ~choice: 0 ("Autocomplete " ^ String.concat "" prefix ^ " with: ") choices state
@@ fun choice ->
File.replace view.file ~x: start_x ~y ~lines: 0 ~characters: (end_x - start_x) (Text.of_utf8_string choice)
let help { H.line; see_also } =
line "Autocomplete with the completion visible in the status bar.";
see_also [ "choose_autocompletion" ]
let () = define "autocomplete" ~help Command @@ fun state ->
let view = State.get_focused_view state in
with_autocompletion view @@ fun { y; start_x; end_x; best_word } ->
File.replace view.file ~x: start_x ~y ~lines: 0 ~characters: (end_x - start_x) (Text.of_utf8_string best_word)
| null | https://raw.githubusercontent.com/rbardou/red/e23c2830909b9e5cd6afe563313435ddaeda90bf/src/command.ml | ocaml | Built-in command definitions.
List of all built-in commands.
Make a parameterized command type.
Add a command, parameterized or not, to the list of built-in commands.
Declare command.
Declare help page.
****************************************************************************
Helpers
****************************************************************************
Clear undo stack (at the very least we should set the modified flags in all undo points).
Create choice file and view.
Replace current view with choice view.
By using uppercase instead of lowercase, symbols like _ are higher in the choice list.
The filter starts empty. Let's select the parent directory by default.
TODO: include topic in name?
****************************************************************************
Definitions
****************************************************************************
TODO: restore cursor positions
Scroll.
Move cursor.
Scroll.
Move cursor.
User killed the file from which we spawned the list choice?
This should be a rare occurrence.
TODO: if validation results in opening a file, do not create a new empty file
We use [Help.command_page_list] instead of [!commands], because [!commands] contains duplicates.
So this is more efficient.
Also, if we decide to hide a command from the help panel, we can also hide it from auto-completion.
If we are going to replace text, enter edit mode.
Search for all cursors.
Get text to search (before replacing it).
Replace text.
Set starting position (after replacing, to not search in the replacement).
Search and move cursor.
If text was not found, say it.
Get default subtext to search.
Create search file and view.
Override previous replacement text.
Keep previous replacement text.
When the search file is edited, search again, but using search_file.text instead of cursor selections.
And this time, do not set starting position.
Search once at the start using the text selected by each cursor.
Get previous replacement text, or prompt for one.
Replace and search.
Get text to search for, and starting point.
Search for another occurrence of the selected text. | open Misc
module H = Help
type command =
{
name: string;
help: (Help.maker -> unit) option;
partial: Redl.Typing.command Redl.Typing.partial;
}
let commands: command list ref = ref []
type _ typ =
| Command: Redl.Typing.command typ
| Function: { parameter_name: string; parameter_type: ('p, 'p) Redl.Typing.typ; result: 'r typ } -> ('p -> 'r) typ
let (@->) (parameter_name, parameter_type) result =
Function { parameter_name; parameter_type; result }
let (-:) name (typ: (_, _) Redl.Typing.typ) =
name, typ
let define (type f) name ?help (typ: f typ) (f: f) =
let rec make_type: type f. f typ -> (f, Redl.Typing.command) Redl.Typing.typ = function
| Command ->
Command
| Function { parameter_type; result } ->
Function (parameter_type, make_type result)
in
let command =
{
name;
help;
partial = Partial { typ = make_type typ; value = Constant f };
}
in
commands := command :: !commands;
let rec get_parameters: type f. _ -> f typ -> _ = fun acc typ ->
match typ with
| Command ->
List.rev acc
| Function { parameter_name; parameter_type; result } ->
get_parameters ((parameter_name, Redl.Typing.Type parameter_type) :: acc) result
in
Help.overload_command name ?help (get_parameters [] typ)
let setup_initial_env overload_command =
let add command = overload_command command.name command.partial in
List.iter add !commands
let bind (context: State.Context.t) (state: State.t) (key: Key.t) (command: string) =
let ast = Redl.parse_string command in
let command =
Parse , type , but do not execute yet .
state.run_string command
in
let context_bindings = State.get_context_bindings context state in
let context_bindings = Key.Map.add key command context_bindings in
state.bindings <- State.Context_map.add context context_bindings state.bindings;
Help.bind context key ast
let abort = State.abort
let abort_with_error = State.abort_with_error
Change cursor position ( apply [ f ] to get new coordinates ) .
Update [ ] unless [ vertical ] .
Reset selection if [ reset_selection ] .
Update [preferred_x] unless [vertical].
Reset selection if [reset_selection]. *)
let move_cursor reset_selection vertical (view: File.view) (cursor: File.cursor) f =
let position = cursor.position in
let x, y = f view.file.text (if vertical then cursor.preferred_x else position.x) position.y in
if reset_selection then (
let selection_start = cursor.selection_start in
selection_start.x <- x;
selection_start.y <- y;
);
position.x <- x;
position.y <- y;
cursor.preferred_x <- if vertical then cursor.preferred_x else x
Change cursor position ( apply [ f ] to get new coordinates ) .
Update [ ] unless [ vertical ] .
Reset selection if [ reset_selection ] .
Update [preferred_x] unless [vertical].
Reset selection if [reset_selection]. *)
let move reset_selection vertical f (state: State.t) =
let view = State.get_focused_view state in
(
File.foreach_cursor view @@ fun cursor ->
move_cursor reset_selection vertical view cursor f
);
File.recenter_if_needed view
let focus_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
State.set_focus state panel
let swap_view_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
let panel_view = Panel.get_current_main_view panel in
Panel.set_current_view panel (File.copy_view (Panel.get_current_main_view state.focus));
Panel.set_current_view state.focus (File.copy_view panel_view);
State.set_focus state panel
let copy_view_relative get (state: State.t) =
match get state.focus state.layout with
| None ->
()
| Some panel ->
Panel.set_current_view panel (File.copy_view (Panel.get_current_main_view state.focus))
let move_after_scroll (view: File.view) old_scroll =
let delta = view.scroll_y - old_scroll in
let text = view.file.text in
let max_y = Text.get_line_count text - 1 in
File.if_only_one_cursor view @@ fun cursor ->
cursor.position.y <- max 0 (min max_y (cursor.position.y + delta));
cursor.position.x <- min (Text.get_line_length cursor.position.y text) cursor.preferred_x;
cursor.selection_start.x <- cursor.position.x;
cursor.selection_start.y <- cursor.position.y
let select_all view =
File.foreach_cursor view @@ fun cursor ->
cursor.selection_start.x <- 0;
cursor.selection_start.y <- 0;
let text = view.file.text in
let max_y = Text.get_line_count text - 1 in
cursor.position.y <- max_y;
cursor.position.x <- Text.get_line_length max_y text
let save (file: File.t) filename =
if filename <> "" then (
file.name <- filename;
File.set_filename file (Some filename);
if not (System.file_exists filename) then
Text.output_file filename file.text
else
(
let perm =
match Unix.stat filename with
| exception Unix.Unix_error _ ->
None
| stat ->
Some stat.st_perm
in
let temporary_filename = System.find_temporary_filename filename in
Text.output_file ?perm temporary_filename file.text;
System.move_file temporary_filename filename;
);
Log.info "Wrote: %s" filename;
file.modified <- false;
file.undo_stack <- [];
file.redo_stack <- [];
)
let prompt ?history ?(default = "") (prompt_text: string) (state: State.t) (validate_prompt: string -> unit) =
let view = State.get_focused_main_view state in
let prompt_view = File.create_view Prompt (File.create ?history prompt_text (Text.of_utf8_string default)) in
select_all prompt_view;
view.prompt <-
Some {
prompt_text;
validate_prompt;
prompt_view;
}
let rec prompt_confirmation ?(repeated = 0) message state confirm =
let message = if repeated = 1 then "Please answer yes or no. " ^ message else message in
prompt ~default: "no" message state @@ fun response ->
if String.lowercase_ascii response = "yes" then
confirm ()
else if String.lowercase_ascii response = "no" then
()
else
prompt_confirmation ~repeated: (min 2 (repeated + 1)) message state confirm
let deduplicate_choices (choices: File.choice_item list): File.choice_item list =
let rec loop exists_before acc choices =
match choices with
| [] ->
List.rev acc
| ((_, choice) as item) :: tail ->
if String_set.mem choice exists_before then
loop exists_before acc tail
else
loop (String_set.add choice exists_before) (item :: acc) tail
in
loop String_set.empty [] choices
let choose_from_list ?(default = "") ?(choice = -1) (choice_prompt_text: string)
(choices: File.choice_item list) (state: State.t)
(validate_choice: string -> unit) =
let choices = deduplicate_choices choices in
let choice_view =
let file = File.create choice_prompt_text (Text.of_utf8_string default) in
let view = File.create_view (List_choice { choice_prompt_text; validate_choice; choices; choice }) file in
select_all view;
view
in
State.set_focused_view state choice_view
let compare_names a b =
String.compare (String.uppercase_ascii a) (String.uppercase_ascii b)
let sort_names list =
List.sort compare_names list
let choose_from_file_system ?default (prompt: string) (state: State.t) (validate: string -> unit) =
let append_dir_sep_if_needed filename =
let length = String.length filename in
let sep_length = String.length Filename.dir_sep in
if
length < sep_length ||
String.sub filename (length - sep_length) sep_length <> Filename.dir_sep
then
filename ^ Filename.dir_sep
else
filename
in
let starting_directory, default =
match default with
| None ->
System.get_cwd (), None
| Some default ->
let base = Filename.basename default in
let base =
if
base = Filename.current_dir_name ||
System.is_root_directory base
then
None
else
Some base
in
let dir =
let dir = Filename.dirname default in
if dir = Filename.current_dir_name then
System.get_cwd ()
else
System.make_filename_absolute dir
in
dir, base
in
let starting_directory = append_dir_sep_if_needed starting_directory in
let rec browse ?default directory =
let choices =
let directories, files =
List.partition
(fun filename -> System.is_directory (Filename.concat directory filename))
(System.ls directory)
in
let directories =
directories
|> sort_names
|> List.map (fun name -> File.Directory, name ^ Filename.dir_sep)
in
let files =
files
|> sort_names
|> List.map (fun name -> File.Other, name)
in
(File.Directory, Filename.parent_dir_name) ::
directories @
files
in
let choice =
match default with
| None ->
Some 0
| Some _ ->
None
in
choose_from_list ?default ?choice (prompt ^ directory) choices state @@ fun choice ->
if choice = "" then
()
else if choice = Filename.current_dir_name then
browse directory
else if choice = Filename.parent_dir_name || choice = append_dir_sep_if_needed Filename.parent_dir_name then
browse (append_dir_sep_if_needed (Filename.dirname directory))
else
let filename = Filename.concat directory choice in
if System.is_directory filename then
browse filename
else
validate filename
in
browse ?default (append_dir_sep_if_needed starting_directory)
let display_help (state: State.t) make_page =
let topic, text, style, links = make_page state in
let view = File.create_view (Help { topic; links }) file in
view.style <- style;
State.set_focused_view state view
let ocaml_stylist =
File.Stylist_module {
equivalent = Ocaml.Stylist.equivalent;
start = Ocaml.Stylist.start;
add_char = Ocaml.Stylist.add_char;
end_of_file = Ocaml.Stylist.end_of_file;
}
let redl_stylist =
File.Stylist_module {
equivalent = Redl.Stylist.equivalent;
start = Redl.Stylist.start;
add_char = Redl.Stylist.add_char;
end_of_file = Redl.Stylist.end_of_file;
}
let set_stylist (view: File.view) =
if view.kind = File then (
let stylist =
match view.file.filename with
| None ->
None
| Some filename ->
if Filename.check_suffix filename ".ml" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mli" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mll" then
Some ocaml_stylist
else if Filename.check_suffix filename ".mly" then
Some ocaml_stylist
else if Filename.check_suffix filename ".red" then
Some redl_stylist
else
None
in
File.set_stylist_module view stylist
)
let () = File.choose_stylist_automatically := set_stylist
let split_panel direction pos (state: State.t) =
let view = State.get_focused_main_view state in
let new_view =
match view.kind with
| Prompt | Search _ | List_choice _ | Help _ ->
State.get_default_view state
| File ->
File.copy_view view
in
match
Layout.replace_panel state.focus (
Layout.split direction ~pos ~sep: (direction = Horizontal)
(Layout.single state.focus)
(Layout.single (Panel.create new_view))
) state.layout
with
| None ->
abort_with_error "failed to replace current panel: panel not found in current layout"
| Some new_layout ->
State.set_layout state new_layout
let help { H.add } =
add "Do nothing."
let () = define "noop" ~help Command @@ fun state ->
()
let help { H.line; par } =
line "Exit the editor.";
par ();
line "Prompt for confirmation if there are modified files."
let () = define "quit" ~help Command @@ fun state ->
let modified_files = List.filter (fun (file: File.t) -> file.modified) state.files in
let modified_file_count = List.length modified_files in
if modified_file_count = 0 then
raise State.Exit
else
let message =
if modified_file_count = 1 then
"There is 1 modified file, really exit? "
else
"There are " ^ string_of_int modified_file_count ^ " modified file(s), really exit? "
in
prompt_confirmation message state @@ fun () ->
raise State.Exit
let help { H.line; add; add_link; nl; add_parameter; par } =
line "Open help.";
par ();
add "Open help page specified by "; add_parameter "page"; add "."; nl ();
line "It can be a command name or a topic.";
add "If "; add_parameter "page"; add " is not specified, prompt for page name."; nl ();
par ();
line "Press Q to go back to what you were doing."
let () = define "help" ~help Command @@ fun state ->
let pages =
List.map (fun page -> File.Recent, page) (State.get_history Help_page state) @
List.map (fun page -> File.Other, page) (Help.make_page_list ())
in
choose_from_list ~choice: 0 "Open help page: " pages state @@ fun page ->
State.add_history Help_page page state;
display_help state (Help.page page)
let () = define "help" ("page" -: String @-> Command) @@ fun page state ->
display_help state (Help.page page)
let help { H.line } =
line "Follow a link to another help page to get more information."
let () = define "follow_link" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.kind with
| Help { links } ->
File.if_only_one_cursor view @@ fun cursor ->
(
match Text.get cursor.position.x cursor.position.y links with
| None | Some None ->
()
| Some (Some link) ->
display_help state (Help.page link)
)
| _ ->
()
let help { H.line; par } =
line "Cancel what you are doing.";
par ();
line "If you currently have multiple cursors, remove all but one.";
line "Else, if you are in a prompt, a list of choices or in a help panel, close it."
let () = define "cancel" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.prompt with
| Some _ ->
view.prompt <- None
| None ->
match view.search with
| Some _ ->
view.search <- None
| None ->
match view.cursors with
| first :: _ :: _ ->
view.cursors <- [ first ]
| _ ->
match view.kind with
| Prompt | Search _ | Help _ | List_choice _ ->
if not (Panel.kill_current_view state.focus) then
let view = State.get_default_view state in
State.set_focused_view state view
| File ->
()
let help { H.line; par; see_also } =
line "Save file.";
par ();
line "If current file has no name, prompt for a filename.";
see_also [ "save_as" ]
let () = define "save" ~help Command @@ fun state ->
let file_to_save = State.get_focused_file state in
match file_to_save.filename with
| None ->
choose_from_file_system "Save as: " state (save file_to_save)
| Some filename ->
save file_to_save filename
let help { H.line; par; see_also } =
line "Save file.";
par ();
line "Prompt for a filename even if current file already has one.";
line "Existing file is not deleted.";
see_also [ "save" ]
let () = define "save_as" ~help Command @@ fun state ->
let file_to_save = State.get_focused_file state in
choose_from_file_system ?default: file_to_save.filename "Save as: " state (save file_to_save)
let help { H.line; par; see_also } =
line "Open a file in the current panel.";
par ();
line "Prompt for the filename to open.";
see_also [ "new"; "switch_file" ]
let () = define "open" ~help Command @@ fun state ->
let panel = state.focus in
choose_from_file_system "Open: " state @@ fun filename ->
if not (System.file_exists filename) then abort "File does not exist: %S" filename;
let file = State.create_file_loading state filename in
let view = File.create_view File file in
Panel.set_current_view panel view
let help { H.line; par; see_also } =
line "Create a new empty file.";
par ();
line "The file is not actually created on disk until you save.";
see_also [ "open"; "switch_file" ]
let () = define "new" ~help Command @@ fun state ->
let file = State.create_empty_file state in
let view = File.create_view File file in
State.set_focused_view state view
let help { H.line; see_also } =
line "Remove current panel from current layout.";
see_also [ "split_panel_vertically"; "split_panel_horizontally"; "close_file" ]
let () = define "close_panel" ~help Command @@ fun state ->
State.remove_panel state.focus state
let help { H.line; par; see_also } =
line "Close current file.";
par ();
line "Remove it from all panels.";
par ();
line "Prompt for confirmation if file has been modified.";
see_also [ "close_panel" ]
let () = define "close_file" ~help Command @@ fun state ->
let file = State.get_focused_file state in
if file.modified then
prompt_confirmation "File has been modified, really close it? " state @@ fun () ->
State.close_file file state
else
State.close_file file state
let help { H.line; par; see_also } =
line "Move cursor to the right.";
par ();
line "All cursors move one character to the right.";
line "If there is no character to the right in the current line,";
line "move to the beginning of the next line instead;";
line "if there is no next line, don't move at all.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_left"; "move_down"; "move_up";
"select_right"; "move_end_of_line"; "move_right_word";
]
let () = define "move_right" ~help Command @@ move true false File.move_right
let help { H.line; par; see_also } =
line "Move cursor to the left.";
par ();
line "All cursors move one character to the left.";
line "If there is no character to the left in the current line,";
line "move to the end of the previous line instead;";
line "if there is no previous line, don't move at all.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_right"; "move_down"; "move_up";
"select_left"; "move_beginning_of_line"; "move_left_word";
]
let () = define "move_left" ~help Command @@ move true false File.move_left
let help { H.line; par; see_also } =
line "Move cursor to the next line.";
par ();
line "All cursors move one line down.";
line "If there is no line below do nothing.";
line "Cursors move to their preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
par ();
line "Reset selection.";
see_also [
"move_up"; "move_right"; "move_left";
"select_down"; "move_end_of_file"; "move_down_paragraph";
]
let () = define "move_down" ~help Command @@ move true true File.move_down
let help { H.line; par; see_also } =
line "Move cursor to the previous line.";
par ();
line "All cursors move one line up.";
line "If there is no line above do nothing.";
line "Cursors move to their preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
par ();
line "Reset selection.";
see_also [
"move_down"; "move_right"; "move_left";
"select_down"; "move_beginning_of_file"; "move_up_paragraph";
]
let () = define "move_up" ~help Command @@ move true true File.move_up
let help { H.line; par; see_also } =
line "Move cursor to the end of the current line.";
par ();
line "All cursors move just after the character at the end of the current line.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_right"; "select_end_of_line";
"move_beginning_of_line"; "move_end_of_file";
]
let () = define "move_end_of_line" ~help Command @@ move true false File.move_end_of_line
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the current line.";
par ();
line "All cursors move to the first character of the current line.";
par ();
line "Reset selection and preferred column.";
see_also [
"move_left"; "select_beginning_of_line";
"move_end_of_line"; "move_beginning_of_file";
]
let () = define "move_beginning_of_line" ~help Command @@ move true false File.move_beginning_of_line
let help { H.line; par; see_also } =
line "Move cursor to the end of the current file.";
par ();
line "All cursors move just after the last character of the last line.";
par ();
line "Reset selection and preferred column.";
see_also [
"select_end_of_file"; "move_end_of_line"; "move_beginning_of_file";
]
let () = define "move_end_of_file" ~help Command @@ move true false File.move_end_of_file
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the current file.";
par ();
line "All cursors move to the first character of the first line.";
par ();
line "Reset selection and preferred column.";
see_also [
"select_beginning_of_file"; "move_beginning_of_line"; "move_end_of_file";
]
let () = define "move_beginning_of_file" ~help Command @@ move true false File.move_beginning_of_file
let help { H.line; par; see_also } =
line "Move cursor to the end of the word.";
par ();
line "All cursors move to the first character after the current word,";
line "or of the next word if they are not in a word.";
par ();
line "A word is a sequence of letters or digits.";
par ();
line "Reset selection and preferred column.";
see_also [ "select_right_word"; "move_left_word" ]
let () = define "move_right_word" ~help Command @@ move true false File.move_right_word
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the word.";
par ();
line "All cursors move to the first character of the current word,";
line "or of the previous word if they are not in a word.";
par ();
line "A word is a sequence of letters or digits.";
par ();
line "Reset selection and preferred column.";
see_also [ "select_left_word"; "move_right_word" ]
let () = define "move_left_word" ~help Command @@ move true false File.move_left_word
let help { H.line; par; see_also } =
line "Move cursor to the end of the paragraph.";
par ();
line "All cursors move to the first line after the current paragraph,";
line "or of the next paragraph if they are not in a paragraph.";
par ();
line "A paragraph is a sequence of non-empty lines.";
par ();
line "Reset selection.";
see_also [ "select_down_paragraph"; "move_up_paragraph" ]
let () = define "move_down_paragraph" ~help Command @@ move true false File.move_down_paragraph
let help { H.line; par; see_also } =
line "Move cursor to the beginning of the paragraph.";
par ();
line "All cursors move to the first line before the current paragraph,";
line "or of the previous paragraph if they are not in a paragraph.";
par ();
line "A paragraph is a sequence of non-empty lines.";
par ();
line "Reset selection.";
see_also [ "select_up_paragraph"; "move_down_paragraph" ]
let () = define "move_up_paragraph" ~help Command @@ move true false File.move_up_paragraph
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_right"; add " but does not reset selection."; nl ()
let () = define "select_right" ~help Command @@ move false false File.move_right
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_left"; add " but does not reset selection."; nl ()
let () = define "select_left" ~help Command @@ move false false File.move_left
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_down"; add " but does not reset selection."; nl ()
let () = define "select_down" ~help Command @@ move false true File.move_down
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_up"; add " but does not reset selection."; nl ()
let () = define "select_up" ~help Command @@ move false true File.move_up
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_end_of_line"; add " but does not reset selection."; nl ()
let () = define "select_end_of_line" ~help Command @@ move false false File.move_end_of_line
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_beginning_of_line"; add " but does not reset selection."; nl ()
let () = define "select_beginning_of_line" ~help Command @@ move false false File.move_beginning_of_line
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_end_of_file"; add " but does not reset selection."; nl ()
let () = define "select_end_of_file" ~help Command @@ move false false File.move_end_of_file
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_beginning_of_file"; add " but does not reset selection."; nl ()
let () = define "select_beginning_of_file" ~help Command @@ move false false File.move_beginning_of_file
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_right_word"; add " but does not reset selection."; nl ()
let () = define "select_right_word" ~help Command @@ move false false File.move_right_word
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_left_word"; add " but does not reset selection."; nl ()
let () = define "select_left_word" ~help Command @@ move false false File.move_left_word
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_down_paragraph"; add " but does not reset selection."; nl ()
let () = define "select_down_paragraph" ~help Command @@ move false false File.move_down_paragraph
let help { H.add; nl; add_link } =
add "Same as "; add_link "move_up_paragraph"; add " but does not reset selection."; nl ()
let () = define "select_up_paragraph" ~help Command @@ move false false File.move_up_paragraph
let help { H.line; par; see_also } =
line "Select all text.";
par ();
line "Set selection of all cursors to start at the beginning of the file.";
line "Set position of all cursors to the end of the file.";
line "Reset preferred column.";
see_also [
"select_right";
"select_end_of_line";
"select_end_of_file";
"select_right_word";
"select_down_paragraph";
]
let () = define "select_all" ~help Command @@ fun state ->
select_all (State.get_focused_view state)
let help { H.line; par; see_also } =
line "Give focus to the panel at the right of the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_left"; "focus_down"; "focus_up";
"swap_view_right"; "copy_view_right";
"split_panel_horizontally";
]
let () = define "focus_right" ~help Command @@ focus_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Give focus to the panel at the left of the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_down"; "focus_up";
"swap_view_left"; "copy_view_left";
"split_panel_horizontally";
]
let () = define "focus_left" ~help Command @@ focus_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Give focus to the panel below the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_left"; "focus_up";
"swap_view_down"; "copy_view_down";
"split_panel_vertically";
]
let () = define "focus_down" ~help Command @@ focus_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Give focus to the panel above the current one.";
par ();
line "Commands which act on a view act on the view of the focused panel.";
line "Only one panel has focus at a given time.";
see_also [
"focus_right"; "focus_left"; "focus_down";
"swap_view_up"; "copy_view_up";
"split_panel_vertically";
]
let () = define "focus_up" ~help Command @@ focus_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel at its right.";
see_also [
"swap_view_left"; "swap_view_down"; "swap_view_up";
"copy_view_right";
"focus_right"; "split_panel_horizontally";
]
let () = define "swap_view_right" ~help Command @@ swap_view_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel at its left.";
see_also [
"swap_view_right"; "swap_view_down"; "swap_view_up";
"copy_view_left";
"focus_left"; "split_panel_horizontally";
]
let () = define "swap_view_left" ~help Command @@ swap_view_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel below it.";
see_also [
"swap_view_up"; "swap_view_right"; "swap_view_left";
"copy_view_down";
"focus_down"; "split_panel_vertically";
]
let () = define "swap_view_down" ~help Command @@ swap_view_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Exchange the views of the current panel and the panel above it.";
see_also [
"swap_view_down"; "swap_view_right"; "swap_view_left";
"copy_view_up";
"focus_up"; "split_panel_vertically";
]
let () = define "swap_view_up" ~help Command @@ swap_view_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Copy current view into the panel at its right.";
see_also [
"copy_view_left"; "copy_view_down"; "copy_view_up";
"swap_view_right";
"focus_right"; "split_panel_horizontally";
]
let () = define "copy_view_right" ~help Command @@ copy_view_relative Layout.get_panel_right
let help { H.line; par; see_also } =
line "Copy current view into the panel at its left.";
see_also [
"copy_view_right"; "copy_view_down"; "copy_view_up";
"swap_view_left";
"focus_left"; "split_panel_horizontally";
]
let () = define "copy_view_left" ~help Command @@ copy_view_relative Layout.get_panel_left
let help { H.line; par; see_also } =
line "Copy current view into the panel below it.";
see_also [
"copy_view_up"; "copy_view_right"; "copy_view_left";
"swap_view_down";
"focus_down"; "split_panel_vertically";
]
let () = define "copy_view_down" ~help Command @@ copy_view_relative Layout.get_panel_down
let help { H.line; par; see_also } =
line "Copy current view into the panel above it.";
see_also [
"copy_view_down"; "copy_view_right"; "copy_view_left";
"swap_view_up";
"focus_up"; "split_panel_vertically";
]
let () = define "copy_view_up" ~help Command @@ copy_view_relative Layout.get_panel_up
let help { H.line; par; see_also } =
line "Scroll half a page down.";
par ();
line "If there is only one cursor, also move it half a page down.";
line "It moves to its preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
see_also [ "scroll_up" ]
let () = define "scroll_down" ~help Command @@ fun state ->
let view = State.get_focused_view state in
let text = view.file.text in
let max_y = Text.get_line_count text - 1 in
let max_scroll =
Last line is often empty , so we want to see at least the line before that , unless panel height is 1 .
if view.height <= 1 then max_y else max_y - 1
in
let old_scroll = view.scroll_y in
view.scroll_y <- min max_scroll (view.scroll_y + view.height / 2);
move_after_scroll view old_scroll
let help { H.line; par; see_also } =
line "Scroll half a page up.";
par ();
line "If there is only one cursor, also move it half a page up.";
line "It moves to its preferred column, or to the last character of the line";
line "if preferred column is after the end of the line.";
see_also [ "scroll_down" ]
let () = define "scroll_up" ~help Command @@ fun state ->
let view = State.get_focused_view state in
let old_scroll = view.scroll_y in
view.scroll_y <- max 0 (view.scroll_y - view.height / 2);
move_after_scroll view old_scroll
let help { H.line; par; see_also } =
line "Split line at cursor.";
par ();
line "The end of the line moves to a new line below.";
line "Cursor moves to the beginning of this new line."
let () = define "insert_new_line" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.replace_selection_by_new_line view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the next character.";
par ();
line "If cursor is at the end of a line, merge the next line instead.";
line "If selection is not empty, delete it instead.";
line "Reset preferred column.";
see_also [
"delete_character_backwards";
"delete_end_of_line";
"delete_end_of_word";
]
let () = define "delete_character" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.delete_selection_or_character view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the previous character.";
par ();
line "If cursor is at the beginning of a line, merge this line";
line "into the previous line instead.";
line "If selection is not empty, delete it instead.";
line "Reset preferred column.";
see_also [
"delete_character";
"delete_beginning_of_word";
]
let () = define "delete_character_backwards" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.delete_selection_or_character_backwards view;
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the end of the current line.";
par ();
line "If cursor is at the end of a line, merge the next line instead.";
see_also [
"delete_character";
"delete_end_of_word";
]
let () = define "delete_end_of_line" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
Can not just use [ move_end_of_line ] here because we want to delete the if we are at the end of the line .
let x = cursor.position.x in
let y = cursor.position.y in
let length = Text.get_line_length y text in
if x >= length then
0, y + 1
else
length, y
);
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the end of the current word.";
par ();
line "If cursor is not in a word, delete until the end of the next word.";
see_also [
"move_right_word";
"delete_character";
"delete_beginning_of_word";
]
let () = define "delete_end_of_word" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
File.move_right_word text cursor.position.x cursor.position.y
);
File.recenter_if_needed view
let help { H.line; par; see_also } =
line "Delete the beginning of the current word.";
par ();
line "If cursor is not in a word, delete until the beginning of the previous word.";
see_also [
"move_left_word";
"delete_character_backwards";
"delete_end_of_word";
]
let () = define "delete_beginning_of_word" ~help Command @@ fun state ->
let view = State.get_focused_view state in
(
File.delete_from_cursors view @@ fun text cursor ->
File.move_left_word text cursor.position.x cursor.position.y
);
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link } =
line "Create one cursor per selected line.";
par ();
add "Use "; add_link "cancel"; add " to go back to one cursor."; nl ();
par ();
add "Commands which apply to cursors, such as "; add_link "move_right_word";
add " or "; add_link "delete_word"; add ","; nl ();
line "are applied to all cursors.";
par ();
add "Clipboard commands, such as "; add_link "copy"; add " and "; add_link "paste";
add ", use the cursor clipboard instead"; nl ();
line "of the global clipboard. This means that you can have each cursor copy its";
line "own selection, and paste it somewhere else.";
par ();
add "Other commands, such as "; add_link "save_as"; add ", are only run once."; nl ()
let () = define "create_cursors_from_selection" ~help Command @@ fun state ->
let view = State.get_focused_view state in
let create_cursors_from_cursor (cursor: File.cursor) =
let first, last, reverse =
let sel_y = cursor.selection_start.y in
let cur_y = cursor.position.y in
if sel_y <= cur_y then
sel_y, cur_y, true
else
cur_y, sel_y, false
in
let rec range acc first last =
if last < first then
acc
else
range (last :: acc) first (last - 1)
in
let text = view.file.text in
let create_cursor y = File.create_cursor (min (Text.get_line_length y text) cursor.position.x) y in
let cursors = List.map create_cursor (range [] first last) in
if reverse then List.rev cursors else cursors
in
let cursors = List.map create_cursors_from_cursor view.cursors in
File.set_cursors view (List.flatten cursors)
let help { H.add; line; nl; par; add_link; see_also } =
line "Copy selection to clipboard.";
par ();
line "If there is only one cursor, selection is copied to the global clipboard.";
line "It can be pasted from any view, in any file.";
par ();
add "If there are several cursor (see "; add_link "create_cursors_from_selection";
add "),"; nl ();
line "the selection of each cursor is copied to the local clipboard of each cursor.";
see_also [ "cut"; "paste" ]
let () = define "copy" ~help Command @@ fun state -> File.copy state.clipboard (State.get_focused_view state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Copy selection to clipboard, then delete selection.";
see_also [ "copy"; "paste" ]
let () = define "cut" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.cut state.clipboard view;
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link; see_also } =
line "Paste from clipboard.";
par ();
line "Selection is deleted before pasting.";
par ();
line "If there is only one cursor, paste selection from the global clipboard.";
add "If there are several cursor (see "; add_link "create_cursors_from_selection";
add "),"; nl ();
line "for each cursor, paste the clipboard of this cursor at its position.";
see_also [ "cut"; "paste" ]
let () = define "paste" ~help Command @@ fun state ->
let view = State.get_focused_view state in
File.paste state.clipboard view;
File.recenter_if_needed view
let help { H.add; line; nl; par; add_link; see_also } =
line "Undo recent edits.";
par ();
line "You can undo repeatedly until the point where the current file was last saved.";
see_also [ "redo" ]
let () = define "undo" ~help Command @@ fun state -> File.undo (State.get_focused_file state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Redo what was recently undone.";
par ();
line "You can redo repeatedly until you come back to the point of the first undo";
line "of the last undo sequence.";
par ();
line "Any edit which is not a redo or an undo will remove the possibility to redo.";
see_also [ "undo" ]
let () = define "redo" ~help Command @@ fun state -> File.redo (State.get_focused_file state)
let help { H.add; line; nl; par; add_link; see_also } =
line "Validate selected choice.";
par ();
add "In a prompt, such as the one which appears when you "; add_link "quit"; add ","; nl ();
line "validate the text you typed.";
par ();
add "In a list of choices, such as the one which appears when you "; add_link "save_as"; add ","; nl ();
line "validate selected choice. If you did not select anything,";
line "validate the text you typed instead."
let () = define "validate" ~help Command @@ fun state ->
let panel = state.focus in
let view = Panel.get_current_main_view panel in
match view.prompt with
| Some { validate_prompt; prompt_view } ->
view.prompt <- None;
validate_prompt (Text.to_string prompt_view.file.text)
| None ->
match view.search with
| Some _ ->
view.search <- None
| None ->
match view.kind with
| List_choice { validate_choice; choice; choices } ->
let filter = Text.to_string view.file.text in
if not (Panel.kill_current_view panel) then
(
let view = State.get_default_view state in
Panel.set_current_view panel view;
);
(
match List.nth (filter_choices filter choices) choice with
| exception (Invalid_argument _ | Failure _) ->
validate_choice filter
| _, choice ->
validate_choice choice
)
| _ ->
abort "Focused panel has no prompt."
let help { H.add; line; nl; par; add_link; see_also } =
line "Execute a command.";
par ();
add "Prompt for a command name, such as "; add_link "save_as"; add " or "; add_link "move_left"; add ","; nl ();
line "and execute this command.";
see_also [ "execute_process" ]
let () = define "execute_command" ~help Command @@ fun state ->
let commands =
List.map (fun page -> File.Recent, page) (State.get_history Command state) @
List.map (fun page -> File.Other, page) (Help.command_page_list ())
in
choose_from_list ~choice: 0 "Execute command: " commands state @@ fun command ->
State.add_history Command command state;
state.run_string command state
let help { H.add; line; nl; par; add_link; see_also } =
line "Execute an external command.";
par ();
add "Prompt for a program name and its arguments, such as ";
add ~style: (Style.bold ()) "ls -la"; add ", and execute it."; nl();
par ();
line "Run the process in the background. Display program output in the current panel.";
see_also [ "execute_command" ]
let () = define "execute_process" ~help Command @@ fun state ->
let panel = state.focus in
prompt "Execute process: " ~history: External_command state @@ fun command ->
State.add_history External_command command state;
match Shell_lexer.items [] [] (Lexing.from_string command) with
| exception Failure reason ->
abort "Parse error in command: %s" reason
| [] ->
()
| program :: arguments ->
let file = State.create_file state ("<" ^ command ^ ">") Text.empty in
Panel.set_current_view panel (File.create_view File file);
File.create_process file program arguments
let help { H.line; par; see_also } =
line "Switch to another already-opened file.";
par ();
line "Prompt for the filename to switch to.";
see_also [ "new"; "open" ]
let () = define "switch_file" ~help Command @@ fun state ->
let panel = state.focus in
let choices =
let make_choice_item_from_file not_modified modified (file: File.t): File.choice_item =
(if file.modified then modified else not_modified),
File.get_name file
in
let make_choice_item_from_view not_modified modified (view: File.view) =
make_choice_item_from_file not_modified modified view.file
in
List.map (make_choice_item_from_view Recent Recent_modified) (Panel.get_previous_views panel) @
(
state.files
|> List.sort (fun (a: File.t) (b: File.t) -> compare_names (File.get_name a) (File.get_name b))
|> List.map (make_choice_item_from_file Other Modified)
)
in
choose_from_list ~choice: 0 "Switch to file: " choices state @@ fun choice ->
match List.find (File.has_name choice) state.files with
| exception Not_found ->
abort "No such file: %s" choice
| file ->
Panel.set_current_file panel file
let help { H.line; add; nl; add_link; par; see_also } =
line "Select the item above the currently selected one.";
par ();
add "If you "; add_link "validate"; add " and an item is selected, choose this item"; nl ();
line "instead of what you typed.";
par ();
line "If no item is selected, select the first one, i.e. the one at the bottom.";
see_also [ "choose_previous" ]
let () = define "choose_next" ~help Command @@ fun state ->
let view = State.get_focused_view state in
match view.kind with
| List_choice choice ->
let choices = filter_choices (Text.to_string view.file.text) choice.choices in
choice.choice <- choice.choice + 1;
let max_choice = List.length choices - 1 in
if choice.choice > max_choice then choice.choice <- max_choice
| _ ->
abort "Focused panel has no prompt."
let help { H.line; add; nl; add_link; par; see_also } =
line "Select the item below the currently selected one.";
par ();
add "If you "; add_link "validate"; add " and an item is selected, choose this item"; nl ();
line "instead of what you typed.";
par ();
line "If the first item is selected, i.e. the one at the bottom, unselect it instead.";
see_also [ "choose_next" ]
let () = define "choose_previous" ~help Command @@ fun state ->
match (State.get_focused_view state).kind with
| List_choice choice ->
choice.choice <- choice.choice - 1;
if choice.choice < -1 then choice.choice <- -1
| _ ->
abort "Focused panel has no prompt."
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Split current panel vertically (top and bottom).";
par ();
add "If "; add_parameter "position"; add " is a positive integer, it specifies the height of the top panel."; nl ();
add "If "; add_parameter "position"; add " is a negative integer, it specifies the height of the bottom panel.";
nl ();
add "If "; add_parameter "position"; add " is a float, it is a ratio of the current panel height."; nl ();
add "Default "; add_parameter "position"; add " is 0.5 (half of current panel)."; nl ();
see_also [ "split_panel_horizontally"; "focus_down"; "focus_up"; "remove_panel" ]
let () = define "split_panel_vertically" ~help Command @@ fun state ->
split_panel Vertical (Layout.Ratio (1, 2)) state
let () = define "split_panel_vertically" ~help ("position" -: Int @-> Command) @@ fun position state ->
let position =
if position >= 0 then
Layout.Absolute_first position
else
Layout.Absolute_second (- position)
in
split_panel Vertical position state
let () = define "split_panel_vertically" ~help ("position" -: Float @-> Command) @@ fun position state ->
if position >= 0. && position < 1. then
let position = Layout.Ratio (int_of_float (position *. 100_000.), 100_000) in
split_panel Vertical position state
else
abort "Invalid position to split panel: %F" position
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Split current panel horizontally (top and bottom).";
par ();
add "If "; add_parameter "position";
add " is a positive integer, it specifies the height of the panel at the left."; nl ();
add "If "; add_parameter "position";
add " is a negative integer, it specifies the height of the panel at the right."; nl ();
add "If "; add_parameter "position"; add " is a float, it is a ratio of the current panel height."; nl ();
add "Default "; add_parameter "position"; add " is 0.5 (half of current panel)."; nl ();
see_also [ "split_panel_vertically"; "focus_right"; "focus_left"; "remove_panel" ]
let () = define "split_panel_horizontally" ~help Command @@ fun state ->
split_panel Horizontal (Layout.Ratio (1, 2)) state
let () = define "split_panel_horizontally" ~help ("position" -: Int @-> Command) @@ fun position state ->
let position =
if position >= 0 then
Layout.Absolute_first position
else
Layout.Absolute_second (- position)
in
split_panel Horizontal position state
let () = define "split_panel_horizontally" ~help ("position" -: Float @-> Command) @@ fun position state ->
if position >= 0. && position < 1. then
let position = Layout.Ratio (int_of_float (position *. 100_000.), 100_000) in
split_panel Horizontal position state
else
abort "Invalid position to split panel: %F" position
let get_selected_text_or_empty (view: File.view) =
match view.cursors with
| [] ->
Text.empty
| [ cursor ] ->
File.get_cursor_subtext cursor view.file.text
| _ :: _ :: _ ->
Text.empty
let search replace_by backwards case_sensitive (state: State.t) =
let view = State.get_focused_main_view state in
let search_from_cursor subtext (cursor: File.cursor) =
match
let equal_characters = if case_sensitive then Character.equals else Character.case_insensitive_equals in
if backwards then
Text.search_backwards
equal_characters
~x2: (cursor.search_start.x - 1) ~y2: cursor.search_start.y
~subtext view.file.text
else
Text.search_forwards
equal_characters
~x1: cursor.search_start.x ~y1: cursor.search_start.y
~subtext view.file.text
with
| None ->
false
| Some (x1, y1, x2, y2) ->
cursor.selection_start.x <- x1;
cursor.selection_start.y <- y1;
cursor.position.x <- x2 + 1;
cursor.position.y <- y2;
cursor.preferred_x <- x2 + 1;
true
in
let search_from_all_cursors ?(set_starting_position = false) ?subtext ?replace_by () =
(
match replace_by with
| None ->
(fun f -> f ())
| Some _ ->
File.edit true view.file
) @@ fun () ->
let exists_not_found = ref false in
(
File.foreach_cursor view @@ fun cursor ->
let subtext =
match subtext with
| None ->
File.get_cursor_subtext cursor view.file.text
| Some subtext ->
subtext
in
(
match replace_by with
| None ->
()
| Some replacement ->
File.replace_selection_with_text_for_cursor view cursor replacement;
);
if set_starting_position then (
let position =
let left, right = File.selection_boundaries cursor in
if backwards then left else right
in
cursor.search_start.x <- position.x;
cursor.search_start.y <- position.y;
);
if not (search_from_cursor subtext cursor) then exists_not_found := true
);
File.recenter_if_needed view;
Log.info "Text not found."
in
let default = get_selected_text_or_empty view in
let search_file = File.create "search" default in
let search_view = File.create_view (Search { backwards; case_sensitive }) search_file in
(
File.foreach_cursor search_view @@ fun cursor ->
move_cursor true false search_view cursor File.move_end_of_line
);
let replacement =
match replace_by, view.search with
| None, None ->
None
| Some _, _ ->
replace_by
| None, Some search ->
search.replacement
in
view.search <-
Some {
search_view;
replacement;
};
search_file.on_edit <- (fun () -> search_from_all_cursors ~subtext: search_file.text ());
search_from_all_cursors ~set_starting_position: true ?replace_by ()
let help { H.line; par; add; nl; add_parameter; add_link; see_also } =
line "Search for fixed text.";
par ();
line "Search for the next occurrence of the selected text.";
line "Edit text to search for in the search prompt.";
add "Exit search prompt using "; add_link "validate"; add " or "; add_link "cancel"; add "."; nl ();
par ();
line "When an occurrence is found, it is selected.";
line "Runnning this command again will thus search for the next occurrence.";
par ();
line "In multiple cursor mode, each cursor searches for his own selection.";
line "Editing the text to search in the search prompt will cause all cursors";
line "to search for this text instead.";
par ();
add "If "; add_parameter "case_sensitive"; add " is true, search for an exact match."; nl ();
line "Else, ignore case. Default is false.";
par ();
add "If "; add_parameter "backwards"; add " is true, search for the first occurrence before the cursor."; nl ();
line "Else, search for the first occurrence after the cursor. Default is false.";
see_also [ "replace"; "create_cursor_from_search" ]
let () = define "search" ~help ("backwards" -: Bool @-> "case_sensitive" -: Bool @-> Command) (search None)
let () = define "search" ~help Command (search None false false)
let help { H.line; par; add; nl; add_parameter; add_link; see_also } =
line "Replace selected text, then search.";
par ();
line "If already replacing text, use current replacement text.";
line "Else, prompt for a replacement text.";
par ();
line "Replace selection by replacement text.";
add "Then "; add_link "search"; add " for the next occurrence of the selected text before it was replaced."; nl ();
see_also [ "search"; "create_cursor_from_search" ]
let replace backwards case_sensitive (state: State.t) =
let view = State.get_focused_main_view state in
(
fun continue ->
match view.search with
| Some { replacement = Some replacement } ->
continue replacement
| None | Some { replacement = None } ->
let default = get_selected_text_or_empty view in
prompt ~history: Replacement_text ~default: (Text.to_string default) "Replace by: " state
@@ fun replacement ->
State.add_history Replacement_text replacement state;
continue (Text.of_utf8_string replacement)
) @@ fun replace_by ->
search (Some replace_by) backwards case_sensitive state
let () = define "replace" ~help ("backwards" -: Bool @-> "case_sensitive" -: Bool @-> Command) replace
let () = define "replace" ~help Command (replace false false)
let help { H.line; add; nl; add_parameter; par; see_also } =
line "Create a cursor by searching for another occurrence of the selected text.";
nl ();
add "If "; add_parameter "backwards"; add " is true, search for the first occurrence of the"; nl ();
line "text selected by the left-most cursor, before this cursor.";
line "Else, search for the first occurrence of the text selected";
line "by the right-most cursor, after this cursor. Default is false.";
see_also [ "search"; "replace" ]
let create_cursor_from_search backwards (state: State.t) =
let view = State.get_focused_view state in
let subtext, start =
match view.cursors with
| [] ->
abort "View has no cursor."
| head :: tail ->
let (<%) = File.(<%) in
let cursor =
if backwards then
let left_most (acc: File.cursor) (candidate: File.cursor) =
let acc_min = File.min_mark acc.selection_start acc.position in
let candidate_min = File.min_mark candidate.selection_start candidate.position in
if candidate_min <% acc_min then candidate else acc
in
List.fold_left left_most head tail
else
let right_most (acc: File.cursor) (candidate: File.cursor) =
let acc_max = File.max_mark acc.selection_start acc.position in
let candidate_max = File.max_mark candidate.selection_start candidate.position in
if candidate_max <% acc_max then acc else candidate
in
List.fold_left right_most head tail
in
let pattern = File.get_selected_text view.file.text cursor in
let start =
if backwards then
File.min_mark cursor.selection_start cursor.position
else
File.max_mark cursor.selection_start cursor.position
in
pattern, start
in
match
if backwards then
Text.search_backwards
Character.equals
~x2: (start.x - 1) ~y2: start.y
~subtext view.file.text
else
Text.search_forwards
Character.equals
~x1: start.x ~y1: start.y
~subtext view.file.text
with
| None ->
abort "Text not found."
| Some (x1, y1, x2, y2) ->
let cursor = File.create_cursor x1 y1 in
cursor.position.x <- x2 + 1;
cursor.position.y <- y2;
cursor.preferred_x <- x2 + 1;
File.set_cursors view (cursor :: view.cursors)
let () = define "create_cursor_from_search" ~help ("backwards" -: Bool @-> Command) create_cursor_from_search
let () = define "create_cursor_from_search" ~help Command (create_cursor_from_search false)
let help { H.line } =
line "Open prompt history."
let () = define "choose_from_history" ~help Command @@ fun state ->
let main_view = State.get_focused_main_view state in
match main_view.prompt with
| None ->
abort "No history here (no prompt)."
| Some { prompt_text; validate_prompt; prompt_view } ->
match prompt_view.file.history_context with
| None ->
abort "No history here."
| Some history_context ->
let choices = List.map (fun choice -> File.Other, choice) (State.get_history history_context state) in
choose_from_list ~choice: 0 prompt_text choices state @@ fun choice ->
main_view.prompt <- None;
validate_prompt choice
let help { H.line } =
line "Copy selected choice into prompt so you can edit it."
let () = define "edit_selected_choice" ~help Command @@ fun state ->
let view = State.get_focused_main_view state in
match view.kind with
| List_choice { choice; choices } ->
let filter = Text.to_string view.file.text in
(
match List.nth (filter_choices filter choices) choice with
| exception (Invalid_argument _ | Failure _) ->
abort "No selected choice."
| _, choice ->
select_all view;
File.replace_selection_with_text view (Text.of_utf8_string choice)
)
| _ ->
abort "Not selecting from a list."
let with_autocompletion view f =
match File.get_autocompletion view with
| No_cursor_to_autocomplete ->
abort "No cursor to autocomplete."
| Too_many_cursors_to_autocomplete ->
abort "Too many cursors to autocomplete."
| Nothing_to_autocomplete ->
abort_with_error "Nothing to autocomplete here."
| Word_is_on_multiple_lines ->
abort_with_error "Word is on multiple lines."
| May_autocomplete autocompletion ->
f autocompletion
let help { H.line; par; see_also } =
line "Open list of autocompletions.";
par ();
line "Autocompletions are big words which start with the one at cursor position.";
line "Big words are like words, but underscore is also part of big words.";
line "Candidate completions are found in open files.";
par ();
line "Has no effect if there are more than one cursors.";
see_also [ "autocomplete" ]
let () = define "choose_autocompletion" ~help Command @@ fun state ->
let view = State.get_focused_view state in
with_autocompletion view @@ fun { y; start_x; end_x; prefix; suffixes } ->
let choices =
Trie.to_list suffixes
|> List.map (fun (word, _) -> File.Other, String.concat "" (prefix @ word))
in
choose_from_list ~choice: 0 ("Autocomplete " ^ String.concat "" prefix ^ " with: ") choices state
@@ fun choice ->
File.replace view.file ~x: start_x ~y ~lines: 0 ~characters: (end_x - start_x) (Text.of_utf8_string choice)
let help { H.line; see_also } =
line "Autocomplete with the completion visible in the status bar.";
see_also [ "choose_autocompletion" ]
let () = define "autocomplete" ~help Command @@ fun state ->
let view = State.get_focused_view state in
with_autocompletion view @@ fun { y; start_x; end_x; best_word } ->
File.replace view.file ~x: start_x ~y ~lines: 0 ~characters: (end_x - start_x) (Text.of_utf8_string best_word)
|
d3b8f55e7c4cf8830a468855f8df7c47ea23c73554831466cd6b03c60bf860a7 | tisnik/clojure-examples | details.clj | {:aliases {"downgrade" "upgrade"},
:checkout-deps-shares
[:source-paths
:test-paths
:resource-paths
:compile-path
"#'leiningen.core.classpath/checkout-deps-paths"],
:clean-targets [:target-path],
:compile-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default/classes",
:dependencies
([org.clojure/clojure "1.10.1"]
[fundingcircle/jackdaw "0.7.6"]
[org.clojure/tools.logging "0.3.1"]
[log4j/log4j
"1.2.17"
:exclusions
([javax.mail/mail]
[javax.jms/jms]
[com.sun.jmdk/jmxtools]
[com.sun.jmx/jmxri])]
[org.slf4j/slf4j-log4j12 "1.6.6"]
[nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])]
[clojure-complete/clojure-complete
"0.2.5"
:exclusions
([org.clojure/clojure])]
[venantius/ultra "0.6.0"]),
:deploy-repositories
[["clojars"
{:url "/",
:password :gpg,
:username :gpg}]],
:description "FIXME: write description",
:eval-in :subprocess,
:global-vars {},
:group "stream-pipe-2",
:jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""],
:jvm-opts
["-XX:-OmitStackTraceInFastThrow"
"-XX:+TieredCompilation"
"-XX:TieredStopAtLevel=1"],
:license
{:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0",
:url "-2.0/"},
:main stream-pipe-2.core,
:monkeypatch-clojure-test false,
:name "stream-pipe-2",
:native-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default/native",
:offline? false,
:pedantic? ranges,
:plugin-repositories
[["central"
{:url "/", :snapshots false}]
["clojars" {:url "/"}]],
:plugins
([lein-codox/lein-codox "0.10.7"]
[test2junit/test2junit "1.1.0"]
[lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit/lein-kibit "0.1.8"]
[lein-clean-m2/lein-clean-m2 "0.1.2"]
[lein-project-edn/lein-project-edn "0.3.0"]
[lein-marginalia/lein-marginalia "0.9.1"]
[venantius/ultra "0.6.0"]),
:prep-tasks ["javac" "compile"],
:profiles
{:uberjar
{:aot [:all], :jvm-opts ["-Dclojure.compiler.direct-linking=true"]},
:whidbey/repl
{:dependencies [[mvxcvi/whidbey "RELEASE"]],
:repl-options
{:init
(do
nil
(clojure.core/require 'whidbey.repl)
(whidbey.repl/init! nil)),
:custom-init (do nil (whidbey.repl/update-print-fn!)),
:nrepl-context
{:interactive-eval {:printer whidbey.repl/render-str}}}}},
:project-edn {:output-file "doc/details.clj"},
:release-tasks
[["vcs" "assert-committed"]
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag"]
["deploy"]
["change" "version" "leiningen.release/bump-version"]
["vcs" "commit"]
["vcs" "push"]],
:repl-options
{:init
(do
(do
(clojure.core/require 'ultra.hardcore)
(clojure.core/require 'whidbey.repl)
(whidbey.repl/init! nil)
(ultra.hardcore/configure!
{:repl
{:print-meta false,
:map-delimiter "",
:print-fallback :print,
:sort-keys true}})))},
:repositories
[["central"
{:url "/", :snapshots false}]
["clojars" {:url "/"}]],
:resource-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/dev-resources"
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/resources"),
:root
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2",
:source-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/src"),
:target-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default",
:test-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/test"),
:test-selectors {:default (constantly true)},
:uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""],
:url "",
:version "0.1.0-SNAPSHOT"}
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/ad495c2443e542269cf4784fd5cfa62787cdff98/kafka-stream-pipe-2/doc/details.clj | clojure | {:aliases {"downgrade" "upgrade"},
:checkout-deps-shares
[:source-paths
:test-paths
:resource-paths
:compile-path
"#'leiningen.core.classpath/checkout-deps-paths"],
:clean-targets [:target-path],
:compile-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default/classes",
:dependencies
([org.clojure/clojure "1.10.1"]
[fundingcircle/jackdaw "0.7.6"]
[org.clojure/tools.logging "0.3.1"]
[log4j/log4j
"1.2.17"
:exclusions
([javax.mail/mail]
[javax.jms/jms]
[com.sun.jmdk/jmxtools]
[com.sun.jmx/jmxri])]
[org.slf4j/slf4j-log4j12 "1.6.6"]
[nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])]
[clojure-complete/clojure-complete
"0.2.5"
:exclusions
([org.clojure/clojure])]
[venantius/ultra "0.6.0"]),
:deploy-repositories
[["clojars"
{:url "/",
:password :gpg,
:username :gpg}]],
:description "FIXME: write description",
:eval-in :subprocess,
:global-vars {},
:group "stream-pipe-2",
:jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""],
:jvm-opts
["-XX:-OmitStackTraceInFastThrow"
"-XX:+TieredCompilation"
"-XX:TieredStopAtLevel=1"],
:license
{:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0",
:url "-2.0/"},
:main stream-pipe-2.core,
:monkeypatch-clojure-test false,
:name "stream-pipe-2",
:native-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default/native",
:offline? false,
:pedantic? ranges,
:plugin-repositories
[["central"
{:url "/", :snapshots false}]
["clojars" {:url "/"}]],
:plugins
([lein-codox/lein-codox "0.10.7"]
[test2junit/test2junit "1.1.0"]
[lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit/lein-kibit "0.1.8"]
[lein-clean-m2/lein-clean-m2 "0.1.2"]
[lein-project-edn/lein-project-edn "0.3.0"]
[lein-marginalia/lein-marginalia "0.9.1"]
[venantius/ultra "0.6.0"]),
:prep-tasks ["javac" "compile"],
:profiles
{:uberjar
{:aot [:all], :jvm-opts ["-Dclojure.compiler.direct-linking=true"]},
:whidbey/repl
{:dependencies [[mvxcvi/whidbey "RELEASE"]],
:repl-options
{:init
(do
nil
(clojure.core/require 'whidbey.repl)
(whidbey.repl/init! nil)),
:custom-init (do nil (whidbey.repl/update-print-fn!)),
:nrepl-context
{:interactive-eval {:printer whidbey.repl/render-str}}}}},
:project-edn {:output-file "doc/details.clj"},
:release-tasks
[["vcs" "assert-committed"]
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag"]
["deploy"]
["change" "version" "leiningen.release/bump-version"]
["vcs" "commit"]
["vcs" "push"]],
:repl-options
{:init
(do
(do
(clojure.core/require 'ultra.hardcore)
(clojure.core/require 'whidbey.repl)
(whidbey.repl/init! nil)
(ultra.hardcore/configure!
{:repl
{:print-meta false,
:map-delimiter "",
:print-fallback :print,
:sort-keys true}})))},
:repositories
[["central"
{:url "/", :snapshots false}]
["clojars" {:url "/"}]],
:resource-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/dev-resources"
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/resources"),
:root
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2",
:source-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/src"),
:target-path
"/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/target/default",
:test-paths
("/home/ptisnovs/src/clojure/clojure-examples/kafka-stream-pipe-2/test"),
:test-selectors {:default (constantly true)},
:uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""],
:url "",
:version "0.1.0-SNAPSHOT"}
|
|
980672e0a06837d466436c7c67027abce24522bfb773947dadfe2a699762e9c0 | bgusach/exercises-htdp2e | ex-273.rkt | #lang htdp/isl
(require test-engine/racket-tests)
# # # Data Definitions
# # # Functions
; [A B] [A -> B] [List-of A] -> [List-of B]
(check-expect (map-clone add1 '()) '())
(check-expect (map-clone add1 '(1 2 3)) '(2 3 4))
(define (map-clone fn l)
(local
(; [A B] A B -> B
(define (merge x acc)
(cons (fn x) acc)
))
(foldr merge '() l)
))
(test)
| null | https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/3-abstraction/ex-273.rkt | racket | [A B] [A -> B] [List-of A] -> [List-of B]
[A B] A B -> B | #lang htdp/isl
(require test-engine/racket-tests)
# # # Data Definitions
# # # Functions
(check-expect (map-clone add1 '()) '())
(check-expect (map-clone add1 '(1 2 3)) '(2 3 4))
(define (map-clone fn l)
(local
(define (merge x acc)
(cons (fn x) acc)
))
(foldr merge '() l)
))
(test)
|
0c6ee77ae0740e85c9cfff70f21f989718afe8f782e63f37054cfee3b324bf78 | mainland/ref-fd | Ref.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - warnings - deprecations #
-- |
Module : Control . . Ref
Copyright : ( c ) Harvard University 2006 - 2011
( c ) 2011 - 2014
-- License : BSD-style
Maintainer : < >
--
-- Stability : experimental
-- Portability : non-portable
module Control.Monad.Ref (
MonadRef(..),
MonadAtomicRef(..)
) where
import Control.Concurrent.STM (STM)
import Control.Concurrent.STM.TVar (TVar,
newTVar,
readTVar,
writeTVar)
import Control.Monad.ST (ST)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Error (ErrorT, Error)
#if MIN_VERSION_transformers(0,4,0)
import Control.Monad.Trans.Except (ExceptT)
#endif /* MIN_VERSION_transformers(0,4,0) */
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Trans.State.Lazy as Lazy (StateT)
import Control.Monad.Trans.State.Strict as Strict (StateT)
import Control.Monad.Trans.Writer.Lazy as Lazy (WriterT)
import Control.Monad.Trans.Writer.Strict as Strict (WriterT)
import Control.Monad.Trans.Class (lift)
import Data.IORef (IORef,
#if MIN_VERSION_base(4,6,0)
atomicModifyIORef',
modifyIORef',
#endif /* MIN_VERSION_base(4,6,0) */
atomicModifyIORef,
modifyIORef,
newIORef,
readIORef,
writeIORef)
import Data.Monoid (Monoid)
import Data.STRef (STRef,
#if MIN_VERSION_base(4,6,0)
modifySTRef',
#endif /* MIN_VERSION_base(4,6,0) */
modifySTRef,
newSTRef,
readSTRef,
writeSTRef)
-- |The 'MonadRef' type class abstracts over the details of manipulating
-- references, allowing one to write code that uses references and can operate
-- in any monad that supports reference operations.
class (Monad m) => MonadRef r m | m -> r where
|Create a new reference
newRef :: a -> m (r a)
-- |Read the value of a reference
readRef :: r a -> m a
-- |Write a new value to a reference
writeRef :: r a -> a -> m ()
-- |Mutate the contents of a reference
modifyRef :: r a -> (a -> a) -> m ()
modifyRef r f = readRef r >>= writeRef r . f
-- |Strict version of 'modifyRef'
modifyRef' :: r a -> (a -> a) -> m ()
modifyRef' r f = readRef r >>= \x -> let x' = f x in x' `seq` writeRef r x'
class (MonadRef r m) => MonadAtomicRef r m | m -> r where
-- |Atomically mutate the contents of a reference
atomicModifyRef :: r a -> (a -> (a, b)) -> m b
-- |Strict version of atomicModifyRef. This forces both the value stored in
-- the reference as well as the value returned.
atomicModifyRef' :: r a -> (a -> (a, b)) -> m b
atomicModifyRef' r f = do
b <- atomicModifyRef r
(\x -> let (a, b) = f x
in (a, a `seq` b))
b `seq` return b
instance MonadRef (STRef s) (ST s) where
newRef = newSTRef
readRef = readSTRef
writeRef = writeSTRef
modifyRef = modifySTRef
#if MIN_VERSION_base(4,6,0)
modifyRef' = modifySTRef'
#endif /* MIN_VERSION_base(4,6,0) */
instance MonadRef IORef IO where
newRef = newIORef
readRef = readIORef
writeRef = writeIORef
modifyRef = modifyIORef
#if MIN_VERSION_base(4,6,0)
modifyRef' = modifyIORef'
#endif /* MIN_VERSION_base(4,6,0) */
instance MonadRef TVar STM where
newRef = newTVar
readRef = readTVar
writeRef = writeTVar
instance MonadRef r m => MonadRef r (ContT r' m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Error e, MonadRef r m) => MonadRef r (ErrorT e m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
#if MIN_VERSION_transformers(0,4,0)
instance (MonadRef r m) => MonadRef r (ExceptT e m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
#endif /* MIN_VERSION_transformers(0,4,0) */
instance MonadRef r m => MonadRef r (IdentityT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (ListT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (MaybeT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (ReaderT r' m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (Lazy.StateT s m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (Strict.StateT s m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Monoid w, MonadRef r m) => MonadRef r (Lazy.WriterT w m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Monoid w, MonadRef r m) => MonadRef r (Strict.WriterT w m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadAtomicRef IORef IO where
atomicModifyRef = atomicModifyIORef
#if MIN_VERSION_base(4,6,0)
atomicModifyRef' = atomicModifyIORef'
#endif /* MIN_VERSION_base(4,6,0) */
-- Since there's no forking, it's automatically atomic.
instance MonadAtomicRef (STRef s) (ST s) where
atomicModifyRef r f = do
x <- readRef r
let (x', y) = f x
writeRef r x'
return y
atomicModifyRef' r f = do
x <- readRef r
let (x', y) = f x
writeRef r $! x'
return y
instance MonadAtomicRef TVar STM where
atomicModifyRef r f = do x <- readRef r
let (x', y) = f x
writeRef r x'
return y
instance MonadAtomicRef r m => MonadAtomicRef r (ContT r' m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Error e, MonadAtomicRef r m) => MonadAtomicRef r (ErrorT e m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (IdentityT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (ListT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (MaybeT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (ReaderT r' m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (Lazy.StateT s m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (Strict.StateT s m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Monoid w, MonadAtomicRef r m) => MonadAtomicRef r (Lazy.WriterT w m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Monoid w, MonadAtomicRef r m) => MonadAtomicRef r (Strict.WriterT w m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
| null | https://raw.githubusercontent.com/mainland/ref-fd/9a95b1ccb5c637a6e29299b3d71c76c3ad1d7f98/Control/Monad/Ref.hs | haskell | |
License : BSD-style
Stability : experimental
Portability : non-portable
|The 'MonadRef' type class abstracts over the details of manipulating
references, allowing one to write code that uses references and can operate
in any monad that supports reference operations.
|Read the value of a reference
|Write a new value to a reference
|Mutate the contents of a reference
|Strict version of 'modifyRef'
|Atomically mutate the contents of a reference
|Strict version of atomicModifyRef. This forces both the value stored in
the reference as well as the value returned.
Since there's no forking, it's automatically atomic. | # LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - warnings - deprecations #
Module : Control . . Ref
Copyright : ( c ) Harvard University 2006 - 2011
( c ) 2011 - 2014
Maintainer : < >
module Control.Monad.Ref (
MonadRef(..),
MonadAtomicRef(..)
) where
import Control.Concurrent.STM (STM)
import Control.Concurrent.STM.TVar (TVar,
newTVar,
readTVar,
writeTVar)
import Control.Monad.ST (ST)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Error (ErrorT, Error)
#if MIN_VERSION_transformers(0,4,0)
import Control.Monad.Trans.Except (ExceptT)
#endif /* MIN_VERSION_transformers(0,4,0) */
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.List (ListT)
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.Trans.Reader (ReaderT)
import Control.Monad.Trans.State.Lazy as Lazy (StateT)
import Control.Monad.Trans.State.Strict as Strict (StateT)
import Control.Monad.Trans.Writer.Lazy as Lazy (WriterT)
import Control.Monad.Trans.Writer.Strict as Strict (WriterT)
import Control.Monad.Trans.Class (lift)
import Data.IORef (IORef,
#if MIN_VERSION_base(4,6,0)
atomicModifyIORef',
modifyIORef',
#endif /* MIN_VERSION_base(4,6,0) */
atomicModifyIORef,
modifyIORef,
newIORef,
readIORef,
writeIORef)
import Data.Monoid (Monoid)
import Data.STRef (STRef,
#if MIN_VERSION_base(4,6,0)
modifySTRef',
#endif /* MIN_VERSION_base(4,6,0) */
modifySTRef,
newSTRef,
readSTRef,
writeSTRef)
class (Monad m) => MonadRef r m | m -> r where
|Create a new reference
newRef :: a -> m (r a)
readRef :: r a -> m a
writeRef :: r a -> a -> m ()
modifyRef :: r a -> (a -> a) -> m ()
modifyRef r f = readRef r >>= writeRef r . f
modifyRef' :: r a -> (a -> a) -> m ()
modifyRef' r f = readRef r >>= \x -> let x' = f x in x' `seq` writeRef r x'
class (MonadRef r m) => MonadAtomicRef r m | m -> r where
atomicModifyRef :: r a -> (a -> (a, b)) -> m b
atomicModifyRef' :: r a -> (a -> (a, b)) -> m b
atomicModifyRef' r f = do
b <- atomicModifyRef r
(\x -> let (a, b) = f x
in (a, a `seq` b))
b `seq` return b
instance MonadRef (STRef s) (ST s) where
newRef = newSTRef
readRef = readSTRef
writeRef = writeSTRef
modifyRef = modifySTRef
#if MIN_VERSION_base(4,6,0)
modifyRef' = modifySTRef'
#endif /* MIN_VERSION_base(4,6,0) */
instance MonadRef IORef IO where
newRef = newIORef
readRef = readIORef
writeRef = writeIORef
modifyRef = modifyIORef
#if MIN_VERSION_base(4,6,0)
modifyRef' = modifyIORef'
#endif /* MIN_VERSION_base(4,6,0) */
instance MonadRef TVar STM where
newRef = newTVar
readRef = readTVar
writeRef = writeTVar
instance MonadRef r m => MonadRef r (ContT r' m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Error e, MonadRef r m) => MonadRef r (ErrorT e m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
#if MIN_VERSION_transformers(0,4,0)
instance (MonadRef r m) => MonadRef r (ExceptT e m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
#endif /* MIN_VERSION_transformers(0,4,0) */
instance MonadRef r m => MonadRef r (IdentityT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (ListT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (MaybeT m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (ReaderT r' m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (Lazy.StateT s m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadRef r m => MonadRef r (Strict.StateT s m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Monoid w, MonadRef r m) => MonadRef r (Lazy.WriterT w m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance (Monoid w, MonadRef r m) => MonadRef r (Strict.WriterT w m) where
newRef r = lift $ newRef r
readRef r = lift $ readRef r
writeRef r x = lift $ writeRef r x
modifyRef r f = lift $ modifyRef r f
modifyRef' r f = lift $ modifyRef' r f
instance MonadAtomicRef IORef IO where
atomicModifyRef = atomicModifyIORef
#if MIN_VERSION_base(4,6,0)
atomicModifyRef' = atomicModifyIORef'
#endif /* MIN_VERSION_base(4,6,0) */
instance MonadAtomicRef (STRef s) (ST s) where
atomicModifyRef r f = do
x <- readRef r
let (x', y) = f x
writeRef r x'
return y
atomicModifyRef' r f = do
x <- readRef r
let (x', y) = f x
writeRef r $! x'
return y
instance MonadAtomicRef TVar STM where
atomicModifyRef r f = do x <- readRef r
let (x', y) = f x
writeRef r x'
return y
instance MonadAtomicRef r m => MonadAtomicRef r (ContT r' m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Error e, MonadAtomicRef r m) => MonadAtomicRef r (ErrorT e m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (IdentityT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (ListT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (MaybeT m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (ReaderT r' m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (Lazy.StateT s m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance MonadAtomicRef r m => MonadAtomicRef r (Strict.StateT s m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Monoid w, MonadAtomicRef r m) => MonadAtomicRef r (Lazy.WriterT w m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
instance (Monoid w, MonadAtomicRef r m) => MonadAtomicRef r (Strict.WriterT w m) where
atomicModifyRef r f = lift $ atomicModifyRef r f
atomicModifyRef' r f = lift $ atomicModifyRef' r f
|
ec208c94ef8069c4085479ce575f4954bede5a00de9e75febae14e6e89c41c36 | jrh13/hol-light | platonic.ml | (* ========================================================================= *)
The five Platonic solids exist and there are no others .
(* ========================================================================= *)
needs "100/polyhedron.ml";;
needs "Multivariate/cross.ml";;
prioritize_real();;
(* ------------------------------------------------------------------------- *)
Some standard regular polyhedra ( vertex coordinates from Wikipedia ) .
(* ------------------------------------------------------------------------- *)
let std_tetrahedron = new_definition
`std_tetrahedron =
convex hull
{vector[&1;&1;&1],vector[-- &1;-- &1;&1],
vector[-- &1;&1;-- &1],vector[&1;-- &1;-- &1]}:real^3->bool`;;
let std_cube = new_definition
`std_cube =
convex hull
{vector[&1;&1;&1],vector[&1;&1;-- &1],
vector[&1;-- &1;&1],vector[&1;-- &1;-- &1],
vector[-- &1;&1;&1],vector[-- &1;&1;-- &1],
vector[-- &1;-- &1;&1],vector[-- &1;-- &1;-- &1]}:real^3->bool`;;
let std_octahedron = new_definition
`std_octahedron =
convex hull
{vector[&1;&0;&0],vector[-- &1;&0;&0],
vector[&0;&0;&1],vector[&0;&0;-- &1],
vector[&0;&1;&0],vector[&0;-- &1;&0]}:real^3->bool`;;
let std_dodecahedron = new_definition
`std_dodecahedron =
let p = (&1 + sqrt(&5)) / &2 in
convex hull
{vector[&1;&1;&1],vector[&1;&1;-- &1],
vector[&1;-- &1;&1],vector[&1;-- &1;-- &1],
vector[-- &1;&1;&1],vector[-- &1;&1;-- &1],
vector[-- &1;-- &1;&1],vector[-- &1;-- &1;-- &1],
vector[&0;inv p;p],vector[&0;inv p;--p],
vector[&0;--inv p;p],vector[&0;--inv p;--p],
vector[inv p;p;&0],vector[inv p;--p;&0],
vector[--inv p;p;&0],vector[--inv p;--p;&0],
vector[p;&0;inv p],vector[--p;&0;inv p],
vector[p;&0;--inv p],vector[--p;&0;--inv p]}:real^3->bool`;;
let std_icosahedron = new_definition
`std_icosahedron =
let p = (&1 + sqrt(&5)) / &2 in
convex hull
{vector[&0; &1; p],vector[&0; &1; --p],
vector[&0; -- &1; p],vector[&0; -- &1; --p],
vector[&1; p; &0],vector[&1; --p; &0],
vector[-- &1; p; &0],vector[-- &1; --p; &0],
vector[p; &0; &1],vector[--p; &0; &1],
vector[p; &0; -- &1],vector[--p; &0; -- &1]}:real^3->bool`;;
(* ------------------------------------------------------------------------- *)
(* Slightly ad hoc conversions for computation in Q[sqrt(5)]. *)
(* Numbers are canonically represented as either a rational constant r or an *)
expression r1 + r2 * sqrt(5 ) where r2 is nonzero but r1 may be zero and
(* must be present. *)
(* ------------------------------------------------------------------------- *)
let REAL_RAT5_OF_RAT_CONV =
let pth = prove
(`p = p + &0 * sqrt(&5)`,
REAL_ARITH_TAC) in
let conv = REWR_CONV pth in
fun tm -> if is_ratconst tm then conv tm else REFL tm;;
let REAL_RAT_OF_RAT5_CONV =
let pth = prove
(`p + &0 * sqrt(&5) = p`,
REAL_ARITH_TAC) in
GEN_REWRITE_CONV TRY_CONV [pth];;
let REAL_RAT5_ADD_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) + (a2 + b2 * sqrt(&5)) =
(a1 + a2) + (b1 + b2) * sqrt(&5)`,
REAL_ARITH_TAC) in
REAL_RAT_ADD_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV REAL_RAT_ADD_CONV THENC
RAND_CONV(LAND_CONV REAL_RAT_ADD_CONV) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_SUB_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) - (a2 + b2 * sqrt(&5)) =
(a1 - a2) + (b1 - b2) * sqrt(&5)`,
REAL_ARITH_TAC) in
REAL_RAT_SUB_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV REAL_RAT_SUB_CONV THENC
RAND_CONV(LAND_CONV REAL_RAT_SUB_CONV) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_MUL_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) * (a2 + b2 * sqrt(&5)) =
(a1 * a2 + &5 * b1 * b2) + (a1 * b2 + a2 * b1) * sqrt(&5)`,
MP_TAC(ISPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD) in
REAL_RAT_MUL_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV(COMB_CONV (RAND_CONV REAL_RAT_MUL_CONV) THENC
RAND_CONV REAL_RAT_MUL_CONV THENC
REAL_RAT_ADD_CONV) THENC
RAND_CONV(LAND_CONV
(BINOP_CONV REAL_RAT_MUL_CONV THENC REAL_RAT_ADD_CONV)) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_INV_CONV =
let pth = prove
(`~(a pow 2 = &5 * b pow 2)
==> inv(a + b * sqrt(&5)) =
a / (a pow 2 - &5 * b pow 2) +
--b / (a pow 2 - &5 * b pow 2) * sqrt(&5)`,
REPEAT GEN_TAC THEN
GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [GSYM REAL_SUB_0] THEN
SUBGOAL_THEN
`a pow 2 - &5 * b pow 2 = (a + b * sqrt(&5)) * (a - b * sqrt(&5))`
SUBST1_TAC THENL
[MP_TAC(SPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD;
REWRITE_TAC[REAL_ENTIRE; DE_MORGAN_THM] THEN CONV_TAC REAL_FIELD]) in
fun tm ->
try REAL_RAT_INV_CONV tm with Failure _ ->
let th1 = PART_MATCH (lhs o rand) pth tm in
let th2 = MP th1 (EQT_ELIM(REAL_RAT_REDUCE_CONV(lhand(concl th1)))) in
let th3 = CONV_RULE(funpow 2 RAND_CONV (funpow 2 LAND_CONV
REAL_RAT_NEG_CONV)) th2 in
let th4 = CONV_RULE(RAND_CONV(RAND_CONV(LAND_CONV
(RAND_CONV(LAND_CONV REAL_RAT_POW_CONV THENC
RAND_CONV(RAND_CONV REAL_RAT_POW_CONV THENC
REAL_RAT_MUL_CONV) THENC
REAL_RAT_SUB_CONV) THENC
REAL_RAT_DIV_CONV)))) th3 in
let th5 = CONV_RULE(RAND_CONV(LAND_CONV
(RAND_CONV(LAND_CONV REAL_RAT_POW_CONV THENC
RAND_CONV(RAND_CONV REAL_RAT_POW_CONV THENC
REAL_RAT_MUL_CONV) THENC
REAL_RAT_SUB_CONV) THENC
REAL_RAT_DIV_CONV))) th4 in
th5;;
let REAL_RAT5_DIV_CONV =
GEN_REWRITE_CONV I [real_div] THENC
RAND_CONV REAL_RAT5_INV_CONV THENC
REAL_RAT5_MUL_CONV;;
let REAL_RAT5_LE_CONV =
let lemma = prove
(`!x y. x <= y * sqrt(&5) <=>
x <= &0 /\ &0 <= y \/
&0 <= x /\ &0 <= y /\ x pow 2 <= &5 * y pow 2 \/
x <= &0 /\ y <= &0 /\ &5 * y pow 2 <= x pow 2`,
REPEAT GEN_TAC THEN MP_TAC(ISPEC `&5` SQRT_POW_2) THEN
REWRITE_TAC[REAL_POS] THEN DISCH_THEN(fun th ->
GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [SYM th]) THEN
REWRITE_TAC[GSYM REAL_POW_MUL; GSYM REAL_LE_SQUARE_ABS] THEN
MP_TAC(ISPECL [`sqrt(&5)`; `y:real`] (CONJUNCT1 REAL_LE_MUL_EQ)) THEN
SIMP_TAC[SQRT_POS_LT; REAL_OF_NUM_LT; ARITH] THEN REAL_ARITH_TAC) in
let pth = prove
(`(a1 + b1 * sqrt(&5)) <= (a2 + b2 * sqrt(&5)) <=>
a1 <= a2 /\ b1 <= b2 \/
a2 <= a1 /\ b1 <= b2 /\ (a1 - a2) pow 2 <= &5 * (b2 - b1) pow 2 \/
a1 <= a2 /\ b2 <= b1 /\ &5 * (b2 - b1) pow 2 <= (a1 - a2) pow 2`,
REWRITE_TAC[REAL_ARITH
`a + b * x <= a' + b' * x <=> a - a' <= (b' - b) * x`] THEN
REWRITE_TAC[lemma] THEN REAL_ARITH_TAC) in
REAL_RAT_LE_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
REAL_RAT_REDUCE_CONV);;
let REAL_RAT5_EQ_CONV =
GEN_REWRITE_CONV I [GSYM REAL_LE_ANTISYM] THENC
BINOP_CONV REAL_RAT5_LE_CONV THENC
GEN_REWRITE_CONV I [AND_CLAUSES];;
(* ------------------------------------------------------------------------- *)
(* Conversions for operations on 3D vectors with coordinates in Q[sqrt(5)] *)
(* ------------------------------------------------------------------------- *)
let VECTOR3_SUB_CONV =
let pth = prove
(`vector[x1;x2;x3] - vector[y1;y2;y3]:real^3 =
vector[x1-y1; x2-y2; x3-y3]`,
SIMP_TAC[CART_EQ; DIMINDEX_3; FORALL_3] THEN
REWRITE_TAC[VECTOR_3; VECTOR_SUB_COMPONENT]) in
GEN_REWRITE_CONV I [pth] THENC RAND_CONV(LIST_CONV REAL_RAT5_SUB_CONV);;
let VECTOR3_CROSS_CONV =
let pth = prove
(`(vector[x1;x2;x3]) cross (vector[y1;y2;y3]) =
vector[x2 * y3 - x3 * y2; x3 * y1 - x1 * y3; x1 * y2 - x2 * y1]`,
REWRITE_TAC[cross; VECTOR_3]) in
GEN_REWRITE_CONV I [pth] THENC
RAND_CONV(LIST_CONV(BINOP_CONV REAL_RAT5_MUL_CONV THENC REAL_RAT5_SUB_CONV));;
let VECTOR3_EQ_0_CONV =
let pth = prove
(`vector[x1;x2;x3]:real^3 = vec 0 <=>
x1 = &0 /\ x2 = &0 /\ x3 = &0`,
SIMP_TAC[CART_EQ; DIMINDEX_3; FORALL_3] THEN
REWRITE_TAC[VECTOR_3; VEC_COMPONENT]) in
GEN_REWRITE_CONV I [pth] THENC
DEPTH_BINOP_CONV `(/\)` REAL_RAT5_EQ_CONV THENC
REWRITE_CONV[];;
let VECTOR3_DOT_CONV =
let pth = prove
(`(vector[x1;x2;x3]:real^3) dot (vector[y1;y2;y3]) =
x1*y1 + x2*y2 + x3*y3`,
REWRITE_TAC[DOT_3; VECTOR_3]) in
GEN_REWRITE_CONV I [pth] THENC
DEPTH_BINOP_CONV `(+):real->real->real` REAL_RAT5_MUL_CONV THENC
RAND_CONV REAL_RAT5_ADD_CONV THENC
REAL_RAT5_ADD_CONV;;
(* ------------------------------------------------------------------------- *)
(* Put any irrational coordinates in our standard form. *)
(* ------------------------------------------------------------------------- *)
let STD_DODECAHEDRON = prove
(`std_dodecahedron =
convex hull
{ vector[&1; &1; &1],
vector[&1; &1; -- &1],
vector[&1; -- &1; &1],
vector[&1; -- &1; -- &1],
vector[-- &1; &1; &1],
vector[-- &1; &1; -- &1],
vector[-- &1; -- &1; &1],
vector[-- &1; -- &1; -- &1],
vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)]}`,
let golden_inverse = prove
(`inv((&1 + sqrt(&5)) / &2) = -- &1 / &2 + &1 / &2 * sqrt(&5)`,
MP_TAC(ISPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD) in
REWRITE_TAC[std_dodecahedron] THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[golden_inverse] THEN
REWRITE_TAC[REAL_ARITH `(&1 + s) / &2 = &1 / &2 + &1 / &2 * s`] THEN
REWRITE_TAC[REAL_ARITH `--(a + b * sqrt(&5)) = --a + --b * sqrt(&5)`] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[]);;
let STD_ICOSAHEDRON = prove
(`std_icosahedron =
convex hull
{ vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1]}`,
REWRITE_TAC[std_icosahedron] THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[REAL_ARITH `(&1 + s) / &2 = &1 / &2 + &1 / &2 * s`] THEN
REWRITE_TAC[REAL_ARITH `--(a + b * sqrt(&5)) = --a + --b * sqrt(&5)`] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[]);;
(* ------------------------------------------------------------------------- *)
(* Explicit computation of facets. *)
(* ------------------------------------------------------------------------- *)
let COMPUTE_FACES_2 = prove
(`!f s:real^3->bool.
FINITE s
==> (f face_of (convex hull s) /\ aff_dim f = &2 <=>
?x y z. x IN s /\ y IN s /\ z IN s /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN s ==> a dot w <= b) \/
(!w. w IN s ==> a dot w >= b)) /\
f = convex hull (s INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN STRIP_TAC THEN EQ_TAC THENL
[STRIP_TAC THEN
SUBGOAL_THEN `?t:real^3->bool. t SUBSET s /\ f = convex hull t`
MP_TAC THENL
[MATCH_MP_TAC FACE_OF_CONVEX_HULL_SUBSET THEN
ASM_SIMP_TAC[FINITE_IMP_COMPACT];
DISCH_THEN(X_CHOOSE_THEN `t:real^3->bool` MP_TAC)] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_CONVEX_HULL]) THEN
MP_TAC(ISPEC `t:real^3->bool` AFFINE_BASIS_EXISTS) THEN
DISCH_THEN(X_CHOOSE_THEN `u:real^3->bool` STRIP_ASSUME_TAC) THEN
SUBGOAL_THEN `(u:real^3->bool) HAS_SIZE 3` MP_TAC THENL
[ASM_SIMP_TAC[HAS_SIZE; AFFINE_INDEPENDENT_IMP_FINITE] THEN
REWRITE_TAC[GSYM INT_OF_NUM_EQ] THEN MATCH_MP_TAC(INT_ARITH
`aff_dim(u:real^3->bool) = &2 /\ aff_dim u = &(CARD u) - &1
==> &(CARD u):int = &3`) THEN CONJ_TAC
THENL [ASM_MESON_TAC[AFF_DIM_AFFINE_HULL]; ASM_MESON_TAC[AFF_DIM_UNIQUE]];
ALL_TAC] THEN
CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN SIMP_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPEAT(DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC)) THEN
DISCH_THEN SUBST_ALL_TAC THEN
MAP_EVERY EXISTS_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPLICATE_TAC 3 (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN
REPEAT LET_TAC THEN
SUBGOAL_THEN `~collinear{x:real^3,y,z}` MP_TAC THENL
[ASM_REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT]; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE `{x,y,z} = {z,x,y}`] THEN
ONCE_REWRITE_TAC[COLLINEAR_3] THEN ASM_REWRITE_TAC[GSYM CROSS_EQ_0] THEN
DISCH_TAC THEN ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `(a:real^3) dot y = b /\ (a:real^3) dot z = b`
STRIP_ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC
[`(z - x) cross (y - x) = a`; `(a:real^3) dot x = b`] THEN VEC3_TAC;
ALL_TAC] THEN
MP_TAC(ISPECL [`convex hull s:real^3->bool`; `convex hull t:real^3->bool`]
EXPOSED_FACE_OF_POLYHEDRON) THEN
ASM_SIMP_TAC[POLYHEDRON_CONVEX_HULL; exposed_face_of] THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`a':real^3`; `b':real`] THEN
DISCH_THEN(STRIP_ASSUME_TAC o GSYM) THEN
SUBGOAL_THEN
`aff_dim(t:real^3->bool)
<= aff_dim({x:real^3 | a dot x = b} INTER {x | a' dot x = b'})`
MP_TAC THENL
[GEN_REWRITE_TAC LAND_CONV [GSYM AFF_DIM_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (LAND_CONV o RAND_CONV)
[SYM th]) THEN
REWRITE_TAC[AFF_DIM_AFFINE_HULL] THEN MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[SUBSET_INTER] THEN CONJ_TAC THENL
[ASM SET_TAC[];
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC `t:real^3->bool` THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[]];
ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFF_DIM_HYPERPLANE;
AFFINE_HYPERPLANE; DIMINDEX_3] THEN
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[SUBSET_HYPERPLANES]) THEN
ASM_REWRITE_TAC[HYPERPLANE_EQ_EMPTY] THEN
DISCH_THEN(DISJ_CASES_THEN2 SUBST_ALL_TAC (MP_TAC o SYM)) THENL
[RULE_ASSUM_TAC(REWRITE_RULE[INTER_UNIV]) THEN
SUBGOAL_THEN `s SUBSET {x:real^3 | a dot x = b}` ASSUME_TAC THENL
[MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull s:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `affine hull t:real^3->bool` THEN
REWRITE_TAC[CONVEX_HULL_SUBSET_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM SET_TAC[];
ALL_TAC] THEN
CONJ_TAC THENL
[RULE_ASSUM_TAC(REWRITE_RULE[SUBSET; IN_ELIM_THM]) THEN
ASM_SIMP_TAC[real_ge; REAL_LE_REFL];
ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`]];
ALL_TAC] THEN
DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(TAUT `(~p /\ ~q ==> F) ==> p \/ q`) THEN
REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; real_ge; REAL_NOT_LE] THEN
DISCH_THEN(CONJUNCTS_THEN2
(X_CHOOSE_TAC `u:real^3`) (X_CHOOSE_TAC `v:real^3`)) THEN
SUBGOAL_THEN `(a':real^3) dot u < b' /\ a' dot v < b'` ASSUME_TAC THENL
[REWRITE_TAC[REAL_LT_LE] THEN REWRITE_TAC
[SET_RULE `f x <= b /\ ~(f x = b) <=>
x IN {x | f x <= b} /\ ~(x IN {x | f x = b})`] THEN
ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[IN_ELIM_THM; REAL_LT_IMP_NE] THEN
SUBGOAL_THEN `(u:real^3) IN convex hull s /\ v IN convex hull s`
MP_TAC THENL [ASM_SIMP_TAC[HULL_INC]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `?w:real^3. w IN segment[u,v] /\ w IN {w | a' dot w = b'}`
MP_TAC THENL
[ASM_REWRITE_TAC[] THEN REWRITE_TAC[IN_ELIM_THM] THEN
MATCH_MP_TAC CONNECTED_IVT_HYPERPLANE THEN
MAP_EVERY EXISTS_TAC [`v:real^3`; `u:real^3`] THEN
ASM_SIMP_TAC[ENDS_IN_SEGMENT; CONNECTED_SEGMENT; REAL_LT_IMP_LE];
REWRITE_TAC[IN_SEGMENT; IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN
REWRITE_TAC[GSYM CONJ_ASSOC; RIGHT_EXISTS_AND_THM] THEN
REWRITE_TAC[UNWIND_THM2; DOT_RADD; DOT_RMUL; CONJ_ASSOC] THEN
DISCH_THEN(CHOOSE_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN
MATCH_MP_TAC(REAL_ARITH `a < b ==> a = b ==> F`) THEN
MATCH_MP_TAC REAL_CONVEX_BOUND_LT THEN ASM_REAL_ARITH_TAC];
MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[MATCH_MP_TAC HULL_MONO THEN REWRITE_TAC[SUBSET_INTER] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[];
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
REWRITE_TAC[SUBSET_INTER] THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE]]];
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPEAT LET_TAC THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN CONJ_TAC THENL
[ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`convex hull (s INTER {x:real^3 | a dot x = b}) =
(convex hull s) INTER {x | a dot x = b}`
SUBST1_TAC THENL
[MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[SIMP_TAC[SUBSET_INTER; HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE];
ALL_TAC] THEN
ASM_CASES_TAC `s SUBSET {x:real^3 | a dot x = b}` THENL
[ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`] THEN SET_TAC[];
ALL_TAC] THEN
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC
`convex hull (convex hull (s INTER {x:real^3 | a dot x = b}) UNION
convex hull (s DIFF {x | a dot x = b})) INTER
{x | a dot x = b}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC(SET_RULE
`s SUBSET t ==> (s INTER u) SUBSET (t INTER u)`) THEN
MATCH_MP_TAC HULL_MONO THEN MATCH_MP_TAC(SET_RULE
`s INTER t SUBSET (P hull (s INTER t)) /\
s DIFF t SUBSET (P hull (s DIFF t))
==> s SUBSET (P hull (s INTER t)) UNION (P hull (s DIFF t))`) THEN
REWRITE_TAC[HULL_SUBSET];
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhs o rand) CONVEX_HULL_UNION_NONEMPTY_EXPLICIT o
lhand o lhand o snd) THEN
ANTS_TAC THENL
[SIMP_TAC[CONVEX_CONVEX_HULL; CONVEX_HULL_EQ_EMPTY] THEN ASM SET_TAC[];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[SUBSET; IN_INTER; IMP_CONJ; FORALL_IN_GSPEC] THEN
MAP_EVERY X_GEN_TAC [`p:real^3`; `u:real`; `q:real^3`] THEN
REPLICATE_TAC 4 DISCH_TAC THEN ASM_CASES_TAC `u = &0` THEN
ASM_REWRITE_TAC[VECTOR_ARITH `(&1 - &0) % p + &0 % q:real^N = p`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN REWRITE_TAC[IN_ELIM_THM] THEN
REWRITE_TAC[DOT_RADD; DOT_RMUL] THEN FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC(REAL_ARITH `x < y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * q < u * b
==> (&1 - u) * p + u * q < b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q < b <=> q IN {x | a dot x < b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LT] THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; REAL_LT_LE]];
MATCH_MP_TAC(REAL_ARITH `x > y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * b < u * q
==> (&1 - u) * p + u * q > b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; REWRITE_TAC[GSYM real_gt]] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q > b <=> q IN {x | a dot x > b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GT] THEN
RULE_ASSUM_TAC(REWRITE_RULE[real_ge]) THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; real_gt; REAL_LT_LE]]];
ALL_TAC] THEN
FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_LE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_GE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM]];
REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC `aff_dim {x:real^3 | a dot x = b}` THEN CONJ_TAC THENL
[MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
ASM_SIMP_TAC[AFF_DIM_HYPERPLANE; DIMINDEX_3] THEN INT_ARITH_TAC];
MATCH_MP_TAC INT_LE_TRANS THEN EXISTS_TAC `aff_dim {x:real^3,y,z}` THEN
CONJ_TAC THENL
[SUBGOAL_THEN `~collinear{x:real^3,y,z}` MP_TAC THENL
[ONCE_REWRITE_TAC[SET_RULE `{x,y,z} = {z,x,y}`] THEN
ONCE_REWRITE_TAC[COLLINEAR_3] THEN
ASM_REWRITE_TAC[GSYM CROSS_EQ_0];
REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT; DE_MORGAN_THM] THEN
STRIP_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INDEPENDENT] THEN
SIMP_TAC[CARD_CLAUSES; FINITE_INSERT; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; ARITH] THEN
CONV_TAC INT_REDUCE_CONV;
MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM_REWRITE_TAC[INSERT_SUBSET] THEN
REWRITE_TAC[EMPTY_SUBSET] THEN REPEAT CONJ_TAC THEN
MATCH_MP_TAC HULL_INC THEN
ASM_REWRITE_TAC[IN_INTER; IN_ELIM_THM] THEN
MAP_EVERY UNDISCH_TAC
[`(z - x) cross (y - x) = a`; `(a:real^3) dot x = b`] THEN
VEC3_TAC]]]]);;
let COMPUTE_FACES_2_STEP_1 = prove
(`!f v s t:real^3->bool.
(?x y z. x IN (v INSERT s) /\ y IN (v INSERT s) /\ z IN (v INSERT s) /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) <=>
(?y z. y IN s /\ z IN s /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) \/
(?x y z. x IN s /\ y IN s /\ z IN s /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN REWRITE_TAC[IN_INSERT] THEN MATCH_MP_TAC(MESON[]
`(!x y z. Q x y z ==> Q x z y) /\
(!x y z. Q x y z ==> Q y x z) /\
(!x z. ~(Q x x z))
==> ((?x y z. (x = v \/ P x) /\ (y = v \/ P y) /\ (z = v \/ P z) /\
Q x y z) <=>
(?y z. P y /\ P z /\ Q v y z) \/
(?x y z. P x /\ P y /\ P z /\ Q x y z))`) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[VECTOR_SUB_REFL; CROSS_0] THEN
CONJ_TAC THEN REPEAT GEN_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
MAP_EVERY (SUBST1_TAC o VEC3_RULE)
[`(z - y) cross (x - y) = --((z - x) cross (y - x))`;
`(y - x) cross (z - x) = --((z - x) cross (y - x))`] THEN
REWRITE_TAC[VECTOR_NEG_EQ_0; DOT_LNEG; REAL_EQ_NEG2; REAL_LE_NEG2;
real_ge] THEN
REWRITE_TAC[DISJ_ACI] THEN
REWRITE_TAC[VEC3_RULE
`((z - x) cross (y - x)) dot y = ((z - x) cross (y - x)) dot x`]);;
let COMPUTE_FACES_2_STEP_2 = prove
(`!f u v s:real^3->bool.
(?y z. y IN (u INSERT s) /\ z IN (u INSERT s) /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) <=>
(?z. z IN s /\
let a = (z - v) cross (u - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) \/
(?y z. y IN s /\ z IN s /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN REWRITE_TAC[IN_INSERT] THEN MATCH_MP_TAC(MESON[]
`(!x y. Q x y ==> Q y x) /\
(!x. ~(Q x x))
==> ((?y z. (y = u \/ P y) /\ (z = u \/ P z) /\
Q y z) <=>
(?z. P z /\ Q u z) \/
(?y z. P y /\ P z /\ Q y z))`) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[CROSS_REFL] THEN REPEAT GEN_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN SUBST1_TAC
(VEC3_RULE `(x - v) cross (y - v) = --((y - v) cross (x - v))`) THEN
REWRITE_TAC[VECTOR_NEG_EQ_0; DOT_LNEG; REAL_EQ_NEG2; REAL_LE_NEG2;
real_ge] THEN REWRITE_TAC[DISJ_ACI]);;
let COMPUTE_FACES_TAC =
let lemma = prove
(`(x INSERT s) INTER {x | P x} =
if P x then x INSERT (s INTER {x | P x})
else s INTER {x | P x}`,
COND_CASES_TAC THEN ASM SET_TAC[]) in
SIMP_TAC[COMPUTE_FACES_2; FINITE_INSERT; FINITE_EMPTY] THEN
REWRITE_TAC[COMPUTE_FACES_2_STEP_1] THEN
REWRITE_TAC[COMPUTE_FACES_2_STEP_2] THEN
REWRITE_TAC[NOT_IN_EMPTY] THEN
REWRITE_TAC[EXISTS_IN_INSERT; NOT_IN_EMPTY] THEN
REWRITE_TAC[FORALL_IN_INSERT; NOT_IN_EMPTY] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_CROSS_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[real_ge] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_LE_CONV) THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI] THEN
REPEAT(CHANGED_TAC
(ONCE_REWRITE_TAC[lemma] THEN
CONV_TAC(ONCE_DEPTH_CONV
(LAND_CONV VECTOR3_DOT_CONV THENC REAL_RAT5_EQ_CONV))) THEN
REWRITE_TAC[]) THEN
REWRITE_TAC[INTER_EMPTY] THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI];;
(* ------------------------------------------------------------------------- *)
Apply this to our standard Platonic solids to derive facets .
Note : this is quite slow and can take a couple of hours .
(* ------------------------------------------------------------------------- *)
let TETRAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_tetrahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1], vector[&1; &1; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_tetrahedron] THEN COMPUTE_FACES_TAC);;
let CUBE_FACETS = time prove
(`!f:real^3->bool.
f face_of std_cube /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1], vector[&1; &1; -- &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; &1], vector[&1; -- &1; &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; &1; -- &1], vector[-- &1; &1; &1], vector[&1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[&1; -- &1; -- &1], vector[&1; -- &1; &1], vector[&1; &1; -- &1], vector[&1; &1; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_cube] THEN COMPUTE_FACES_TAC);;
let OCTAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_octahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; &1; &0], vector[&0; &0; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_octahedron] THEN COMPUTE_FACES_TAC);;
let ICOSAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_icosahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]}`,
GEN_TAC THEN REWRITE_TAC[STD_ICOSAHEDRON] THEN COMPUTE_FACES_TAC);;
let DODECAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_dodecahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1; -- &1; &1], vector[-- &1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; -- &1], vector[&1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; &1], vector[&1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; -- &1], vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; &1], vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1; -- &1; &1], vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; -- &1; -- &1], vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]}`,
GEN_TAC THEN REWRITE_TAC[STD_DODECAHEDRON] THEN COMPUTE_FACES_TAC);;
(* ------------------------------------------------------------------------- *)
(* Given a coplanar set, return a hyperplane containing it. *)
Maps term s to theorem |- ! IN s = = > n dot x = d
Currently assumes |s| > = 3 but it would be trivial to do other cases .
(* ------------------------------------------------------------------------- *)
let COPLANAR_HYPERPLANE_RULE =
let rec allsets m l =
if m = 0 then [[]] else
match l with
[] -> []
| h::t -> map (fun g -> h::g) (allsets (m - 1) t) @ allsets m t in
let mk_sub = mk_binop `(-):real^3->real^3->real^3`
and mk_cross = mk_binop `cross`
and mk_dot = mk_binop `(dot):real^3->real^3->real`
and zerovec_tm = `vector[&0;&0;&0]:real^3`
and template = `(!x:real^3. x IN s ==> n dot x = d)`
and s_tm = `s:real^3->bool`
and n_tm = `n:real^3`
and d_tm = `d:real` in
let mk_normal [x;y;z] = mk_cross (mk_sub y x) (mk_sub z x) in
let eval_normal t =
(BINOP_CONV VECTOR3_SUB_CONV THENC VECTOR3_CROSS_CONV) (mk_normal t) in
let check_normal t =
let th = eval_normal t in
let n = rand(concl th) in
if n = zerovec_tm then failwith "check_normal" else n in
fun tm ->
let s = dest_setenum tm in
if length s < 3 then failwith "COPLANAR_HYPERPLANE_RULE: trivial" else
let n = tryfind check_normal (allsets 3 s) in
let d = rand(concl(VECTOR3_DOT_CONV(mk_dot n (hd s)))) in
let ptm = vsubst [tm,s_tm; n,n_tm; d,d_tm] template in
EQT_ELIM
((REWRITE_CONV[FORALL_IN_INSERT; NOT_IN_EMPTY] THENC
DEPTH_BINOP_CONV `/\`
(LAND_CONV VECTOR3_DOT_CONV THENC REAL_RAT5_EQ_CONV) THENC
GEN_REWRITE_CONV DEPTH_CONV [AND_CLAUSES]) ptm);;
(* ------------------------------------------------------------------------- *)
(* Explicit computation of edges, assuming hyperplane containing the set. *)
(* ------------------------------------------------------------------------- *)
let COMPUTE_FACES_1 = prove
(`!s:real^3->bool n d.
(!x. x IN s ==> n dot x = d)
==> FINITE s /\ ~(n = vec 0)
==> !f. f face_of (convex hull s) /\ aff_dim f = &1 <=>
?x y. x IN s /\ y IN s /\
let a = n cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN s ==> a dot w <= b) \/
(!w. w IN s ==> a dot w >= b)) /\
f = convex hull (s INTER {x | a dot x = b})`,
REPEAT GEN_TAC THEN STRIP_TAC THEN STRIP_TAC THEN GEN_TAC THEN EQ_TAC THENL
[STRIP_TAC THEN
SUBGOAL_THEN `?t:real^3->bool. t SUBSET s /\ f = convex hull t`
MP_TAC THENL
[MATCH_MP_TAC FACE_OF_CONVEX_HULL_SUBSET THEN
ASM_SIMP_TAC[FINITE_IMP_COMPACT];
DISCH_THEN(X_CHOOSE_THEN `t:real^3->bool` MP_TAC)] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_CONVEX_HULL]) THEN
MP_TAC(ISPEC `t:real^3->bool` AFFINE_BASIS_EXISTS) THEN
DISCH_THEN(X_CHOOSE_THEN `u:real^3->bool` STRIP_ASSUME_TAC) THEN
SUBGOAL_THEN `(u:real^3->bool) HAS_SIZE 2` MP_TAC THENL
[ASM_SIMP_TAC[HAS_SIZE; AFFINE_INDEPENDENT_IMP_FINITE] THEN
REWRITE_TAC[GSYM INT_OF_NUM_EQ] THEN MATCH_MP_TAC(INT_ARITH
`aff_dim(u:real^3->bool) = &1 /\ aff_dim u = &(CARD u) - &1
==> &(CARD u):int = &2`) THEN CONJ_TAC
THENL [ASM_MESON_TAC[AFF_DIM_AFFINE_HULL]; ASM_MESON_TAC[AFF_DIM_UNIQUE]];
ALL_TAC] THEN
CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN SIMP_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
MAP_EVERY EXISTS_TAC [`x:real^3`; `y:real^3`] THEN
REPLICATE_TAC 2 (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN
SUBGOAL_THEN `(x:real^3) IN s /\ y IN s` STRIP_ASSUME_TAC THENL
[ASM SET_TAC[]; ALL_TAC] THEN
REPEAT LET_TAC THEN
MP_TAC(ISPECL [`n:real^3`; `y - x:real^3`] NORM_AND_CROSS_EQ_0) THEN
ASM_SIMP_TAC[DOT_RSUB; VECTOR_SUB_EQ; REAL_SUB_0] THEN DISCH_TAC THEN
SUBGOAL_THEN `(a:real^3) dot y = b` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC
[`n cross (y - x) = a`; `(a:real^3) dot x = b`] THEN VEC3_TAC;
ALL_TAC] THEN
MP_TAC(ISPECL [`convex hull s:real^3->bool`; `convex hull t:real^3->bool`]
EXPOSED_FACE_OF_POLYHEDRON) THEN
ASM_SIMP_TAC[POLYHEDRON_CONVEX_HULL; EXPOSED_FACE_OF_PARALLEL] THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`a':real^3`; `b':real`] THEN
SUBGOAL_THEN `~(convex hull t:real^3->bool = {})` ASSUME_TAC THENL
[REWRITE_TAC[GSYM MEMBER_NOT_EMPTY] THEN EXISTS_TAC `x:real^3` THEN
MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[];
ASM_REWRITE_TAC[]] THEN
ASM_CASES_TAC `convex hull t:real^3->bool = convex hull s` THEN
ASM_REWRITE_TAC[] THENL
[FIRST_X_ASSUM(ASSUME_TAC o GEN_REWRITE_RULE RAND_CONV
[GSYM AFFINE_HULL_CONVEX_HULL]) THEN
UNDISCH_THEN `convex hull t:real^3->bool = convex hull s`
(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFFINE_HULL_CONVEX_HULL]) THEN
REWRITE_TAC[SET_RULE `s = s INTER t <=> s SUBSET t`] THEN STRIP_TAC THEN
SUBGOAL_THEN `s SUBSET {x:real^3 | a dot x = b}` ASSUME_TAC THENL
[MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `affine hull s:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM SET_TAC[];
CONJ_TAC THENL
[RULE_ASSUM_TAC(REWRITE_RULE[SUBSET; IN_ELIM_THM]) THEN
ASM_SIMP_TAC[real_ge; REAL_LE_REFL];
AP_TERM_TAC THEN ASM SET_TAC[]]];
STRIP_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFFINE_HULL_CONVEX_HULL]) THEN
SUBGOAL_THEN
`aff_dim(t:real^3->bool)
<= aff_dim(({x:real^3 | a dot x = b} INTER {x:real^3 | a' dot x = b'})
INTER {x | n dot x = d})`
MP_TAC THENL
[GEN_REWRITE_TAC LAND_CONV [GSYM AFF_DIM_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (LAND_CONV o RAND_CONV)
[SYM th]) THEN
REWRITE_TAC[AFF_DIM_AFFINE_HULL] THEN MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[SUBSET_INTER; INSERT_SUBSET; EMPTY_SUBSET; IN_ELIM_THM] THEN
ASM_SIMP_TAC[] THEN
SUBGOAL_THEN `(x:real^3) IN convex hull t /\ y IN convex hull t`
MP_TAC THENL
[CONJ_TAC THEN MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[];
ASM SET_TAC[]];
ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFF_DIM_HYPERPLANE;
AFFINE_HYPERPLANE; DIMINDEX_3; AFFINE_INTER] THEN
ASM_CASES_TAC `{x:real^3 | a dot x = b} SUBSET {v | a' dot v = b'}` THEN
ASM_REWRITE_TAC[] THENL
[ALL_TAC;
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (SET_RULE
`s INTER t SUBSET u ==> !x. x IN s /\ x IN t ==> x IN u`)) THEN
DISCH_THEN(MP_TAC o SPEC `x + n:real^3`) THEN
MATCH_MP_TAC(TAUT `p /\ q /\ ~r ==> (p /\ q ==> r) ==> s`) THEN
ASM_SIMP_TAC[IN_ELIM_THM; DOT_RADD] THEN REPEAT CONJ_TAC THENL
[EXPAND_TAC "a" THEN VEC3_TAC;
ALL_TAC;
ASM_REWRITE_TAC[REAL_EQ_ADD_LCANCEL_0; DOT_EQ_0]] THEN
SUBGOAL_THEN `a' dot (x:real^3) = b'` SUBST1_TAC THENL
[SUBGOAL_THEN `(x:real^3) IN convex hull t` MP_TAC THENL
[MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `(n:real^3) dot (x + a') = n dot x` MP_TAC THENL
[ALL_TAC;
SIMP_TAC[DOT_RADD] THEN REWRITE_TAC[DOT_SYM] THEN REAL_ARITH_TAC] THEN
MATCH_MP_TAC(REAL_ARITH `x:real = d /\ y = d ==> x = y`) THEN
SUBGOAL_THEN
`affine hull s SUBSET {x:real^3 | n dot x = d}`
MP_TAC THENL
[MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
REWRITE_TAC[SUBSET; IN_ELIM_THM] THEN ASM_SIMP_TAC[HULL_INC]]] THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [SUBSET_HYPERPLANES]) THEN
ASM_REWRITE_TAC[HYPERPLANE_EQ_EMPTY; HYPERPLANE_EQ_UNIV] THEN
DISCH_THEN(fun th -> DISCH_THEN(K ALL_TAC) THEN MP_TAC(SYM th)) THEN
DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(TAUT `(~p /\ ~q ==> F) ==> p \/ q`) THEN
REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; real_ge; REAL_NOT_LE] THEN
DISCH_THEN(CONJUNCTS_THEN2
(X_CHOOSE_TAC `u:real^3`) (X_CHOOSE_TAC `v:real^3`)) THEN
SUBGOAL_THEN `(a':real^3) dot u < b' /\ a' dot v < b'` ASSUME_TAC THENL
[REWRITE_TAC[REAL_LT_LE] THEN REWRITE_TAC
[SET_RULE `f x <= b /\ ~(f x = b) <=>
x IN {x | f x <= b} /\ ~(x IN {x | f x = b})`] THEN
ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[IN_ELIM_THM; REAL_LT_IMP_NE] THEN
SUBGOAL_THEN `(u:real^3) IN convex hull s /\ v IN convex hull s`
MP_TAC THENL [ASM_SIMP_TAC[HULL_INC]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `?w:real^3. w IN segment[u,v] /\ w IN {w | a' dot w = b'}`
MP_TAC THENL
[ASM_REWRITE_TAC[] THEN REWRITE_TAC[IN_ELIM_THM] THEN
MATCH_MP_TAC CONNECTED_IVT_HYPERPLANE THEN
MAP_EVERY EXISTS_TAC [`v:real^3`; `u:real^3`] THEN
ASM_SIMP_TAC[ENDS_IN_SEGMENT; CONNECTED_SEGMENT; REAL_LT_IMP_LE];
REWRITE_TAC[IN_SEGMENT; IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN
REWRITE_TAC[GSYM CONJ_ASSOC; RIGHT_EXISTS_AND_THM] THEN
REWRITE_TAC[UNWIND_THM2; DOT_RADD; DOT_RMUL; CONJ_ASSOC] THEN
DISCH_THEN(CHOOSE_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN
MATCH_MP_TAC(REAL_ARITH `a < b ==> a = b ==> F`) THEN
MATCH_MP_TAC REAL_CONVEX_BOUND_LT THEN ASM_REAL_ARITH_TAC];
FIRST_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[MATCH_MP_TAC HULL_MONO THEN REWRITE_TAC[SUBSET_INTER] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[];
ASM_REWRITE_TAC[SUBSET_INTER] THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE]]];
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`] THEN
REPEAT LET_TAC THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN CONJ_TAC THENL
[ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`convex hull (s INTER {x:real^3 | a dot x = b}) =
(convex hull s) INTER {x | a dot x = b}`
SUBST1_TAC THENL
[MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[SIMP_TAC[SUBSET_INTER; HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE];
ALL_TAC] THEN
ASM_CASES_TAC `s SUBSET {x:real^3 | a dot x = b}` THENL
[ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`] THEN SET_TAC[];
ALL_TAC] THEN
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC
`convex hull (convex hull (s INTER {x:real^3 | a dot x = b}) UNION
convex hull (s DIFF {x | a dot x = b})) INTER
{x | a dot x = b}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC(SET_RULE
`s SUBSET t ==> (s INTER u) SUBSET (t INTER u)`) THEN
MATCH_MP_TAC HULL_MONO THEN MATCH_MP_TAC(SET_RULE
`s INTER t SUBSET (P hull (s INTER t)) /\
s DIFF t SUBSET (P hull (s DIFF t))
==> s SUBSET (P hull (s INTER t)) UNION (P hull (s DIFF t))`) THEN
REWRITE_TAC[HULL_SUBSET];
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhs o rand) CONVEX_HULL_UNION_NONEMPTY_EXPLICIT o
lhand o lhand o snd) THEN
ANTS_TAC THENL
[SIMP_TAC[CONVEX_CONVEX_HULL; CONVEX_HULL_EQ_EMPTY] THEN ASM SET_TAC[];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[SUBSET; IN_INTER; IMP_CONJ; FORALL_IN_GSPEC] THEN
MAP_EVERY X_GEN_TAC [`p:real^3`; `u:real`; `q:real^3`] THEN
REPLICATE_TAC 4 DISCH_TAC THEN ASM_CASES_TAC `u = &0` THEN
ASM_REWRITE_TAC[VECTOR_ARITH `(&1 - &0) % p + &0 % q:real^N = p`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN REWRITE_TAC[IN_ELIM_THM] THEN
REWRITE_TAC[DOT_RADD; DOT_RMUL] THEN FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC(REAL_ARITH `x < y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * q < u * b
==> (&1 - u) * p + u * q < b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q < b <=> q IN {x | a dot x < b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LT] THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; REAL_LT_LE]];
MATCH_MP_TAC(REAL_ARITH `x > y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * b < u * q
==> (&1 - u) * p + u * q > b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; REWRITE_TAC[GSYM real_gt]] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q > b <=> q IN {x | a dot x > b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GT] THEN
RULE_ASSUM_TAC(REWRITE_RULE[real_ge]) THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; real_gt; REAL_LT_LE]]];
ALL_TAC] THEN
FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_LE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_GE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM]];
ASM_REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[ALL_TAC;
MATCH_MP_TAC INT_LE_TRANS THEN EXISTS_TAC `aff_dim{x:real^3,y}` THEN
CONJ_TAC THENL
[ASM_REWRITE_TAC[AFF_DIM_2] THEN
ASM_MESON_TAC[CROSS_0; VECTOR_SUB_REFL; INT_LE_REFL];
MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[INSERT_SUBSET; EMPTY_SUBSET] THEN
CONJ_TAC THEN MATCH_MP_TAC HULL_INC THEN
ASM_REWRITE_TAC[IN_INTER; IN_ELIM_THM] THEN
MAP_EVERY UNDISCH_TAC
[`n cross (y - x) = a`; `(a:real^3) dot x = b`] THEN
VEC3_TAC]] THEN
REWRITE_TAC[AFF_DIM_CONVEX_HULL] THEN MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC
`aff_dim({x:real^3 | a dot x = b} INTER {x | n dot x = d})` THEN
CONJ_TAC THENL
[MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM SET_TAC[]; ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFFINE_HYPERPLANE;
AFF_DIM_HYPERPLANE; DIMINDEX_3] THEN
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o SPEC `x + n:real^3` o
GEN_REWRITE_RULE I [SUBSET]) THEN
ASM_SIMP_TAC[IN_ELIM_THM; DOT_RADD; REAL_EQ_ADD_LCANCEL_0; DOT_EQ_0] THEN
EXPAND_TAC "a" THEN VEC3_TAC]]);;
(* ------------------------------------------------------------------------- *)
(* Given a coplanar set, return exhaustive edge case theorem. *)
(* ------------------------------------------------------------------------- *)
let COMPUTE_EDGES_CONV =
let lemma = prove
(`(x INSERT s) INTER {x | P x} =
if P x then x INSERT (s INTER {x | P x})
else s INTER {x | P x}`,
COND_CASES_TAC THEN ASM SET_TAC[]) in
fun tm ->
let th1 = MATCH_MP COMPUTE_FACES_1 (COPLANAR_HYPERPLANE_RULE tm) in
let th2 = MP (CONV_RULE(LAND_CONV
(COMB2_CONV (RAND_CONV(PURE_REWRITE_CONV[FINITE_INSERT; FINITE_EMPTY]))
(RAND_CONV VECTOR3_EQ_0_CONV THENC
GEN_REWRITE_CONV I [NOT_CLAUSES]) THENC
GEN_REWRITE_CONV I [AND_CLAUSES])) th1) TRUTH in
CONV_RULE
(BINDER_CONV(RAND_CONV
(REWRITE_CONV[RIGHT_EXISTS_AND_THM] THENC
REWRITE_CONV[EXISTS_IN_INSERT; NOT_IN_EMPTY] THENC
REWRITE_CONV[FORALL_IN_INSERT; NOT_IN_EMPTY] THENC
ONCE_DEPTH_CONV VECTOR3_SUB_CONV THENC
ONCE_DEPTH_CONV VECTOR3_CROSS_CONV THENC
ONCE_DEPTH_CONV let_CONV THENC
ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV THENC
REWRITE_CONV[real_ge] THENC
ONCE_DEPTH_CONV VECTOR3_DOT_CONV THENC
ONCE_DEPTH_CONV let_CONV THENC
ONCE_DEPTH_CONV REAL_RAT5_LE_CONV THENC
REWRITE_CONV[INSERT_AC] THENC REWRITE_CONV[DISJ_ACI] THENC
REPEATC(CHANGED_CONV
(ONCE_REWRITE_CONV[lemma] THENC
ONCE_DEPTH_CONV(LAND_CONV VECTOR3_DOT_CONV THENC
REAL_RAT5_EQ_CONV) THENC
REWRITE_CONV[])) THENC
REWRITE_CONV[INTER_EMPTY] THENC
REWRITE_CONV[INSERT_AC] THENC REWRITE_CONV[DISJ_ACI]
))) th2;;
(* ------------------------------------------------------------------------- *)
Use this to prove the number of edges per face for each Platonic solid .
(* ------------------------------------------------------------------------- *)
let CARD_EQ_LEMMA = prove
(`!x s n. 0 < n /\ ~(x IN s) /\ s HAS_SIZE (n - 1)
==> (x INSERT s) HAS_SIZE n`,
REWRITE_TAC[HAS_SIZE] THEN REPEAT STRIP_TAC THEN
ASM_SIMP_TAC[CARD_CLAUSES; FINITE_INSERT] THEN ASM_ARITH_TAC);;
let EDGES_PER_FACE_TAC th =
REPEAT STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {e:real^3->bool | e face_of f /\ aff_dim(e) = &1}` THEN
CONJ_TAC THENL
[AP_TERM_TAC THEN GEN_REWRITE_TAC I [EXTENSION] THEN
REWRITE_TAC[IN_ELIM_THM] THEN
ASM_MESON_TAC[FACE_OF_FACE; FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
ALL_TAC] THEN
MP_TAC(ISPEC `f:real^3->bool` th) THEN ASM_REWRITE_TAC[] THEN
DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST1_TAC) THEN
W(fun (_,w) -> REWRITE_TAC[COMPUTE_EDGES_CONV(find_term is_setenum w)]) THEN
REWRITE_TAC[SET_RULE `x = a \/ x = b <=> x IN {a,b}`] THEN
REWRITE_TAC[GSYM IN_INSERT; SET_RULE `{x | x IN s} = s`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL] THEN MATCH_MP_TAC
(MESON[HAS_SIZE] `s HAS_SIZE n ==> CARD s = n`) THEN
REPEAT
(MATCH_MP_TAC CARD_EQ_LEMMA THEN REPEAT CONJ_TAC THENL
[CONV_TAC NUM_REDUCE_CONV THEN NO_TAC;
REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; SEGMENT_EQ; DE_MORGAN_THM] THEN
REPEAT CONJ_TAC THEN MATCH_MP_TAC(SET_RULE
`~(a = c /\ b = d) /\ ~(a = d /\ b = c) /\ ~(a = b /\ c = d)
==> ~({a,b} = {c,d})`) THEN
PURE_ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
ALL_TAC]) THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[CONJUNCT1 HAS_SIZE_CLAUSES];;
let TETRAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_tetrahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_tetrahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC TETRAHEDRON_FACETS);;
let CUBE_EDGES_PER_FACE = prove
(`!f. f face_of std_cube /\ aff_dim(f) = &2
==> CARD {e | e face_of std_cube /\ aff_dim(e) = &1 /\
e SUBSET f} = 4`,
EDGES_PER_FACE_TAC CUBE_FACETS);;
let OCTAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_octahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_octahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC OCTAHEDRON_FACETS);;
let DODECAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_dodecahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_dodecahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 5`,
EDGES_PER_FACE_TAC DODECAHEDRON_FACETS);;
let ICOSAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_icosahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_icosahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC ICOSAHEDRON_FACETS);;
(* ------------------------------------------------------------------------- *)
Show that the Platonic solids are all full - dimensional .
(* ------------------------------------------------------------------------- *)
let POLYTOPE_3D_LEMMA = prove
(`(let a = (z - x) cross (y - x) in
~(a = vec 0) /\ ?w. w IN s /\ ~(a dot w = a dot x))
==> aff_dim(convex hull (x INSERT y INSERT z INSERT s:real^3->bool)) = &3`,
REPEAT GEN_TAC THEN LET_TAC THEN STRIP_TAC THEN
REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM DIMINDEX_3; AFF_DIM_LE_UNIV]; ALL_TAC] THEN
REWRITE_TAC[AFF_DIM_CONVEX_HULL] THEN MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC `aff_dim {w:real^3,x,y,z}` THEN CONJ_TAC THENL
[ALL_TAC; MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM SET_TAC[]] THEN
ONCE_REWRITE_TAC[AFF_DIM_INSERT] THEN COND_CASES_TAC THENL
[SUBGOAL_THEN `w IN {w:real^3 | a dot w = a dot x}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
REWRITE_TAC[INSERT_SUBSET; EMPTY_SUBSET; IN_ELIM_THM] THEN
UNDISCH_TAC `~(a:real^3 = vec 0)` THEN EXPAND_TAC "a" THEN VEC3_TAC;
ASM_REWRITE_TAC[IN_ELIM_THM]];
UNDISCH_TAC `~(a:real^3 = vec 0)` THEN EXPAND_TAC "a" THEN
REWRITE_TAC[CROSS_EQ_0; GSYM COLLINEAR_3] THEN
REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT; INSERT_AC; DE_MORGAN_THM] THEN
STRIP_TAC THEN ASM_SIMP_TAC[AFF_DIM_AFFINE_INDEPENDENT] THEN
SIMP_TAC[CARD_CLAUSES; FINITE_INSERT; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; ARITH] THEN INT_ARITH_TAC]);;
let POLYTOPE_FULLDIM_TAC =
MATCH_MP_TAC POLYTOPE_3D_LEMMA THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_CROSS_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN CONJ_TAC THENL
[CONV_TAC(RAND_CONV VECTOR3_EQ_0_CONV) THEN REWRITE_TAC[];
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
REWRITE_TAC[EXISTS_IN_INSERT; NOT_IN_EMPTY] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[]];;
let STD_TETRAHEDRON_FULLDIM = prove
(`aff_dim std_tetrahedron = &3`,
REWRITE_TAC[std_tetrahedron] THEN POLYTOPE_FULLDIM_TAC);;
let STD_CUBE_FULLDIM = prove
(`aff_dim std_cube = &3`,
REWRITE_TAC[std_cube] THEN POLYTOPE_FULLDIM_TAC);;
let STD_OCTAHEDRON_FULLDIM = prove
(`aff_dim std_octahedron = &3`,
REWRITE_TAC[std_octahedron] THEN POLYTOPE_FULLDIM_TAC);;
let STD_DODECAHEDRON_FULLDIM = prove
(`aff_dim std_dodecahedron = &3`,
REWRITE_TAC[STD_DODECAHEDRON] THEN POLYTOPE_FULLDIM_TAC);;
let STD_ICOSAHEDRON_FULLDIM = prove
(`aff_dim std_icosahedron = &3`,
REWRITE_TAC[STD_ICOSAHEDRON] THEN POLYTOPE_FULLDIM_TAC);;
(* ------------------------------------------------------------------------- *)
Complete list of edges for each Platonic solid .
(* ------------------------------------------------------------------------- *)
let COMPUTE_EDGES_TAC defn fulldim facets =
GEN_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`?f:real^3->bool. (f face_of p /\ aff_dim f = &2) /\
(e face_of f /\ aff_dim e = &1)`) THEN
CONJ_TAC THENL
[EQ_TAC THENL [STRIP_TAC; MESON_TAC[FACE_OF_TRANS]] THEN
MP_TAC(ISPECL [lhs(concl defn); `e:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
CONJ_TAC THEN
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
MATCH_MP_TAC MONO_EXISTS THEN REWRITE_TAC[facet_of] THEN
REWRITE_TAC[fulldim] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_MESON_TAC[FACE_OF_FACE]];
REWRITE_TAC[facets] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
CONV_TAC(LAND_CONV(DEPTH_BINOP_CONV `\/`
(fun tm -> REWR_CONV (COMPUTE_EDGES_CONV(rand(rand(lhand tm)))) tm))) THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI]];;
let TETRAHEDRON_EDGES = prove
(`!e. e face_of std_tetrahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; &1; &1]}`,
COMPUTE_EDGES_TAC
std_tetrahedron STD_TETRAHEDRON_FULLDIM TETRAHEDRON_FACETS);;
let CUBE_EDGES = prove
(`!e. e face_of std_cube /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1; &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; &1; -- &1]} \/
e = convex hull {vector[&1; -- &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; &1; -- &1], vector[&1; &1; &1]}`,
COMPUTE_EDGES_TAC
std_cube STD_CUBE_FULLDIM CUBE_FACETS);;
let OCTAHEDRON_EDGES = prove
(`!e. e face_of std_octahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &1; &0]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&0; &1; &0], vector[&0; &0; &1]}`,
COMPUTE_EDGES_TAC
std_octahedron STD_OCTAHEDRON_FULLDIM OCTAHEDRON_FACETS);;
let DODECAHEDRON_EDGES = prove
(`!e. e face_of std_dodecahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[-- &1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[-- &1; -- &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[-- &1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1; -- &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_EDGES_TAC
STD_DODECAHEDRON STD_DODECAHEDRON_FULLDIM DODECAHEDRON_FACETS);;
let ICOSAHEDRON_EDGES = prove
(`!e. e face_of std_icosahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_EDGES_TAC
STD_ICOSAHEDRON STD_ICOSAHEDRON_FULLDIM ICOSAHEDRON_FACETS);;
(* ------------------------------------------------------------------------- *)
(* Enumerate all the vertices. *)
(* ------------------------------------------------------------------------- *)
let COMPUTE_VERTICES_TAC defn fulldim edges =
GEN_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`?e:real^3->bool. (e face_of p /\ aff_dim e = &1) /\
(v face_of e /\ aff_dim v = &0)`) THEN
CONJ_TAC THENL
[EQ_TAC THENL [STRIP_TAC; MESON_TAC[FACE_OF_TRANS]] THEN
MP_TAC(ISPECL [lhs(concl defn); `v:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
CONJ_TAC THEN
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
REWRITE_TAC[facet_of] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^3->bool` STRIP_ASSUME_TAC)] THEN
MP_TAC(ISPECL [`f:real^3->bool`; `v:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[REPEAT CONJ_TAC THENL
[MATCH_MP_TAC FACE_OF_POLYHEDRON_POLYHEDRON THEN
FIRST_ASSUM(fun th ->
EXISTS_TAC (rand(concl th)) THEN
CONJ_TAC THENL [ALL_TAC; ACCEPT_TAC th]) THEN
REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
ASM_MESON_TAC[FACE_OF_FACE];
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV;
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
MATCH_MP_TAC MONO_EXISTS THEN REWRITE_TAC[facet_of] THEN
ASM_REWRITE_TAC[fulldim] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_MESON_TAC[FACE_OF_FACE; FACE_OF_TRANS]];
REWRITE_TAC[edges] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
REWRITE_TAC[AFF_DIM_EQ_0; RIGHT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[MESON[]
`v face_of s /\ v = {a} <=> {a} face_of s /\ v = {a}`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL; FACE_OF_SING] THEN
REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
REWRITE_TAC[DISJ_ACI]];;
let TETRAHEDRON_VERTICES = prove
(`!v. v face_of std_tetrahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1; -- &1; &1]} \/
v = {vector [-- &1; &1; -- &1]} \/
v = {vector [&1; -- &1; -- &1]} \/
v = {vector [&1; &1; &1]}`,
COMPUTE_VERTICES_TAC
std_tetrahedron STD_TETRAHEDRON_FULLDIM TETRAHEDRON_EDGES);;
let CUBE_VERTICES = prove
(`!v. v face_of std_cube /\ aff_dim v = &0 <=>
v = {vector [-- &1; -- &1; -- &1]} \/
v = {vector [-- &1; -- &1; &1]} \/
v = {vector [-- &1; &1; -- &1]} \/
v = {vector [-- &1; &1; &1]} \/
v = {vector [&1; -- &1; -- &1]} \/
v = {vector [&1; -- &1; &1]} \/
v = {vector [&1; &1; -- &1]} \/
v = {vector [&1; &1; &1]}`,
COMPUTE_VERTICES_TAC
std_cube STD_CUBE_FULLDIM CUBE_EDGES);;
let OCTAHEDRON_VERTICES = prove
(`!v. v face_of std_octahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1; &0; &0]} \/
v = {vector [&1; &0; &0]} \/
v = {vector [&0; -- &1; &0]} \/
v = {vector [&0; &1; &0]} \/
v = {vector [&0; &0; -- &1]} \/
v = {vector [&0; &0; &1]}`,
COMPUTE_VERTICES_TAC
std_octahedron STD_OCTAHEDRON_FULLDIM OCTAHEDRON_EDGES);;
let DODECAHEDRON_VERTICES = prove
(`!v. v face_of std_dodecahedron /\ aff_dim v = &0 <=>
v = {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1; -- &1; -- &1]} \/
v = {vector[-- &1; -- &1; &1]} \/
v = {vector[-- &1; &1; -- &1]} \/
v = {vector[-- &1; &1; &1]} \/
v = {vector[&1; -- &1; -- &1]} \/
v = {vector[&1; -- &1; &1]} \/
v = {vector[&1; &1; -- &1]} \/
v = {vector[&1; &1; &1]} \/
v = {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_VERTICES_TAC
STD_DODECAHEDRON STD_DODECAHEDRON_FULLDIM DODECAHEDRON_EDGES);;
let ICOSAHEDRON_VERTICES = prove
(`!v. v face_of std_icosahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1]} \/
v = {vector [-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1]} \/
v = {vector [&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1]} \/
v = {vector [&1 / &2 + &1 / &2 * sqrt (&5); &0; &1]} \/
v = {vector [-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector [-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_VERTICES_TAC
STD_ICOSAHEDRON STD_ICOSAHEDRON_FULLDIM ICOSAHEDRON_EDGES);;
(* ------------------------------------------------------------------------- *)
(* Number of edges meeting at each vertex. *)
(* ------------------------------------------------------------------------- *)
let EDGES_PER_VERTEX_TAC defn edges verts =
REPEAT STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`CARD {e | (e face_of p /\ aff_dim(e) = &1) /\
(v:real^3->bool) face_of e}`) THEN
CONJ_TAC THENL
[AP_TERM_TAC THEN REWRITE_TAC[EXTENSION; IN_ELIM_THM] THEN
ASM_MESON_TAC[FACE_OF_FACE];
ALL_TAC] THEN
MP_TAC(ISPEC `v:real^3->bool` verts) THEN
ASM_REWRITE_TAC[] THEN
DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST1_TAC) THEN
REWRITE_TAC[edges] THEN
REWRITE_TAC[SET_RULE
`{e | (P e \/ Q e) /\ R e} =
{e | P e /\ R e} UNION {e | Q e /\ R e}`] THEN
REWRITE_TAC[MESON[FACE_OF_SING]
`e = a /\ {x} face_of e <=> e = a /\ x extreme_point_of a`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL; EXTREME_POINT_OF_SEGMENT] THEN
ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[EMPTY_GSPEC; UNION_EMPTY] THEN
REWRITE_TAC[SET_RULE `{x | x = a} = {a}`] THEN
REWRITE_TAC[SET_RULE `{x} UNION s = x INSERT s`] THEN MATCH_MP_TAC
(MESON[HAS_SIZE] `s HAS_SIZE n ==> CARD s = n`) THEN
REPEAT
(MATCH_MP_TAC CARD_EQ_LEMMA THEN REPEAT CONJ_TAC THENL
[CONV_TAC NUM_REDUCE_CONV THEN NO_TAC;
REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; DE_MORGAN_THM; SEGMENT_EQ] THEN
REPEAT CONJ_TAC THEN MATCH_MP_TAC(SET_RULE
`~(a = c /\ b = d) /\ ~(a = d /\ b = c) /\ ~(a = b /\ c = d)
==> ~({a,b} = {c,d})`) THEN
PURE_ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
ALL_TAC]) THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[CONJUNCT1 HAS_SIZE_CLAUSES];;
let TETRAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_tetrahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_tetrahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
std_tetrahedron TETRAHEDRON_EDGES TETRAHEDRON_VERTICES);;
let CUBE_EDGES_PER_VERTEX = prove
(`!v. v face_of std_cube /\ aff_dim(v) = &0
==> CARD {e | e face_of std_cube /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
std_cube CUBE_EDGES CUBE_VERTICES);;
let OCTAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_octahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_octahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 4`,
EDGES_PER_VERTEX_TAC
std_octahedron OCTAHEDRON_EDGES OCTAHEDRON_VERTICES);;
let DODECAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_dodecahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_dodecahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
STD_DODECAHEDRON DODECAHEDRON_EDGES DODECAHEDRON_VERTICES);;
let ICOSAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_icosahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_icosahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 5`,
EDGES_PER_VERTEX_TAC
STD_ICOSAHEDRON ICOSAHEDRON_EDGES ICOSAHEDRON_VERTICES);;
(* ------------------------------------------------------------------------- *)
Number of Platonic solids .
(* ------------------------------------------------------------------------- *)
let MULTIPLE_COUNTING_LEMMA = prove
(`!R:A->B->bool s t.
FINITE s /\ FINITE t /\
(!x. x IN s ==> CARD {y | y IN t /\ R x y} = m) /\
(!y. y IN t ==> CARD {x | x IN s /\ R x y} = n)
==> m * CARD s = n * CARD t`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPECL [`R:A->B->bool`; `\x:A y:B. 1`; `s:A->bool`; `t:B->bool`]
NSUM_NSUM_RESTRICT) THEN
ASM_SIMP_TAC[NSUM_CONST; FINITE_RESTRICT] THEN ARITH_TAC);;
let SIZE_ZERO_DIMENSIONAL_FACES = prove
(`!s:real^N->bool.
polyhedron s
==> CARD {f | f face_of s /\ aff_dim f = &0} =
CARD {v | v extreme_point_of s} /\
(FINITE {f | f face_of s /\ aff_dim f = &0} <=>
FINITE {v | v extreme_point_of s}) /\
(!n. {f | f face_of s /\ aff_dim f = &0} HAS_SIZE n <=>
{v | v extreme_point_of s} HAS_SIZE n)`,
REWRITE_TAC[RIGHT_AND_FORALL_THM] THEN REPEAT GEN_TAC THEN DISCH_TAC THEN
SUBGOAL_THEN `{f | f face_of s /\ aff_dim f = &0} =
IMAGE (\v:real^N. {v}) {v | v extreme_point_of s}`
SUBST1_TAC THENL
[CONV_TAC SYM_CONV THEN MATCH_MP_TAC SURJECTIVE_IMAGE_EQ THEN
REWRITE_TAC[AFF_DIM_SING; FACE_OF_SING; IN_ELIM_THM] THEN
REWRITE_TAC[AFF_DIM_EQ_0] THEN MESON_TAC[];
REPEAT STRIP_TAC THENL
[MATCH_MP_TAC CARD_IMAGE_INJ;
MATCH_MP_TAC FINITE_IMAGE_INJ_EQ;
MATCH_MP_TAC HAS_SIZE_IMAGE_INJ_EQ] THEN
ASM_SIMP_TAC[FINITE_POLYHEDRON_EXTREME_POINTS] THEN SET_TAC[]]);;
let PLATONIC_SOLIDS_LIMITS = prove
(`!p:real^3->bool m n.
polytope p /\ aff_dim p = &3 /\
(!f. f face_of p /\ aff_dim(f) = &2
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ e SUBSET f} = m) /\
(!v. v face_of p /\ aff_dim(v) = &0
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ v SUBSET e} = n)
==> m = 3 /\ n = 3 \/ // Tetrahedron
m = 4 /\ n = 3 \/ // Cube
m = 3 /\ n = 4 \/ // Octahedron
m = 5 /\ n = 3 \/ // Dodecahedron
m = 3 /\ n = 5 // Icosahedron`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPEC `p:real^3->bool` EULER_RELATION) THEN
ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`m * CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2} =
2 * CARD {e | e face_of p /\ aff_dim e = &1} /\
n * CARD {v | v face_of p /\ aff_dim v = &0} =
2 * CARD {e | e face_of p /\ aff_dim e = &1}`
MP_TAC THENL
[CONJ_TAC THEN MATCH_MP_TAC MULTIPLE_COUNTING_LEMMA THENL
[EXISTS_TAC `\(f:real^3->bool) (e:real^3->bool). e SUBSET f`;
EXISTS_TAC `\(v:real^3->bool) (e:real^3->bool). v SUBSET e`] THEN
ONCE_REWRITE_TAC[SET_RULE `f face_of s <=> f IN {f | f face_of s}`] THEN
ASM_SIMP_TAC[FINITE_POLYTOPE_FACES; FINITE_RESTRICT] THEN
ASM_REWRITE_TAC[IN_ELIM_THM; GSYM CONJ_ASSOC] THEN
X_GEN_TAC `e:real^3->bool` THEN STRIP_TAC THENL
[MP_TAC(ISPECL [`p:real^3->bool`; `e:real^3->bool`]
POLYHEDRON_RIDGE_TWO_FACETS) THEN
ASM_SIMP_TAC[POLYTOPE_IMP_POLYHEDRON] THEN ANTS_TAC THENL
[CONV_TAC INT_REDUCE_CONV THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_EMPTY]) THEN ASM_INT_ARITH_TAC;
CONV_TAC INT_REDUCE_CONV THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`f1:real^3->bool`; `f2:real^3->bool`] THEN
STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {f1:real^3->bool,f2}` THEN CONJ_TAC THENL
[AP_TERM_TAC THEN GEN_REWRITE_TAC I [EXTENSION] THEN
REWRITE_TAC[IN_ELIM_THM; IN_INSERT; NOT_IN_EMPTY] THEN
ASM_MESON_TAC[];
ASM_SIMP_TAC[CARD_CLAUSES; IN_INSERT; FINITE_RULES;
NOT_IN_EMPTY; ARITH]]];
SUBGOAL_THEN `?a b:real^3. e = segment[a,b]` STRIP_ASSUME_TAC THENL
[MATCH_MP_TAC COMPACT_CONVEX_COLLINEAR_SEGMENT THEN
REPEAT CONJ_TAC THENL
[DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_EMPTY]) THEN ASM_INT_ARITH_TAC;
MATCH_MP_TAC FACE_OF_IMP_COMPACT THEN
EXISTS_TAC `p:real^3->bool` THEN
ASM_SIMP_TAC[POLYTOPE_IMP_CONVEX; POLYTOPE_IMP_COMPACT];
ASM_MESON_TAC[FACE_OF_IMP_CONVEX];
MP_TAC(ISPEC `e:real^3->bool` AFF_DIM) THEN
DISCH_THEN(X_CHOOSE_THEN `b:real^3->bool` MP_TAC) THEN
ASM_REWRITE_TAC[INT_ARITH `&1:int = b - &1 <=> b = &2`] THEN
DISCH_THEN(CONJUNCTS_THEN2 (ASSUME_TAC o SYM) MP_TAC) THEN
ASM_CASES_TAC `FINITE(b:real^3->bool)` THENL
[ALL_TAC; ASM_MESON_TAC[AFFINE_INDEPENDENT_IMP_FINITE]] THEN
REWRITE_TAC[INT_OF_NUM_EQ] THEN STRIP_TAC THEN
SUBGOAL_THEN `(b:real^3->bool) HAS_SIZE 2` MP_TAC THENL
[ASM_REWRITE_TAC[HAS_SIZE]; CONV_TAC(LAND_CONV HAS_SIZE_CONV)] THEN
REWRITE_TAC[COLLINEAR_AFFINE_HULL] THEN
REPEAT(MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC) THEN
ASM_MESON_TAC[HULL_SUBSET]];
ASM_CASES_TAC `a:real^3 = b` THENL
[UNDISCH_TAC `aff_dim(e:real^3->bool) = &1` THEN
ASM_REWRITE_TAC[SEGMENT_REFL; AFF_DIM_SING; INT_OF_NUM_EQ; ARITH_EQ];
ALL_TAC] THEN
MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {v:real^3 | v extreme_point_of segment[a,b]}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC CARD_IMAGE_INJ_EQ THEN
EXISTS_TAC `\v:real^3. {v}` THEN
REWRITE_TAC[IN_ELIM_THM; FACE_OF_SING; AFF_DIM_SING] THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[SET_RULE `{x | x = a \/ x = b} = {a,b}`] THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
X_GEN_TAC `v:real^3` THEN REWRITE_TAC[GSYM FACE_OF_SING] THEN
ASM_MESON_TAC[FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
X_GEN_TAC `s:real^3->bool` THEN REWRITE_TAC[AFF_DIM_EQ_0] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN
DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN
DISCH_THEN(X_CHOOSE_THEN `v:real^3` SUBST_ALL_TAC) THEN
REWRITE_TAC[EXISTS_UNIQUE] THEN EXISTS_TAC `v:real^3` THEN
ASM_REWRITE_TAC[GSYM FACE_OF_SING] THEN CONJ_TAC THENL
[ASM_MESON_TAC[FACE_OF_FACE]; SET_TAC[]]];
ASM_REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[SET_RULE `{x | x = a \/ x = b} = {a,b}`] THEN
ASM_SIMP_TAC[FINITE_INSERT; CARD_CLAUSES; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_SING; NOT_IN_EMPTY; ARITH]]]];
ALL_TAC] THEN
STRIP_TAC THEN
DISCH_THEN(ASSUME_TAC o MATCH_MP (ARITH_RULE
`(a + b) - c = 2 ==> a + b = c + 2`)) THEN
SUBGOAL_THEN `4 <= CARD {v:real^3->bool | v face_of p /\ aff_dim v = &0}`
ASSUME_TAC THENL
[ASM_SIMP_TAC[SIZE_ZERO_DIMENSIONAL_FACES; POLYTOPE_IMP_POLYHEDRON] THEN
MP_TAC(ISPEC `p:real^3->bool` POLYTOPE_VERTEX_LOWER_BOUND) THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INT_REDUCE_CONV THEN
REWRITE_TAC[INT_OF_NUM_LE];
ALL_TAC] THEN
SUBGOAL_THEN `4 <= CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2}`
ASSUME_TAC THENL
[MP_TAC(ISPEC `p:real^3->bool` POLYTOPE_FACET_LOWER_BOUND) THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_REWRITE_TAC[INT_OF_NUM_LE; facet_of] THEN
MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
GEN_REWRITE_TAC I [EXTENSION] THEN REWRITE_TAC[IN_ELIM_THM] THEN
CONV_TAC INT_REDUCE_CONV THEN GEN_TAC THEN EQ_TAC THEN
STRIP_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_MESON_TAC[INT_ARITH `~(&2:int = -- &1)`; AFF_DIM_EMPTY];
ALL_TAC] THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`v + f = e + 2 ==> 4 <= v /\ 4 <= f ==> 6 <= e`)) THEN
ASM_REWRITE_TAC[] THEN
ASM_CASES_TAC
`CARD {e:real^3->bool | e face_of p /\ aff_dim e = &1} = 0` THEN
ASM_REWRITE_TAC[ARITH] THEN DISCH_TAC THEN
SUBGOAL_THEN `3 <= m` ASSUME_TAC THENL
[ASM_CASES_TAC `{f:real^3->bool | f face_of p /\ aff_dim f = &2} = {}` THENL
[UNDISCH_TAC
`4 <= CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2}` THEN
ASM_REWRITE_TAC[CARD_CLAUSES] THEN ARITH_TAC;
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY])] THEN
REWRITE_TAC[IN_ELIM_THM] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^3->bool` MP_TAC) THEN
DISCH_THEN(fun th -> STRIP_ASSUME_TAC th THEN
FIRST_X_ASSUM(SUBST1_TAC o SYM o C MATCH_MP th)) THEN
MP_TAC(ISPEC `f:real^3->bool` POLYTOPE_FACET_LOWER_BOUND) THEN
ASM_REWRITE_TAC[facet_of] THEN CONV_TAC INT_REDUCE_CONV THEN
ANTS_TAC THENL [ASM_MESON_TAC[FACE_OF_POLYTOPE_POLYTOPE]; ALL_TAC] THEN
REWRITE_TAC[INT_OF_NUM_LE] THEN MATCH_MP_TAC EQ_IMP THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
GEN_REWRITE_TAC I [EXTENSION] THEN REWRITE_TAC[IN_ELIM_THM] THEN
CONV_TAC INT_REDUCE_CONV THEN X_GEN_TAC `e:real^3->bool` THEN
EQ_TAC THEN ASM_CASES_TAC `e:real^3->bool = {}` THEN
ASM_SIMP_TAC[AFF_DIM_EMPTY] THEN CONV_TAC INT_REDUCE_CONV THENL
[ASM_MESON_TAC[FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
ASM_MESON_TAC[FACE_OF_FACE]];
ALL_TAC] THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (ARITH_RULE `3 <= m ==> ~(m = 0)`)) THEN
ASM_CASES_TAC `n = 0` THENL
[UNDISCH_THEN `n = 0` SUBST_ALL_TAC THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`0 * x = 2 * e ==> e = 0`)) THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (NUM_RING
`v + f = e + 2 ==> !m n. m * n * v + n * m * f = m * n * (e + 2)`)) THEN
DISCH_THEN(MP_TAC o SPECL [`m:num`; `n:num`]) THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[ARITH_RULE `m * 2 * e + n * 2 * e = m * n * (e + 2) <=>
e * 2 * (m + n) = m * n * (e + 2)`] THEN
ABBREV_TAC `E = CARD {e:real^3->bool | e face_of p /\ aff_dim e = &1}` THEN
ASM_CASES_TAC `n = 1` THENL
[ASM_REWRITE_TAC[MULT_CLAUSES; ARITH_RULE
`E * 2 * (n + 1) = n * (E + 2) <=> E * (n + 2) = 2 * n`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN
MATCH_MP_TAC(ARITH_RULE `n:num < m ==> ~(m = n)`) THEN
MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `2 * (m + 2)` THEN
CONJ_TAC THENL [ARITH_TAC; MATCH_MP_TAC LE_MULT2 THEN ASM_ARITH_TAC];
ALL_TAC] THEN
ASM_CASES_TAC `n = 2` THENL
[ASM_REWRITE_TAC[ARITH_RULE `E * 2 * (n + 2) = n * 2 * (E + 2) <=>
E = n`] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (NUM_RING
`E * c = 2 * E ==> E = 0 \/ c = 2`)) THEN
ASM_ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `3 <= n` ASSUME_TAC THENL [ASM_ARITH_TAC; ALL_TAC] THEN
ASM_CASES_TAC `m * n < 2 * (m + n)` THENL
[DISCH_TAC;
DISCH_TAC THEN RULE_ASSUM_TAC(REWRITE_RULE[NOT_LT]) THEN
SUBGOAL_THEN `E * 2 * (m + n) <= E * m * n` MP_TAC THENL
[REWRITE_TAC[LE_MULT_LCANCEL] THEN ASM_ARITH_TAC;
ASM_REWRITE_TAC[ARITH_RULE `m * n * (E + 2) <= E * m * n <=>
2 * m * n = 0`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN
REWRITE_TAC[MULT_EQ_0] THEN ASM_ARITH_TAC]] THEN
SUBGOAL_THEN `&m - &2:real < &4 /\ &n - &2 < &4` MP_TAC THENL
[CONJ_TAC THENL
[MATCH_MP_TAC REAL_LT_RCANCEL_IMP THEN EXISTS_TAC `&n - &2`;
MATCH_MP_TAC REAL_LT_LCANCEL_IMP THEN EXISTS_TAC `&m - &2`] THEN
ASM_SIMP_TAC[REAL_SUB_LT; REAL_OF_NUM_LT;
ARITH_RULE `2 < n <=> 3 <= n`] THEN
MATCH_MP_TAC REAL_LTE_TRANS THEN EXISTS_TAC `&4` THEN
REWRITE_TAC[REAL_ARITH `(m - &2) * (n - &2) < &4 <=>
m * n < &2 * (m + n)`] THEN
ASM_REWRITE_TAC[REAL_OF_NUM_MUL; REAL_OF_NUM_ADD; REAL_OF_NUM_LT] THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_SUB_RDISTRIB; REAL_LE_SUB_LADD] THEN
REWRITE_TAC[REAL_OF_NUM_MUL; REAL_OF_NUM_ADD; REAL_OF_NUM_LE] THEN
ASM_ARITH_TAC;
ALL_TAC] THEN
REWRITE_TAC[REAL_LT_SUB_RADD; REAL_OF_NUM_ADD; REAL_OF_NUM_LT] THEN
REWRITE_TAC[ARITH_RULE `m < 4 + 2 <=> m <= 5`] THEN
ASM_SIMP_TAC[ARITH_RULE
`3 <= m ==> (m <= 5 <=> m = 3 \/ m = 4 \/ m = 5)`] THEN
STRIP_TAC THEN UNDISCH_TAC `E * 2 * (m + n) = m * n * (E + 2)` THEN
ASM_REWRITE_TAC[] THEN CONV_TAC NUM_REDUCE_CONV THEN ASM_ARITH_TAC);;
(* ------------------------------------------------------------------------- *)
(* If-and-only-if version. *)
(* ------------------------------------------------------------------------- *)
let PLATONIC_SOLIDS = prove
(`!m n.
(?p:real^3->bool.
polytope p /\ aff_dim p = &3 /\
(!f. f face_of p /\ aff_dim(f) = &2
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ e SUBSET f} = m) /\
(!v. v face_of p /\ aff_dim(v) = &0
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ v SUBSET e} = n)) <=>
m = 3 /\ n = 3 \/ // Tetrahedron
m = 4 /\ n = 3 \/ // Cube
m = 3 /\ n = 4 \/ // Octahedron
m = 5 /\ n = 3 \/ // Dodecahedron
m = 3 /\ n = 5 // Icosahedron`,
REPEAT GEN_TAC THEN EQ_TAC THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM; PLATONIC_SOLIDS_LIMITS] THEN
STRIP_TAC THENL
[EXISTS_TAC `std_tetrahedron` THEN
ASM_REWRITE_TAC[TETRAHEDRON_EDGES_PER_VERTEX; TETRAHEDRON_EDGES_PER_FACE;
STD_TETRAHEDRON_FULLDIM] THEN
REWRITE_TAC[std_tetrahedron] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_cube` THEN
ASM_REWRITE_TAC[CUBE_EDGES_PER_VERTEX; CUBE_EDGES_PER_FACE;
STD_CUBE_FULLDIM] THEN
REWRITE_TAC[std_cube] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_octahedron` THEN
ASM_REWRITE_TAC[OCTAHEDRON_EDGES_PER_VERTEX; OCTAHEDRON_EDGES_PER_FACE;
STD_OCTAHEDRON_FULLDIM] THEN
REWRITE_TAC[std_octahedron] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_dodecahedron` THEN
ASM_REWRITE_TAC[DODECAHEDRON_EDGES_PER_VERTEX; DODECAHEDRON_EDGES_PER_FACE;
STD_DODECAHEDRON_FULLDIM] THEN
REWRITE_TAC[STD_DODECAHEDRON] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_icosahedron` THEN
ASM_REWRITE_TAC[ICOSAHEDRON_EDGES_PER_VERTEX; ICOSAHEDRON_EDGES_PER_FACE;
STD_ICOSAHEDRON_FULLDIM] THEN
REWRITE_TAC[STD_ICOSAHEDRON] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY]]);;
(* ------------------------------------------------------------------------- *)
(* Show that the regular polyhedra do have all edges and faces congruent. *)
(* ------------------------------------------------------------------------- *)
parse_as_infix("congruent",(12,"right"));;
let congruent = new_definition
`(s:real^N->bool) congruent (t:real^N->bool) <=>
?c f. orthogonal_transformation f /\ t = IMAGE (\x. c + f x) s`;;
let CONGRUENT_SIMPLE = prove
(`(?A:real^3^3. orthogonal_matrix A /\ IMAGE (\x:real^3. A ** x) s = t)
==> (convex hull s) congruent (convex hull t)`,
REPEAT GEN_TAC THEN
DISCH_THEN(CHOOSE_THEN (CONJUNCTS_THEN2 ASSUME_TAC (SUBST1_TAC o SYM))) THEN
SIMP_TAC[CONVEX_HULL_LINEAR_IMAGE; MATRIX_VECTOR_MUL_LINEAR] THEN
REWRITE_TAC[congruent] THEN EXISTS_TAC `vec 0:real^3` THEN
EXISTS_TAC `\x:real^3. (A:real^3^3) ** x` THEN
REWRITE_TAC[VECTOR_ADD_LID; ORTHOGONAL_TRANSFORMATION_MATRIX] THEN
ASM_SIMP_TAC[MATRIX_OF_MATRIX_VECTOR_MUL; MATRIX_VECTOR_MUL_LINEAR]);;
let CONGRUENT_SEGMENTS = prove
(`!a b c d:real^N.
dist(a,b) = dist(c,d)
==> segment[a,b] congruent segment[c,d]`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPECL [`b - a:real^N`; `d - c:real^N`]
ORTHOGONAL_TRANSFORMATION_EXISTS) THEN
ANTS_TAC THENL [POP_ASSUM MP_TAC THEN NORM_ARITH_TAC; ALL_TAC] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^N->real^N` STRIP_ASSUME_TAC) THEN
REWRITE_TAC[congruent] THEN
EXISTS_TAC `c - (f:real^N->real^N) a` THEN
EXISTS_TAC `f:real^N->real^N` THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP ORTHOGONAL_TRANSFORMATION_LINEAR) THEN
SUBGOAL_THEN
`(\x. (c - f a) + (f:real^N->real^N) x) = (\x. (c - f a) + x) o f`
SUBST1_TAC THENL [REWRITE_TAC[FUN_EQ_THM; o_THM]; ALL_TAC] THEN
ASM_SIMP_TAC[GSYM CONVEX_HULL_LINEAR_IMAGE; SEGMENT_CONVEX_HULL; IMAGE_o;
GSYM CONVEX_HULL_TRANSLATION] THEN
REWRITE_TAC[IMAGE_CLAUSES] THEN
AP_TERM_TAC THEN BINOP_TAC THENL
[VECTOR_ARITH_TAC; AP_THM_TAC THEN AP_TERM_TAC] THEN
REWRITE_TAC[VECTOR_ARITH `d:real^N = c - a + b <=> b - a = d - c`] THEN
ASM_MESON_TAC[LINEAR_SUB]);;
let compute_dist =
let mk_sub = mk_binop `(-):real^3->real^3->real^3`
and dot_tm = `(dot):real^3->real^3->real` in
fun v1 v2 -> let vth = VECTOR3_SUB_CONV(mk_sub v1 v2) in
let dth = CONV_RULE(RAND_CONV VECTOR3_DOT_CONV)
(MK_COMB(AP_TERM dot_tm vth,vth)) in
rand(concl dth);;
let le_rat5 =
let mk_le = mk_binop `(<=):real->real->bool` and t_tm = `T` in
fun r1 r2 -> rand(concl(REAL_RAT5_LE_CONV(mk_le r1 r2))) = t_tm;;
let three_adjacent_points s =
match s with
| x::t -> let (y,_)::(z,_)::_ =
sort (fun (_,r1) (_,r2) -> le_rat5 r1 r2)
(map (fun y -> y,compute_dist x y) t) in
x,y,z
| _ -> failwith "three_adjacent_points: no points";;
let mk_33matrix =
let a11_tm = `a11:real`
and a12_tm = `a12:real`
and a13_tm = `a13:real`
and a21_tm = `a21:real`
and a22_tm = `a22:real`
and a23_tm = `a23:real`
and a31_tm = `a31:real`
and a32_tm = `a32:real`
and a33_tm = `a33:real`
and pat_tm =
`vector[vector[a11; a12; a13];
vector[a21; a22; a23];
vector[a31; a32; a33]]:real^3^3` in
fun [a11;a12;a13;a21;a22;a23;a31;a32;a33] ->
vsubst[a11,a11_tm;
a12,a12_tm;
a13,a13_tm;
a21,a21_tm;
a22,a22_tm;
a23,a23_tm;
a31,a31_tm;
a32,a32_tm;
a33,a33_tm] pat_tm;;
let MATRIX_VECTOR_MUL_3 = prove
(`(vector[vector[a11;a12;a13];
vector[a21; a22; a23];
vector[a31; a32; a33]]:real^3^3) **
(vector[x1;x2;x3]:real^3) =
vector[a11 * x1 + a12 * x2 + a13 * x3;
a21 * x1 + a22 * x2 + a23 * x3;
a31 * x1 + a32 * x2 + a33 * x3]`,
SIMP_TAC[CART_EQ; matrix_vector_mul; LAMBDA_BETA] THEN
REWRITE_TAC[DIMINDEX_3; FORALL_3; SUM_3; VECTOR_3]);;
let MATRIX_LEMMA = prove
(`!A:real^3^3.
A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
(vector [x1; y1; z1]:real^3^3) ** (row 1 A:real^3) =
vector [x2$1; y2$1; z2$1] /\
(vector [x1; y1; z1]:real^3^3) ** (row 2 A:real^3) =
vector [x2$2; y2$2; z2$2] /\
(vector [x1; y1; z1]:real^3^3) ** (row 3 A:real^3) =
vector [x2$3; y2$3; z2$3]`,
SIMP_TAC[CART_EQ; transp; matrix_vector_mul; row; VECTOR_3; LAMBDA_BETA] THEN
REWRITE_TAC[FORALL_3; DIMINDEX_3; VECTOR_3; SUM_3] THEN REAL_ARITH_TAC);;
let MATRIX_BY_CRAMER_LEMMA = prove
(`!A:real^3^3.
~(det(vector[x1; y1; z1]:real^3^3) = &0)
==> (A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
A = lambda m k. det((lambda i j.
if j = k
then (vector[x2$m; y2$m; z2$m]:real^3)$i
else (vector[x1; y1; z1]:real^3^3)$i$j)
:real^3^3) /
det(vector[x1;y1;z1]:real^3^3))`,
REPEAT STRIP_TAC THEN GEN_REWRITE_TAC LAND_CONV [MATRIX_LEMMA] THEN
ASM_SIMP_TAC[CRAMER] THEN REWRITE_TAC[CART_EQ; row] THEN
SIMP_TAC[LAMBDA_BETA] THEN REWRITE_TAC[DIMINDEX_3; FORALL_3]);;
let MATRIX_BY_CRAMER = prove
(`!A:real^3^3 x1 y1 z1 x2 y2 z2.
let d = det(vector[x1; y1; z1]:real^3^3) in
~(d = &0)
==> (A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
A$1$1 =
(x2$1 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$1 +
x1$3 * y2$1 * z1$2 -
x2$1 * y1$3 * z1$2 -
x1$2 * y2$1 * z1$3 -
x1$3 * y1$2 * z2$1) / d /\
A$1$2 =
(x1$1 * y2$1 * z1$3 +
x2$1 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$1 -
x1$1 * y1$3 * z2$1 -
x2$1 * y1$1 * z1$3 -
x1$3 * y2$1 * z1$1) / d /\
A$1$3 =
(x1$1 * y1$2 * z2$1 +
x1$2 * y2$1 * z1$1 +
x2$1 * y1$1 * z1$2 -
x1$1 * y2$1 * z1$2 -
x1$2 * y1$1 * z2$1 -
x2$1 * y1$2 * z1$1) / d /\
A$2$1 =
(x2$2 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$2 +
x1$3 * y2$2 * z1$2 -
x2$2 * y1$3 * z1$2 -
x1$2 * y2$2 * z1$3 -
x1$3 * y1$2 * z2$2) / d /\
A$2$2 =
(x1$1 * y2$2 * z1$3 +
x2$2 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$2 -
x1$1 * y1$3 * z2$2 -
x2$2 * y1$1 * z1$3 -
x1$3 * y2$2 * z1$1) / d /\
A$2$3 =
(x1$1 * y1$2 * z2$2 +
x1$2 * y2$2 * z1$1 +
x2$2 * y1$1 * z1$2 -
x1$1 * y2$2 * z1$2 -
x1$2 * y1$1 * z2$2 -
x2$2 * y1$2 * z1$1) / d /\
A$3$1 =
(x2$3 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$3 +
x1$3 * y2$3 * z1$2 -
x2$3 * y1$3 * z1$2 -
x1$2 * y2$3 * z1$3 -
x1$3 * y1$2 * z2$3) / d /\
A$3$2 =
(x1$1 * y2$3 * z1$3 +
x2$3 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$3 -
x1$1 * y1$3 * z2$3 -
x2$3 * y1$1 * z1$3 -
x1$3 * y2$3 * z1$1) / d /\
A$3$3 =
(x1$1 * y1$2 * z2$3 +
x1$2 * y2$3 * z1$1 +
x2$3 * y1$1 * z1$2 -
x1$1 * y2$3 * z1$2 -
x1$2 * y1$1 * z2$3 -
x2$3 * y1$2 * z1$1) / d)`,
REPEAT GEN_TAC THEN CONV_TAC let_CONV THEN DISCH_TAC THEN
ASM_SIMP_TAC[MATRIX_BY_CRAMER_LEMMA] THEN
REWRITE_TAC[DET_3; CART_EQ] THEN
SIMP_TAC[LAMBDA_BETA; DIMINDEX_3; ARITH; VECTOR_3] THEN
REWRITE_TAC[FORALL_3; ARITH; VECTOR_3] THEN REWRITE_TAC[CONJ_ACI]);;
let CONGRUENT_EDGES_TAC edges =
REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM] THEN REWRITE_TAC[IMP_IMP] THEN
REWRITE_TAC[edges] THEN
REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL] THEN
MATCH_MP_TAC CONGRUENT_SEGMENTS THEN REWRITE_TAC[DIST_EQ] THEN
REWRITE_TAC[dist; NORM_POW_2] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[];;
let CONGRUENT_FACES_TAC facets =
REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM] THEN REWRITE_TAC[IMP_IMP] THEN
REWRITE_TAC[facets] THEN
REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[] THEN
W(fun (asl,w) ->
let t1 = rand(lhand w) and t2 = rand(rand w) in
let (x1,y1,z1) = three_adjacent_points (dest_setenum t1)
and (x2,y2,z2) = three_adjacent_points (dest_setenum t2) in
let th1 = SPECL [`A:real^3^3`;x1;y1;z1;x2;y2;z2] MATRIX_BY_CRAMER in
let th2 = REWRITE_RULE[VECTOR_3; DET_3] th1 in
let th3 = CONV_RULE (DEPTH_CONV REAL_RAT5_MUL_CONV) th2 in
let th4 = CONV_RULE (DEPTH_CONV
(REAL_RAT5_ADD_CONV ORELSEC REAL_RAT5_SUB_CONV)) th3 in
let th5 = CONV_RULE let_CONV th4 in
let th6 = CONV_RULE(ONCE_DEPTH_CONV REAL_RAT5_DIV_CONV) th5 in
let th7 = CONV_RULE(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) th6 in
let th8 = MP th7 (EQT_ELIM(REWRITE_CONV[] (lhand(concl th7)))) in
let tms = map rhs (conjuncts(rand(concl th8))) in
let matt = mk_33matrix tms in
MATCH_MP_TAC CONGRUENT_SIMPLE THEN EXISTS_TAC matt THEN CONJ_TAC THENL
[REWRITE_TAC[ORTHOGONAL_MATRIX; CART_EQ] THEN
SIMP_TAC[transp; LAMBDA_BETA; matrix_mul; mat] THEN
REWRITE_TAC[DIMINDEX_3; SUM_3; FORALL_3; VECTOR_3; ARITH] THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_MUL_CONV) THEN
CONV_TAC(DEPTH_CONV REAL_RAT5_ADD_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
REWRITE_TAC[IMAGE_CLAUSES; MATRIX_VECTOR_MUL_3] THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_MUL_CONV) THEN
CONV_TAC(DEPTH_CONV REAL_RAT5_ADD_CONV) THEN
REWRITE_TAC[INSERT_AC]]);;
let TETRAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_tetrahedron /\ aff_dim e1 = &1 /\
e2 face_of std_tetrahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC TETRAHEDRON_EDGES);;
let TETRAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_tetrahedron /\ aff_dim f1 = &2 /\
f2 face_of std_tetrahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC TETRAHEDRON_FACETS);;
let CUBE_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_cube /\ aff_dim e1 = &1 /\
e2 face_of std_cube /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC CUBE_EDGES);;
let CUBE_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_cube /\ aff_dim f1 = &2 /\
f2 face_of std_cube /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC CUBE_FACETS);;
let OCTAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_octahedron /\ aff_dim e1 = &1 /\
e2 face_of std_octahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC OCTAHEDRON_EDGES);;
let OCTAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_octahedron /\ aff_dim f1 = &2 /\
f2 face_of std_octahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC OCTAHEDRON_FACETS);;
let DODECAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_dodecahedron /\ aff_dim e1 = &1 /\
e2 face_of std_dodecahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC DODECAHEDRON_EDGES);;
let DODECAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_dodecahedron /\ aff_dim f1 = &2 /\
f2 face_of std_dodecahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC DODECAHEDRON_FACETS);;
let ICOSAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_icosahedron /\ aff_dim e1 = &1 /\
e2 face_of std_icosahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC ICOSAHEDRON_EDGES);;
let ICOSAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_icosahedron /\ aff_dim f1 = &2 /\
f2 face_of std_icosahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC ICOSAHEDRON_FACETS);;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/100/platonic.ml | ocaml | =========================================================================
=========================================================================
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Slightly ad hoc conversions for computation in Q[sqrt(5)].
Numbers are canonically represented as either a rational constant r or an
must be present.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Conversions for operations on 3D vectors with coordinates in Q[sqrt(5)]
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Put any irrational coordinates in our standard form.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Explicit computation of facets.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Given a coplanar set, return a hyperplane containing it.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Explicit computation of edges, assuming hyperplane containing the set.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Given a coplanar set, return exhaustive edge case theorem.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Enumerate all the vertices.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Number of edges meeting at each vertex.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
If-and-only-if version.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Show that the regular polyhedra do have all edges and faces congruent.
------------------------------------------------------------------------- | The five Platonic solids exist and there are no others .
needs "100/polyhedron.ml";;
needs "Multivariate/cross.ml";;
prioritize_real();;
Some standard regular polyhedra ( vertex coordinates from Wikipedia ) .
let std_tetrahedron = new_definition
`std_tetrahedron =
convex hull
{vector[&1;&1;&1],vector[-- &1;-- &1;&1],
vector[-- &1;&1;-- &1],vector[&1;-- &1;-- &1]}:real^3->bool`;;
let std_cube = new_definition
`std_cube =
convex hull
{vector[&1;&1;&1],vector[&1;&1;-- &1],
vector[&1;-- &1;&1],vector[&1;-- &1;-- &1],
vector[-- &1;&1;&1],vector[-- &1;&1;-- &1],
vector[-- &1;-- &1;&1],vector[-- &1;-- &1;-- &1]}:real^3->bool`;;
let std_octahedron = new_definition
`std_octahedron =
convex hull
{vector[&1;&0;&0],vector[-- &1;&0;&0],
vector[&0;&0;&1],vector[&0;&0;-- &1],
vector[&0;&1;&0],vector[&0;-- &1;&0]}:real^3->bool`;;
let std_dodecahedron = new_definition
`std_dodecahedron =
let p = (&1 + sqrt(&5)) / &2 in
convex hull
{vector[&1;&1;&1],vector[&1;&1;-- &1],
vector[&1;-- &1;&1],vector[&1;-- &1;-- &1],
vector[-- &1;&1;&1],vector[-- &1;&1;-- &1],
vector[-- &1;-- &1;&1],vector[-- &1;-- &1;-- &1],
vector[&0;inv p;p],vector[&0;inv p;--p],
vector[&0;--inv p;p],vector[&0;--inv p;--p],
vector[inv p;p;&0],vector[inv p;--p;&0],
vector[--inv p;p;&0],vector[--inv p;--p;&0],
vector[p;&0;inv p],vector[--p;&0;inv p],
vector[p;&0;--inv p],vector[--p;&0;--inv p]}:real^3->bool`;;
let std_icosahedron = new_definition
`std_icosahedron =
let p = (&1 + sqrt(&5)) / &2 in
convex hull
{vector[&0; &1; p],vector[&0; &1; --p],
vector[&0; -- &1; p],vector[&0; -- &1; --p],
vector[&1; p; &0],vector[&1; --p; &0],
vector[-- &1; p; &0],vector[-- &1; --p; &0],
vector[p; &0; &1],vector[--p; &0; &1],
vector[p; &0; -- &1],vector[--p; &0; -- &1]}:real^3->bool`;;
expression r1 + r2 * sqrt(5 ) where r2 is nonzero but r1 may be zero and
let REAL_RAT5_OF_RAT_CONV =
let pth = prove
(`p = p + &0 * sqrt(&5)`,
REAL_ARITH_TAC) in
let conv = REWR_CONV pth in
fun tm -> if is_ratconst tm then conv tm else REFL tm;;
let REAL_RAT_OF_RAT5_CONV =
let pth = prove
(`p + &0 * sqrt(&5) = p`,
REAL_ARITH_TAC) in
GEN_REWRITE_CONV TRY_CONV [pth];;
let REAL_RAT5_ADD_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) + (a2 + b2 * sqrt(&5)) =
(a1 + a2) + (b1 + b2) * sqrt(&5)`,
REAL_ARITH_TAC) in
REAL_RAT_ADD_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV REAL_RAT_ADD_CONV THENC
RAND_CONV(LAND_CONV REAL_RAT_ADD_CONV) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_SUB_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) - (a2 + b2 * sqrt(&5)) =
(a1 - a2) + (b1 - b2) * sqrt(&5)`,
REAL_ARITH_TAC) in
REAL_RAT_SUB_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV REAL_RAT_SUB_CONV THENC
RAND_CONV(LAND_CONV REAL_RAT_SUB_CONV) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_MUL_CONV =
let pth = prove
(`(a1 + b1 * sqrt(&5)) * (a2 + b2 * sqrt(&5)) =
(a1 * a2 + &5 * b1 * b2) + (a1 * b2 + a2 * b1) * sqrt(&5)`,
MP_TAC(ISPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD) in
REAL_RAT_MUL_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
LAND_CONV(COMB_CONV (RAND_CONV REAL_RAT_MUL_CONV) THENC
RAND_CONV REAL_RAT_MUL_CONV THENC
REAL_RAT_ADD_CONV) THENC
RAND_CONV(LAND_CONV
(BINOP_CONV REAL_RAT_MUL_CONV THENC REAL_RAT_ADD_CONV)) THENC
REAL_RAT_OF_RAT5_CONV);;
let REAL_RAT5_INV_CONV =
let pth = prove
(`~(a pow 2 = &5 * b pow 2)
==> inv(a + b * sqrt(&5)) =
a / (a pow 2 - &5 * b pow 2) +
--b / (a pow 2 - &5 * b pow 2) * sqrt(&5)`,
REPEAT GEN_TAC THEN
GEN_REWRITE_TAC (LAND_CONV o ONCE_DEPTH_CONV) [GSYM REAL_SUB_0] THEN
SUBGOAL_THEN
`a pow 2 - &5 * b pow 2 = (a + b * sqrt(&5)) * (a - b * sqrt(&5))`
SUBST1_TAC THENL
[MP_TAC(SPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD;
REWRITE_TAC[REAL_ENTIRE; DE_MORGAN_THM] THEN CONV_TAC REAL_FIELD]) in
fun tm ->
try REAL_RAT_INV_CONV tm with Failure _ ->
let th1 = PART_MATCH (lhs o rand) pth tm in
let th2 = MP th1 (EQT_ELIM(REAL_RAT_REDUCE_CONV(lhand(concl th1)))) in
let th3 = CONV_RULE(funpow 2 RAND_CONV (funpow 2 LAND_CONV
REAL_RAT_NEG_CONV)) th2 in
let th4 = CONV_RULE(RAND_CONV(RAND_CONV(LAND_CONV
(RAND_CONV(LAND_CONV REAL_RAT_POW_CONV THENC
RAND_CONV(RAND_CONV REAL_RAT_POW_CONV THENC
REAL_RAT_MUL_CONV) THENC
REAL_RAT_SUB_CONV) THENC
REAL_RAT_DIV_CONV)))) th3 in
let th5 = CONV_RULE(RAND_CONV(LAND_CONV
(RAND_CONV(LAND_CONV REAL_RAT_POW_CONV THENC
RAND_CONV(RAND_CONV REAL_RAT_POW_CONV THENC
REAL_RAT_MUL_CONV) THENC
REAL_RAT_SUB_CONV) THENC
REAL_RAT_DIV_CONV))) th4 in
th5;;
let REAL_RAT5_DIV_CONV =
GEN_REWRITE_CONV I [real_div] THENC
RAND_CONV REAL_RAT5_INV_CONV THENC
REAL_RAT5_MUL_CONV;;
let REAL_RAT5_LE_CONV =
let lemma = prove
(`!x y. x <= y * sqrt(&5) <=>
x <= &0 /\ &0 <= y \/
&0 <= x /\ &0 <= y /\ x pow 2 <= &5 * y pow 2 \/
x <= &0 /\ y <= &0 /\ &5 * y pow 2 <= x pow 2`,
REPEAT GEN_TAC THEN MP_TAC(ISPEC `&5` SQRT_POW_2) THEN
REWRITE_TAC[REAL_POS] THEN DISCH_THEN(fun th ->
GEN_REWRITE_TAC (RAND_CONV o ONCE_DEPTH_CONV) [SYM th]) THEN
REWRITE_TAC[GSYM REAL_POW_MUL; GSYM REAL_LE_SQUARE_ABS] THEN
MP_TAC(ISPECL [`sqrt(&5)`; `y:real`] (CONJUNCT1 REAL_LE_MUL_EQ)) THEN
SIMP_TAC[SQRT_POS_LT; REAL_OF_NUM_LT; ARITH] THEN REAL_ARITH_TAC) in
let pth = prove
(`(a1 + b1 * sqrt(&5)) <= (a2 + b2 * sqrt(&5)) <=>
a1 <= a2 /\ b1 <= b2 \/
a2 <= a1 /\ b1 <= b2 /\ (a1 - a2) pow 2 <= &5 * (b2 - b1) pow 2 \/
a1 <= a2 /\ b2 <= b1 /\ &5 * (b2 - b1) pow 2 <= (a1 - a2) pow 2`,
REWRITE_TAC[REAL_ARITH
`a + b * x <= a' + b' * x <=> a - a' <= (b' - b) * x`] THEN
REWRITE_TAC[lemma] THEN REAL_ARITH_TAC) in
REAL_RAT_LE_CONV ORELSEC
(BINOP_CONV REAL_RAT5_OF_RAT_CONV THENC
GEN_REWRITE_CONV I [pth] THENC
REAL_RAT_REDUCE_CONV);;
let REAL_RAT5_EQ_CONV =
GEN_REWRITE_CONV I [GSYM REAL_LE_ANTISYM] THENC
BINOP_CONV REAL_RAT5_LE_CONV THENC
GEN_REWRITE_CONV I [AND_CLAUSES];;
let VECTOR3_SUB_CONV =
let pth = prove
(`vector[x1;x2;x3] - vector[y1;y2;y3]:real^3 =
vector[x1-y1; x2-y2; x3-y3]`,
SIMP_TAC[CART_EQ; DIMINDEX_3; FORALL_3] THEN
REWRITE_TAC[VECTOR_3; VECTOR_SUB_COMPONENT]) in
GEN_REWRITE_CONV I [pth] THENC RAND_CONV(LIST_CONV REAL_RAT5_SUB_CONV);;
let VECTOR3_CROSS_CONV =
let pth = prove
(`(vector[x1;x2;x3]) cross (vector[y1;y2;y3]) =
vector[x2 * y3 - x3 * y2; x3 * y1 - x1 * y3; x1 * y2 - x2 * y1]`,
REWRITE_TAC[cross; VECTOR_3]) in
GEN_REWRITE_CONV I [pth] THENC
RAND_CONV(LIST_CONV(BINOP_CONV REAL_RAT5_MUL_CONV THENC REAL_RAT5_SUB_CONV));;
let VECTOR3_EQ_0_CONV =
let pth = prove
(`vector[x1;x2;x3]:real^3 = vec 0 <=>
x1 = &0 /\ x2 = &0 /\ x3 = &0`,
SIMP_TAC[CART_EQ; DIMINDEX_3; FORALL_3] THEN
REWRITE_TAC[VECTOR_3; VEC_COMPONENT]) in
GEN_REWRITE_CONV I [pth] THENC
DEPTH_BINOP_CONV `(/\)` REAL_RAT5_EQ_CONV THENC
REWRITE_CONV[];;
let VECTOR3_DOT_CONV =
let pth = prove
(`(vector[x1;x2;x3]:real^3) dot (vector[y1;y2;y3]) =
x1*y1 + x2*y2 + x3*y3`,
REWRITE_TAC[DOT_3; VECTOR_3]) in
GEN_REWRITE_CONV I [pth] THENC
DEPTH_BINOP_CONV `(+):real->real->real` REAL_RAT5_MUL_CONV THENC
RAND_CONV REAL_RAT5_ADD_CONV THENC
REAL_RAT5_ADD_CONV;;
let STD_DODECAHEDRON = prove
(`std_dodecahedron =
convex hull
{ vector[&1; &1; &1],
vector[&1; &1; -- &1],
vector[&1; -- &1; &1],
vector[&1; -- &1; -- &1],
vector[-- &1; &1; &1],
vector[-- &1; &1; -- &1],
vector[-- &1; -- &1; &1],
vector[-- &1; -- &1; -- &1],
vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)]}`,
let golden_inverse = prove
(`inv((&1 + sqrt(&5)) / &2) = -- &1 / &2 + &1 / &2 * sqrt(&5)`,
MP_TAC(ISPEC `&5` SQRT_POW_2) THEN CONV_TAC REAL_FIELD) in
REWRITE_TAC[std_dodecahedron] THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[golden_inverse] THEN
REWRITE_TAC[REAL_ARITH `(&1 + s) / &2 = &1 / &2 + &1 / &2 * s`] THEN
REWRITE_TAC[REAL_ARITH `--(a + b * sqrt(&5)) = --a + --b * sqrt(&5)`] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[]);;
let STD_ICOSAHEDRON = prove
(`std_icosahedron =
convex hull
{ vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)],
vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)],
vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0],
vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1],
vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1],
vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1]}`,
REWRITE_TAC[std_icosahedron] THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[REAL_ARITH `(&1 + s) / &2 = &1 / &2 + &1 / &2 * s`] THEN
REWRITE_TAC[REAL_ARITH `--(a + b * sqrt(&5)) = --a + --b * sqrt(&5)`] THEN
CONV_TAC REAL_RAT_REDUCE_CONV THEN REWRITE_TAC[]);;
let COMPUTE_FACES_2 = prove
(`!f s:real^3->bool.
FINITE s
==> (f face_of (convex hull s) /\ aff_dim f = &2 <=>
?x y z. x IN s /\ y IN s /\ z IN s /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN s ==> a dot w <= b) \/
(!w. w IN s ==> a dot w >= b)) /\
f = convex hull (s INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN STRIP_TAC THEN EQ_TAC THENL
[STRIP_TAC THEN
SUBGOAL_THEN `?t:real^3->bool. t SUBSET s /\ f = convex hull t`
MP_TAC THENL
[MATCH_MP_TAC FACE_OF_CONVEX_HULL_SUBSET THEN
ASM_SIMP_TAC[FINITE_IMP_COMPACT];
DISCH_THEN(X_CHOOSE_THEN `t:real^3->bool` MP_TAC)] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_CONVEX_HULL]) THEN
MP_TAC(ISPEC `t:real^3->bool` AFFINE_BASIS_EXISTS) THEN
DISCH_THEN(X_CHOOSE_THEN `u:real^3->bool` STRIP_ASSUME_TAC) THEN
SUBGOAL_THEN `(u:real^3->bool) HAS_SIZE 3` MP_TAC THENL
[ASM_SIMP_TAC[HAS_SIZE; AFFINE_INDEPENDENT_IMP_FINITE] THEN
REWRITE_TAC[GSYM INT_OF_NUM_EQ] THEN MATCH_MP_TAC(INT_ARITH
`aff_dim(u:real^3->bool) = &2 /\ aff_dim u = &(CARD u) - &1
==> &(CARD u):int = &3`) THEN CONJ_TAC
THENL [ASM_MESON_TAC[AFF_DIM_AFFINE_HULL]; ASM_MESON_TAC[AFF_DIM_UNIQUE]];
ALL_TAC] THEN
CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN SIMP_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPEAT(DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC)) THEN
DISCH_THEN SUBST_ALL_TAC THEN
MAP_EVERY EXISTS_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPLICATE_TAC 3 (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN
REPEAT LET_TAC THEN
SUBGOAL_THEN `~collinear{x:real^3,y,z}` MP_TAC THENL
[ASM_REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT]; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE `{x,y,z} = {z,x,y}`] THEN
ONCE_REWRITE_TAC[COLLINEAR_3] THEN ASM_REWRITE_TAC[GSYM CROSS_EQ_0] THEN
DISCH_TAC THEN ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN `(a:real^3) dot y = b /\ (a:real^3) dot z = b`
STRIP_ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC
[`(z - x) cross (y - x) = a`; `(a:real^3) dot x = b`] THEN VEC3_TAC;
ALL_TAC] THEN
MP_TAC(ISPECL [`convex hull s:real^3->bool`; `convex hull t:real^3->bool`]
EXPOSED_FACE_OF_POLYHEDRON) THEN
ASM_SIMP_TAC[POLYHEDRON_CONVEX_HULL; exposed_face_of] THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`a':real^3`; `b':real`] THEN
DISCH_THEN(STRIP_ASSUME_TAC o GSYM) THEN
SUBGOAL_THEN
`aff_dim(t:real^3->bool)
<= aff_dim({x:real^3 | a dot x = b} INTER {x | a' dot x = b'})`
MP_TAC THENL
[GEN_REWRITE_TAC LAND_CONV [GSYM AFF_DIM_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (LAND_CONV o RAND_CONV)
[SYM th]) THEN
REWRITE_TAC[AFF_DIM_AFFINE_HULL] THEN MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[SUBSET_INTER] THEN CONJ_TAC THENL
[ASM SET_TAC[];
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC `t:real^3->bool` THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[]];
ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFF_DIM_HYPERPLANE;
AFFINE_HYPERPLANE; DIMINDEX_3] THEN
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I
[SUBSET_HYPERPLANES]) THEN
ASM_REWRITE_TAC[HYPERPLANE_EQ_EMPTY] THEN
DISCH_THEN(DISJ_CASES_THEN2 SUBST_ALL_TAC (MP_TAC o SYM)) THENL
[RULE_ASSUM_TAC(REWRITE_RULE[INTER_UNIV]) THEN
SUBGOAL_THEN `s SUBSET {x:real^3 | a dot x = b}` ASSUME_TAC THENL
[MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull s:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `affine hull t:real^3->bool` THEN
REWRITE_TAC[CONVEX_HULL_SUBSET_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM SET_TAC[];
ALL_TAC] THEN
CONJ_TAC THENL
[RULE_ASSUM_TAC(REWRITE_RULE[SUBSET; IN_ELIM_THM]) THEN
ASM_SIMP_TAC[real_ge; REAL_LE_REFL];
ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`]];
ALL_TAC] THEN
DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(TAUT `(~p /\ ~q ==> F) ==> p \/ q`) THEN
REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; real_ge; REAL_NOT_LE] THEN
DISCH_THEN(CONJUNCTS_THEN2
(X_CHOOSE_TAC `u:real^3`) (X_CHOOSE_TAC `v:real^3`)) THEN
SUBGOAL_THEN `(a':real^3) dot u < b' /\ a' dot v < b'` ASSUME_TAC THENL
[REWRITE_TAC[REAL_LT_LE] THEN REWRITE_TAC
[SET_RULE `f x <= b /\ ~(f x = b) <=>
x IN {x | f x <= b} /\ ~(x IN {x | f x = b})`] THEN
ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[IN_ELIM_THM; REAL_LT_IMP_NE] THEN
SUBGOAL_THEN `(u:real^3) IN convex hull s /\ v IN convex hull s`
MP_TAC THENL [ASM_SIMP_TAC[HULL_INC]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `?w:real^3. w IN segment[u,v] /\ w IN {w | a' dot w = b'}`
MP_TAC THENL
[ASM_REWRITE_TAC[] THEN REWRITE_TAC[IN_ELIM_THM] THEN
MATCH_MP_TAC CONNECTED_IVT_HYPERPLANE THEN
MAP_EVERY EXISTS_TAC [`v:real^3`; `u:real^3`] THEN
ASM_SIMP_TAC[ENDS_IN_SEGMENT; CONNECTED_SEGMENT; REAL_LT_IMP_LE];
REWRITE_TAC[IN_SEGMENT; IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN
REWRITE_TAC[GSYM CONJ_ASSOC; RIGHT_EXISTS_AND_THM] THEN
REWRITE_TAC[UNWIND_THM2; DOT_RADD; DOT_RMUL; CONJ_ASSOC] THEN
DISCH_THEN(CHOOSE_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN
MATCH_MP_TAC(REAL_ARITH `a < b ==> a = b ==> F`) THEN
MATCH_MP_TAC REAL_CONVEX_BOUND_LT THEN ASM_REAL_ARITH_TAC];
MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[MATCH_MP_TAC HULL_MONO THEN REWRITE_TAC[SUBSET_INTER] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[];
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [SYM th]) THEN
REWRITE_TAC[SUBSET_INTER] THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE]]];
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`; `z:real^3`] THEN
REPEAT LET_TAC THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN CONJ_TAC THENL
[ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`convex hull (s INTER {x:real^3 | a dot x = b}) =
(convex hull s) INTER {x | a dot x = b}`
SUBST1_TAC THENL
[MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[SIMP_TAC[SUBSET_INTER; HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE];
ALL_TAC] THEN
ASM_CASES_TAC `s SUBSET {x:real^3 | a dot x = b}` THENL
[ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`] THEN SET_TAC[];
ALL_TAC] THEN
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC
`convex hull (convex hull (s INTER {x:real^3 | a dot x = b}) UNION
convex hull (s DIFF {x | a dot x = b})) INTER
{x | a dot x = b}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC(SET_RULE
`s SUBSET t ==> (s INTER u) SUBSET (t INTER u)`) THEN
MATCH_MP_TAC HULL_MONO THEN MATCH_MP_TAC(SET_RULE
`s INTER t SUBSET (P hull (s INTER t)) /\
s DIFF t SUBSET (P hull (s DIFF t))
==> s SUBSET (P hull (s INTER t)) UNION (P hull (s DIFF t))`) THEN
REWRITE_TAC[HULL_SUBSET];
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhs o rand) CONVEX_HULL_UNION_NONEMPTY_EXPLICIT o
lhand o lhand o snd) THEN
ANTS_TAC THENL
[SIMP_TAC[CONVEX_CONVEX_HULL; CONVEX_HULL_EQ_EMPTY] THEN ASM SET_TAC[];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[SUBSET; IN_INTER; IMP_CONJ; FORALL_IN_GSPEC] THEN
MAP_EVERY X_GEN_TAC [`p:real^3`; `u:real`; `q:real^3`] THEN
REPLICATE_TAC 4 DISCH_TAC THEN ASM_CASES_TAC `u = &0` THEN
ASM_REWRITE_TAC[VECTOR_ARITH `(&1 - &0) % p + &0 % q:real^N = p`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN REWRITE_TAC[IN_ELIM_THM] THEN
REWRITE_TAC[DOT_RADD; DOT_RMUL] THEN FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC(REAL_ARITH `x < y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * q < u * b
==> (&1 - u) * p + u * q < b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q < b <=> q IN {x | a dot x < b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LT] THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; REAL_LT_LE]];
MATCH_MP_TAC(REAL_ARITH `x > y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * b < u * q
==> (&1 - u) * p + u * q > b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; REWRITE_TAC[GSYM real_gt]] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q > b <=> q IN {x | a dot x > b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GT] THEN
RULE_ASSUM_TAC(REWRITE_RULE[real_ge]) THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; real_gt; REAL_LT_LE]]];
ALL_TAC] THEN
FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_LE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_GE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM]];
REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC `aff_dim {x:real^3 | a dot x = b}` THEN CONJ_TAC THENL
[MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
ASM_SIMP_TAC[AFF_DIM_HYPERPLANE; DIMINDEX_3] THEN INT_ARITH_TAC];
MATCH_MP_TAC INT_LE_TRANS THEN EXISTS_TAC `aff_dim {x:real^3,y,z}` THEN
CONJ_TAC THENL
[SUBGOAL_THEN `~collinear{x:real^3,y,z}` MP_TAC THENL
[ONCE_REWRITE_TAC[SET_RULE `{x,y,z} = {z,x,y}`] THEN
ONCE_REWRITE_TAC[COLLINEAR_3] THEN
ASM_REWRITE_TAC[GSYM CROSS_EQ_0];
REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT; DE_MORGAN_THM] THEN
STRIP_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INDEPENDENT] THEN
SIMP_TAC[CARD_CLAUSES; FINITE_INSERT; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; ARITH] THEN
CONV_TAC INT_REDUCE_CONV;
MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM_REWRITE_TAC[INSERT_SUBSET] THEN
REWRITE_TAC[EMPTY_SUBSET] THEN REPEAT CONJ_TAC THEN
MATCH_MP_TAC HULL_INC THEN
ASM_REWRITE_TAC[IN_INTER; IN_ELIM_THM] THEN
MAP_EVERY UNDISCH_TAC
[`(z - x) cross (y - x) = a`; `(a:real^3) dot x = b`] THEN
VEC3_TAC]]]]);;
let COMPUTE_FACES_2_STEP_1 = prove
(`!f v s t:real^3->bool.
(?x y z. x IN (v INSERT s) /\ y IN (v INSERT s) /\ z IN (v INSERT s) /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) <=>
(?y z. y IN s /\ z IN s /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) \/
(?x y z. x IN s /\ y IN s /\ z IN s /\
let a = (z - x) cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN REWRITE_TAC[IN_INSERT] THEN MATCH_MP_TAC(MESON[]
`(!x y z. Q x y z ==> Q x z y) /\
(!x y z. Q x y z ==> Q y x z) /\
(!x z. ~(Q x x z))
==> ((?x y z. (x = v \/ P x) /\ (y = v \/ P y) /\ (z = v \/ P z) /\
Q x y z) <=>
(?y z. P y /\ P z /\ Q v y z) \/
(?x y z. P x /\ P y /\ P z /\ Q x y z))`) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[VECTOR_SUB_REFL; CROSS_0] THEN
CONJ_TAC THEN REPEAT GEN_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
MAP_EVERY (SUBST1_TAC o VEC3_RULE)
[`(z - y) cross (x - y) = --((z - x) cross (y - x))`;
`(y - x) cross (z - x) = --((z - x) cross (y - x))`] THEN
REWRITE_TAC[VECTOR_NEG_EQ_0; DOT_LNEG; REAL_EQ_NEG2; REAL_LE_NEG2;
real_ge] THEN
REWRITE_TAC[DISJ_ACI] THEN
REWRITE_TAC[VEC3_RULE
`((z - x) cross (y - x)) dot y = ((z - x) cross (y - x)) dot x`]);;
let COMPUTE_FACES_2_STEP_2 = prove
(`!f u v s:real^3->bool.
(?y z. y IN (u INSERT s) /\ z IN (u INSERT s) /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) <=>
(?z. z IN s /\
let a = (z - v) cross (u - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b})) \/
(?y z. y IN s /\ z IN s /\
let a = (z - v) cross (y - v) in
~(a = vec 0) /\
let b = a dot v in
((!w. w IN t ==> a dot w <= b) \/
(!w. w IN t ==> a dot w >= b)) /\
f = convex hull (t INTER {x | a dot x = b}))`,
REPEAT GEN_TAC THEN REWRITE_TAC[IN_INSERT] THEN MATCH_MP_TAC(MESON[]
`(!x y. Q x y ==> Q y x) /\
(!x. ~(Q x x))
==> ((?y z. (y = u \/ P y) /\ (z = u \/ P z) /\
Q y z) <=>
(?z. P z /\ Q u z) \/
(?y z. P y /\ P z /\ Q y z))`) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
REWRITE_TAC[CROSS_REFL] THEN REPEAT GEN_TAC THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN SUBST1_TAC
(VEC3_RULE `(x - v) cross (y - v) = --((y - v) cross (x - v))`) THEN
REWRITE_TAC[VECTOR_NEG_EQ_0; DOT_LNEG; REAL_EQ_NEG2; REAL_LE_NEG2;
real_ge] THEN REWRITE_TAC[DISJ_ACI]);;
let COMPUTE_FACES_TAC =
let lemma = prove
(`(x INSERT s) INTER {x | P x} =
if P x then x INSERT (s INTER {x | P x})
else s INTER {x | P x}`,
COND_CASES_TAC THEN ASM SET_TAC[]) in
SIMP_TAC[COMPUTE_FACES_2; FINITE_INSERT; FINITE_EMPTY] THEN
REWRITE_TAC[COMPUTE_FACES_2_STEP_1] THEN
REWRITE_TAC[COMPUTE_FACES_2_STEP_2] THEN
REWRITE_TAC[NOT_IN_EMPTY] THEN
REWRITE_TAC[EXISTS_IN_INSERT; NOT_IN_EMPTY] THEN
REWRITE_TAC[FORALL_IN_INSERT; NOT_IN_EMPTY] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_CROSS_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[real_ge] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_LE_CONV) THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI] THEN
REPEAT(CHANGED_TAC
(ONCE_REWRITE_TAC[lemma] THEN
CONV_TAC(ONCE_DEPTH_CONV
(LAND_CONV VECTOR3_DOT_CONV THENC REAL_RAT5_EQ_CONV))) THEN
REWRITE_TAC[]) THEN
REWRITE_TAC[INTER_EMPTY] THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI];;
Apply this to our standard Platonic solids to derive facets .
Note : this is quite slow and can take a couple of hours .
let TETRAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_tetrahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1], vector[&1; &1; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_tetrahedron] THEN COMPUTE_FACES_TAC);;
let CUBE_FACETS = time prove
(`!f:real^3->bool.
f face_of std_cube /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
f = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1], vector[&1; &1; -- &1]} \/
f = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; &1], vector[&1; -- &1; &1], vector[&1; &1; &1]} \/
f = convex hull {vector[-- &1; &1; -- &1], vector[-- &1; &1; &1], vector[&1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[&1; -- &1; -- &1], vector[&1; -- &1; &1], vector[&1; &1; -- &1], vector[&1; &1; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_cube] THEN COMPUTE_FACES_TAC);;
let OCTAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_octahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
f = convex hull {vector[&1; &0; &0], vector[&0; &1; &0], vector[&0; &0; &1]}`,
GEN_TAC THEN REWRITE_TAC[std_octahedron] THEN COMPUTE_FACES_TAC);;
let ICOSAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_icosahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt(&5)]}`,
GEN_TAC THEN REWRITE_TAC[STD_ICOSAHEDRON] THEN COMPUTE_FACES_TAC);;
let DODECAHEDRON_FACETS = time prove
(`!f:real^3->bool.
f face_of std_dodecahedron /\ aff_dim f = &2 <=>
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[-- &1; -- &1; &1], vector[-- &1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; -- &1], vector[&1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[-- &1; -- &1; &1], vector[&1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; -- &1], vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[-- &1; &1; &1], vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5); &0], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; &1; -- &1], vector[&1; &1; &1]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; -- &1 / &2 + &1 / &2 * sqrt(&5)], vector[&1; -- &1; &1], vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); &1 / &2 + &1 / &2 * sqrt(&5)]} \/
f = convex hull {vector[&1 / &2 + &1 / &2 * sqrt(&5); &0; &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&1; -- &1; -- &1], vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt(&5); -- &1 / &2 + -- &1 / &2 * sqrt(&5)]}`,
GEN_TAC THEN REWRITE_TAC[STD_DODECAHEDRON] THEN COMPUTE_FACES_TAC);;
Maps term s to theorem |- ! IN s = = > n dot x = d
Currently assumes |s| > = 3 but it would be trivial to do other cases .
let COPLANAR_HYPERPLANE_RULE =
let rec allsets m l =
if m = 0 then [[]] else
match l with
[] -> []
| h::t -> map (fun g -> h::g) (allsets (m - 1) t) @ allsets m t in
let mk_sub = mk_binop `(-):real^3->real^3->real^3`
and mk_cross = mk_binop `cross`
and mk_dot = mk_binop `(dot):real^3->real^3->real`
and zerovec_tm = `vector[&0;&0;&0]:real^3`
and template = `(!x:real^3. x IN s ==> n dot x = d)`
and s_tm = `s:real^3->bool`
and n_tm = `n:real^3`
and d_tm = `d:real` in
let mk_normal [x;y;z] = mk_cross (mk_sub y x) (mk_sub z x) in
let eval_normal t =
(BINOP_CONV VECTOR3_SUB_CONV THENC VECTOR3_CROSS_CONV) (mk_normal t) in
let check_normal t =
let th = eval_normal t in
let n = rand(concl th) in
if n = zerovec_tm then failwith "check_normal" else n in
fun tm ->
let s = dest_setenum tm in
if length s < 3 then failwith "COPLANAR_HYPERPLANE_RULE: trivial" else
let n = tryfind check_normal (allsets 3 s) in
let d = rand(concl(VECTOR3_DOT_CONV(mk_dot n (hd s)))) in
let ptm = vsubst [tm,s_tm; n,n_tm; d,d_tm] template in
EQT_ELIM
((REWRITE_CONV[FORALL_IN_INSERT; NOT_IN_EMPTY] THENC
DEPTH_BINOP_CONV `/\`
(LAND_CONV VECTOR3_DOT_CONV THENC REAL_RAT5_EQ_CONV) THENC
GEN_REWRITE_CONV DEPTH_CONV [AND_CLAUSES]) ptm);;
let COMPUTE_FACES_1 = prove
(`!s:real^3->bool n d.
(!x. x IN s ==> n dot x = d)
==> FINITE s /\ ~(n = vec 0)
==> !f. f face_of (convex hull s) /\ aff_dim f = &1 <=>
?x y. x IN s /\ y IN s /\
let a = n cross (y - x) in
~(a = vec 0) /\
let b = a dot x in
((!w. w IN s ==> a dot w <= b) \/
(!w. w IN s ==> a dot w >= b)) /\
f = convex hull (s INTER {x | a dot x = b})`,
REPEAT GEN_TAC THEN STRIP_TAC THEN STRIP_TAC THEN GEN_TAC THEN EQ_TAC THENL
[STRIP_TAC THEN
SUBGOAL_THEN `?t:real^3->bool. t SUBSET s /\ f = convex hull t`
MP_TAC THENL
[MATCH_MP_TAC FACE_OF_CONVEX_HULL_SUBSET THEN
ASM_SIMP_TAC[FINITE_IMP_COMPACT];
DISCH_THEN(X_CHOOSE_THEN `t:real^3->bool` MP_TAC)] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_CONVEX_HULL]) THEN
MP_TAC(ISPEC `t:real^3->bool` AFFINE_BASIS_EXISTS) THEN
DISCH_THEN(X_CHOOSE_THEN `u:real^3->bool` STRIP_ASSUME_TAC) THEN
SUBGOAL_THEN `(u:real^3->bool) HAS_SIZE 2` MP_TAC THENL
[ASM_SIMP_TAC[HAS_SIZE; AFFINE_INDEPENDENT_IMP_FINITE] THEN
REWRITE_TAC[GSYM INT_OF_NUM_EQ] THEN MATCH_MP_TAC(INT_ARITH
`aff_dim(u:real^3->bool) = &1 /\ aff_dim u = &(CARD u) - &1
==> &(CARD u):int = &2`) THEN CONJ_TAC
THENL [ASM_MESON_TAC[AFF_DIM_AFFINE_HULL]; ASM_MESON_TAC[AFF_DIM_UNIQUE]];
ALL_TAC] THEN
CONV_TAC(LAND_CONV HAS_SIZE_CONV) THEN SIMP_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC SUBST_ALL_TAC) THEN
MAP_EVERY EXISTS_TAC [`x:real^3`; `y:real^3`] THEN
REPLICATE_TAC 2 (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN
SUBGOAL_THEN `(x:real^3) IN s /\ y IN s` STRIP_ASSUME_TAC THENL
[ASM SET_TAC[]; ALL_TAC] THEN
REPEAT LET_TAC THEN
MP_TAC(ISPECL [`n:real^3`; `y - x:real^3`] NORM_AND_CROSS_EQ_0) THEN
ASM_SIMP_TAC[DOT_RSUB; VECTOR_SUB_EQ; REAL_SUB_0] THEN DISCH_TAC THEN
SUBGOAL_THEN `(a:real^3) dot y = b` ASSUME_TAC THENL
[MAP_EVERY UNDISCH_TAC
[`n cross (y - x) = a`; `(a:real^3) dot x = b`] THEN VEC3_TAC;
ALL_TAC] THEN
MP_TAC(ISPECL [`convex hull s:real^3->bool`; `convex hull t:real^3->bool`]
EXPOSED_FACE_OF_POLYHEDRON) THEN
ASM_SIMP_TAC[POLYHEDRON_CONVEX_HULL; EXPOSED_FACE_OF_PARALLEL] THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`a':real^3`; `b':real`] THEN
SUBGOAL_THEN `~(convex hull t:real^3->bool = {})` ASSUME_TAC THENL
[REWRITE_TAC[GSYM MEMBER_NOT_EMPTY] THEN EXISTS_TAC `x:real^3` THEN
MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[];
ASM_REWRITE_TAC[]] THEN
ASM_CASES_TAC `convex hull t:real^3->bool = convex hull s` THEN
ASM_REWRITE_TAC[] THENL
[FIRST_X_ASSUM(ASSUME_TAC o GEN_REWRITE_RULE RAND_CONV
[GSYM AFFINE_HULL_CONVEX_HULL]) THEN
UNDISCH_THEN `convex hull t:real^3->bool = convex hull s`
(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFFINE_HULL_CONVEX_HULL]) THEN
REWRITE_TAC[SET_RULE `s = s INTER t <=> s SUBSET t`] THEN STRIP_TAC THEN
SUBGOAL_THEN `s SUBSET {x:real^3 | a dot x = b}` ASSUME_TAC THENL
[MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `affine hull s:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM SET_TAC[];
CONJ_TAC THENL
[RULE_ASSUM_TAC(REWRITE_RULE[SUBSET; IN_ELIM_THM]) THEN
ASM_SIMP_TAC[real_ge; REAL_LE_REFL];
AP_TERM_TAC THEN ASM SET_TAC[]]];
STRIP_TAC] THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFFINE_HULL_CONVEX_HULL]) THEN
SUBGOAL_THEN
`aff_dim(t:real^3->bool)
<= aff_dim(({x:real^3 | a dot x = b} INTER {x:real^3 | a' dot x = b'})
INTER {x | n dot x = d})`
MP_TAC THENL
[GEN_REWRITE_TAC LAND_CONV [GSYM AFF_DIM_AFFINE_HULL] THEN
FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC (LAND_CONV o RAND_CONV)
[SYM th]) THEN
REWRITE_TAC[AFF_DIM_AFFINE_HULL] THEN MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[SUBSET_INTER; INSERT_SUBSET; EMPTY_SUBSET; IN_ELIM_THM] THEN
ASM_SIMP_TAC[] THEN
SUBGOAL_THEN `(x:real^3) IN convex hull t /\ y IN convex hull t`
MP_TAC THENL
[CONJ_TAC THEN MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[];
ASM SET_TAC[]];
ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFF_DIM_HYPERPLANE;
AFFINE_HYPERPLANE; DIMINDEX_3; AFFINE_INTER] THEN
ASM_CASES_TAC `{x:real^3 | a dot x = b} SUBSET {v | a' dot v = b'}` THEN
ASM_REWRITE_TAC[] THENL
[ALL_TAC;
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (SET_RULE
`s INTER t SUBSET u ==> !x. x IN s /\ x IN t ==> x IN u`)) THEN
DISCH_THEN(MP_TAC o SPEC `x + n:real^3`) THEN
MATCH_MP_TAC(TAUT `p /\ q /\ ~r ==> (p /\ q ==> r) ==> s`) THEN
ASM_SIMP_TAC[IN_ELIM_THM; DOT_RADD] THEN REPEAT CONJ_TAC THENL
[EXPAND_TAC "a" THEN VEC3_TAC;
ALL_TAC;
ASM_REWRITE_TAC[REAL_EQ_ADD_LCANCEL_0; DOT_EQ_0]] THEN
SUBGOAL_THEN `a' dot (x:real^3) = b'` SUBST1_TAC THENL
[SUBGOAL_THEN `(x:real^3) IN convex hull t` MP_TAC THENL
[MATCH_MP_TAC HULL_INC THEN ASM SET_TAC[]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `(n:real^3) dot (x + a') = n dot x` MP_TAC THENL
[ALL_TAC;
SIMP_TAC[DOT_RADD] THEN REWRITE_TAC[DOT_SYM] THEN REAL_ARITH_TAC] THEN
MATCH_MP_TAC(REAL_ARITH `x:real = d /\ y = d ==> x = y`) THEN
SUBGOAL_THEN
`affine hull s SUBSET {x:real^3 | n dot x = d}`
MP_TAC THENL
[MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
REWRITE_TAC[SUBSET; IN_ELIM_THM] THEN ASM_SIMP_TAC[HULL_INC]]] THEN
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [SUBSET_HYPERPLANES]) THEN
ASM_REWRITE_TAC[HYPERPLANE_EQ_EMPTY; HYPERPLANE_EQ_UNIV] THEN
DISCH_THEN(fun th -> DISCH_THEN(K ALL_TAC) THEN MP_TAC(SYM th)) THEN
DISCH_THEN(fun th -> SUBST_ALL_TAC th THEN ASSUME_TAC th) THEN
CONJ_TAC THENL
[MATCH_MP_TAC(TAUT `(~p /\ ~q ==> F) ==> p \/ q`) THEN
REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; real_ge; REAL_NOT_LE] THEN
DISCH_THEN(CONJUNCTS_THEN2
(X_CHOOSE_TAC `u:real^3`) (X_CHOOSE_TAC `v:real^3`)) THEN
SUBGOAL_THEN `(a':real^3) dot u < b' /\ a' dot v < b'` ASSUME_TAC THENL
[REWRITE_TAC[REAL_LT_LE] THEN REWRITE_TAC
[SET_RULE `f x <= b /\ ~(f x = b) <=>
x IN {x | f x <= b} /\ ~(x IN {x | f x = b})`] THEN
ASM_REWRITE_TAC[] THEN ASM_SIMP_TAC[IN_ELIM_THM; REAL_LT_IMP_NE] THEN
SUBGOAL_THEN `(u:real^3) IN convex hull s /\ v IN convex hull s`
MP_TAC THENL [ASM_SIMP_TAC[HULL_INC]; ASM SET_TAC[]];
ALL_TAC] THEN
SUBGOAL_THEN `?w:real^3. w IN segment[u,v] /\ w IN {w | a' dot w = b'}`
MP_TAC THENL
[ASM_REWRITE_TAC[] THEN REWRITE_TAC[IN_ELIM_THM] THEN
MATCH_MP_TAC CONNECTED_IVT_HYPERPLANE THEN
MAP_EVERY EXISTS_TAC [`v:real^3`; `u:real^3`] THEN
ASM_SIMP_TAC[ENDS_IN_SEGMENT; CONNECTED_SEGMENT; REAL_LT_IMP_LE];
REWRITE_TAC[IN_SEGMENT; IN_ELIM_THM; LEFT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[SWAP_EXISTS_THM] THEN
REWRITE_TAC[GSYM CONJ_ASSOC; RIGHT_EXISTS_AND_THM] THEN
REWRITE_TAC[UNWIND_THM2; DOT_RADD; DOT_RMUL; CONJ_ASSOC] THEN
DISCH_THEN(CHOOSE_THEN(CONJUNCTS_THEN2 STRIP_ASSUME_TAC MP_TAC)) THEN
MATCH_MP_TAC(REAL_ARITH `a < b ==> a = b ==> F`) THEN
MATCH_MP_TAC REAL_CONVEX_BOUND_LT THEN ASM_REAL_ARITH_TAC];
FIRST_ASSUM(fun th -> GEN_REWRITE_TAC LAND_CONV [SYM th]) THEN
MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[MATCH_MP_TAC HULL_MONO THEN REWRITE_TAC[SUBSET_INTER] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull t:real^3->bool` THEN
REWRITE_TAC[HULL_SUBSET] THEN ASM SET_TAC[];
ASM_REWRITE_TAC[SUBSET_INTER] THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
ASM_REWRITE_TAC[] THEN MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE]]];
REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`x:real^3`; `y:real^3`] THEN
REPEAT LET_TAC THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN CONJ_TAC THENL
[ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`convex hull (s INTER {x:real^3 | a dot x = b}) =
(convex hull s) INTER {x | a dot x = b}`
SUBST1_TAC THENL
[MATCH_MP_TAC SUBSET_ANTISYM THEN CONJ_TAC THENL
[SIMP_TAC[SUBSET_INTER; HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC SUBSET_TRANS THEN
EXISTS_TAC `convex hull {x:real^3 | a dot x = b}` THEN
SIMP_TAC[HULL_MONO; INTER_SUBSET] THEN
MATCH_MP_TAC(SET_RULE `s = t ==> s SUBSET t`) THEN
REWRITE_TAC[CONVEX_HULL_EQ; CONVEX_HYPERPLANE];
ALL_TAC] THEN
ASM_CASES_TAC `s SUBSET {x:real^3 | a dot x = b}` THENL
[ASM_SIMP_TAC[SET_RULE `s SUBSET t ==> s INTER t = s`] THEN SET_TAC[];
ALL_TAC] THEN
MATCH_MP_TAC SUBSET_TRANS THEN EXISTS_TAC
`convex hull (convex hull (s INTER {x:real^3 | a dot x = b}) UNION
convex hull (s DIFF {x | a dot x = b})) INTER
{x | a dot x = b}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC(SET_RULE
`s SUBSET t ==> (s INTER u) SUBSET (t INTER u)`) THEN
MATCH_MP_TAC HULL_MONO THEN MATCH_MP_TAC(SET_RULE
`s INTER t SUBSET (P hull (s INTER t)) /\
s DIFF t SUBSET (P hull (s DIFF t))
==> s SUBSET (P hull (s INTER t)) UNION (P hull (s DIFF t))`) THEN
REWRITE_TAC[HULL_SUBSET];
ALL_TAC] THEN
W(MP_TAC o PART_MATCH (lhs o rand) CONVEX_HULL_UNION_NONEMPTY_EXPLICIT o
lhand o lhand o snd) THEN
ANTS_TAC THENL
[SIMP_TAC[CONVEX_CONVEX_HULL; CONVEX_HULL_EQ_EMPTY] THEN ASM SET_TAC[];
DISCH_THEN SUBST1_TAC] THEN
REWRITE_TAC[SUBSET; IN_INTER; IMP_CONJ; FORALL_IN_GSPEC] THEN
MAP_EVERY X_GEN_TAC [`p:real^3`; `u:real`; `q:real^3`] THEN
REPLICATE_TAC 4 DISCH_TAC THEN ASM_CASES_TAC `u = &0` THEN
ASM_REWRITE_TAC[VECTOR_ARITH `(&1 - &0) % p + &0 % q:real^N = p`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN REWRITE_TAC[IN_ELIM_THM] THEN
REWRITE_TAC[DOT_RADD; DOT_RMUL] THEN FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC(REAL_ARITH `x < y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * q < u * b
==> (&1 - u) * p + u * q < b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; ALL_TAC] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q < b <=> q IN {x | a dot x < b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LT] THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; REAL_LT_LE]];
MATCH_MP_TAC(REAL_ARITH `x > y ==> ~(x = y)`) THEN
MATCH_MP_TAC(REAL_ARITH
`(&1 - u) * p = (&1 - u) * b /\ u * b < u * q
==> (&1 - u) * p + u * q > b`) THEN
CONJ_TAC THENL
[SUBGOAL_THEN `p IN {x:real^3 | a dot x = b}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HYPERPLANE] THEN
SET_TAC[];
SIMP_TAC[IN_ELIM_THM]];
MATCH_MP_TAC REAL_LT_LMUL THEN CONJ_TAC THENL
[ASM_REAL_ARITH_TAC; REWRITE_TAC[GSYM real_gt]] THEN
ONCE_REWRITE_TAC[SET_RULE
`(a:real^3) dot q > b <=> q IN {x | a dot x > b}`] THEN
FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GT] THEN
RULE_ASSUM_TAC(REWRITE_RULE[real_ge]) THEN
ASM_SIMP_TAC[SUBSET; IN_DIFF; IN_ELIM_THM; real_gt; REAL_LT_LE]]];
ALL_TAC] THEN
FIRST_X_ASSUM DISJ_CASES_TAC THENL
[MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_LE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_LE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM];
MATCH_MP_TAC FACE_OF_INTER_SUPPORTING_HYPERPLANE_GE THEN
REWRITE_TAC[CONVEX_CONVEX_HULL] THEN
SIMP_TAC[SET_RULE `(!x. x IN s ==> P x) <=> s SUBSET {x | P x}`] THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[CONVEX_HALFSPACE_GE] THEN
ASM_SIMP_TAC[SUBSET; IN_ELIM_THM]];
ASM_REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[ALL_TAC;
MATCH_MP_TAC INT_LE_TRANS THEN EXISTS_TAC `aff_dim{x:real^3,y}` THEN
CONJ_TAC THENL
[ASM_REWRITE_TAC[AFF_DIM_2] THEN
ASM_MESON_TAC[CROSS_0; VECTOR_SUB_REFL; INT_LE_REFL];
MATCH_MP_TAC AFF_DIM_SUBSET THEN
REWRITE_TAC[INSERT_SUBSET; EMPTY_SUBSET] THEN
CONJ_TAC THEN MATCH_MP_TAC HULL_INC THEN
ASM_REWRITE_TAC[IN_INTER; IN_ELIM_THM] THEN
MAP_EVERY UNDISCH_TAC
[`n cross (y - x) = a`; `(a:real^3) dot x = b`] THEN
VEC3_TAC]] THEN
REWRITE_TAC[AFF_DIM_CONVEX_HULL] THEN MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC
`aff_dim({x:real^3 | a dot x = b} INTER {x | n dot x = d})` THEN
CONJ_TAC THENL
[MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM SET_TAC[]; ALL_TAC] THEN
ASM_SIMP_TAC[AFF_DIM_AFFINE_INTER_HYPERPLANE; AFFINE_HYPERPLANE;
AFF_DIM_HYPERPLANE; DIMINDEX_3] THEN
REPEAT(COND_CASES_TAC THEN CONV_TAC INT_REDUCE_CONV) THEN
FIRST_X_ASSUM(MP_TAC o SPEC `x + n:real^3` o
GEN_REWRITE_RULE I [SUBSET]) THEN
ASM_SIMP_TAC[IN_ELIM_THM; DOT_RADD; REAL_EQ_ADD_LCANCEL_0; DOT_EQ_0] THEN
EXPAND_TAC "a" THEN VEC3_TAC]]);;
let COMPUTE_EDGES_CONV =
let lemma = prove
(`(x INSERT s) INTER {x | P x} =
if P x then x INSERT (s INTER {x | P x})
else s INTER {x | P x}`,
COND_CASES_TAC THEN ASM SET_TAC[]) in
fun tm ->
let th1 = MATCH_MP COMPUTE_FACES_1 (COPLANAR_HYPERPLANE_RULE tm) in
let th2 = MP (CONV_RULE(LAND_CONV
(COMB2_CONV (RAND_CONV(PURE_REWRITE_CONV[FINITE_INSERT; FINITE_EMPTY]))
(RAND_CONV VECTOR3_EQ_0_CONV THENC
GEN_REWRITE_CONV I [NOT_CLAUSES]) THENC
GEN_REWRITE_CONV I [AND_CLAUSES])) th1) TRUTH in
CONV_RULE
(BINDER_CONV(RAND_CONV
(REWRITE_CONV[RIGHT_EXISTS_AND_THM] THENC
REWRITE_CONV[EXISTS_IN_INSERT; NOT_IN_EMPTY] THENC
REWRITE_CONV[FORALL_IN_INSERT; NOT_IN_EMPTY] THENC
ONCE_DEPTH_CONV VECTOR3_SUB_CONV THENC
ONCE_DEPTH_CONV VECTOR3_CROSS_CONV THENC
ONCE_DEPTH_CONV let_CONV THENC
ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV THENC
REWRITE_CONV[real_ge] THENC
ONCE_DEPTH_CONV VECTOR3_DOT_CONV THENC
ONCE_DEPTH_CONV let_CONV THENC
ONCE_DEPTH_CONV REAL_RAT5_LE_CONV THENC
REWRITE_CONV[INSERT_AC] THENC REWRITE_CONV[DISJ_ACI] THENC
REPEATC(CHANGED_CONV
(ONCE_REWRITE_CONV[lemma] THENC
ONCE_DEPTH_CONV(LAND_CONV VECTOR3_DOT_CONV THENC
REAL_RAT5_EQ_CONV) THENC
REWRITE_CONV[])) THENC
REWRITE_CONV[INTER_EMPTY] THENC
REWRITE_CONV[INSERT_AC] THENC REWRITE_CONV[DISJ_ACI]
))) th2;;
Use this to prove the number of edges per face for each Platonic solid .
let CARD_EQ_LEMMA = prove
(`!x s n. 0 < n /\ ~(x IN s) /\ s HAS_SIZE (n - 1)
==> (x INSERT s) HAS_SIZE n`,
REWRITE_TAC[HAS_SIZE] THEN REPEAT STRIP_TAC THEN
ASM_SIMP_TAC[CARD_CLAUSES; FINITE_INSERT] THEN ASM_ARITH_TAC);;
let EDGES_PER_FACE_TAC th =
REPEAT STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {e:real^3->bool | e face_of f /\ aff_dim(e) = &1}` THEN
CONJ_TAC THENL
[AP_TERM_TAC THEN GEN_REWRITE_TAC I [EXTENSION] THEN
REWRITE_TAC[IN_ELIM_THM] THEN
ASM_MESON_TAC[FACE_OF_FACE; FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
ALL_TAC] THEN
MP_TAC(ISPEC `f:real^3->bool` th) THEN ASM_REWRITE_TAC[] THEN
DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST1_TAC) THEN
W(fun (_,w) -> REWRITE_TAC[COMPUTE_EDGES_CONV(find_term is_setenum w)]) THEN
REWRITE_TAC[SET_RULE `x = a \/ x = b <=> x IN {a,b}`] THEN
REWRITE_TAC[GSYM IN_INSERT; SET_RULE `{x | x IN s} = s`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL] THEN MATCH_MP_TAC
(MESON[HAS_SIZE] `s HAS_SIZE n ==> CARD s = n`) THEN
REPEAT
(MATCH_MP_TAC CARD_EQ_LEMMA THEN REPEAT CONJ_TAC THENL
[CONV_TAC NUM_REDUCE_CONV THEN NO_TAC;
REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; SEGMENT_EQ; DE_MORGAN_THM] THEN
REPEAT CONJ_TAC THEN MATCH_MP_TAC(SET_RULE
`~(a = c /\ b = d) /\ ~(a = d /\ b = c) /\ ~(a = b /\ c = d)
==> ~({a,b} = {c,d})`) THEN
PURE_ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
ALL_TAC]) THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[CONJUNCT1 HAS_SIZE_CLAUSES];;
let TETRAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_tetrahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_tetrahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC TETRAHEDRON_FACETS);;
let CUBE_EDGES_PER_FACE = prove
(`!f. f face_of std_cube /\ aff_dim(f) = &2
==> CARD {e | e face_of std_cube /\ aff_dim(e) = &1 /\
e SUBSET f} = 4`,
EDGES_PER_FACE_TAC CUBE_FACETS);;
let OCTAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_octahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_octahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC OCTAHEDRON_FACETS);;
let DODECAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_dodecahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_dodecahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 5`,
EDGES_PER_FACE_TAC DODECAHEDRON_FACETS);;
let ICOSAHEDRON_EDGES_PER_FACE = prove
(`!f. f face_of std_icosahedron /\ aff_dim(f) = &2
==> CARD {e | e face_of std_icosahedron /\ aff_dim(e) = &1 /\
e SUBSET f} = 3`,
EDGES_PER_FACE_TAC ICOSAHEDRON_FACETS);;
Show that the Platonic solids are all full - dimensional .
let POLYTOPE_3D_LEMMA = prove
(`(let a = (z - x) cross (y - x) in
~(a = vec 0) /\ ?w. w IN s /\ ~(a dot w = a dot x))
==> aff_dim(convex hull (x INSERT y INSERT z INSERT s:real^3->bool)) = &3`,
REPEAT GEN_TAC THEN LET_TAC THEN STRIP_TAC THEN
REWRITE_TAC[GSYM INT_LE_ANTISYM] THEN CONJ_TAC THENL
[REWRITE_TAC[GSYM DIMINDEX_3; AFF_DIM_LE_UNIV]; ALL_TAC] THEN
REWRITE_TAC[AFF_DIM_CONVEX_HULL] THEN MATCH_MP_TAC INT_LE_TRANS THEN
EXISTS_TAC `aff_dim {w:real^3,x,y,z}` THEN CONJ_TAC THENL
[ALL_TAC; MATCH_MP_TAC AFF_DIM_SUBSET THEN ASM SET_TAC[]] THEN
ONCE_REWRITE_TAC[AFF_DIM_INSERT] THEN COND_CASES_TAC THENL
[SUBGOAL_THEN `w IN {w:real^3 | a dot w = a dot x}` MP_TAC THENL
[FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (SET_RULE
`x IN s ==> s SUBSET t ==> x IN t`)) THEN
MATCH_MP_TAC HULL_MINIMAL THEN REWRITE_TAC[AFFINE_HYPERPLANE] THEN
REWRITE_TAC[INSERT_SUBSET; EMPTY_SUBSET; IN_ELIM_THM] THEN
UNDISCH_TAC `~(a:real^3 = vec 0)` THEN EXPAND_TAC "a" THEN VEC3_TAC;
ASM_REWRITE_TAC[IN_ELIM_THM]];
UNDISCH_TAC `~(a:real^3 = vec 0)` THEN EXPAND_TAC "a" THEN
REWRITE_TAC[CROSS_EQ_0; GSYM COLLINEAR_3] THEN
REWRITE_TAC[COLLINEAR_3_EQ_AFFINE_DEPENDENT; INSERT_AC; DE_MORGAN_THM] THEN
STRIP_TAC THEN ASM_SIMP_TAC[AFF_DIM_AFFINE_INDEPENDENT] THEN
SIMP_TAC[CARD_CLAUSES; FINITE_INSERT; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; ARITH] THEN INT_ARITH_TAC]);;
let POLYTOPE_FULLDIM_TAC =
MATCH_MP_TAC POLYTOPE_3D_LEMMA THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_CROSS_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV let_CONV) THEN CONJ_TAC THENL
[CONV_TAC(RAND_CONV VECTOR3_EQ_0_CONV) THEN REWRITE_TAC[];
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
REWRITE_TAC[EXISTS_IN_INSERT; NOT_IN_EMPTY] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[]];;
let STD_TETRAHEDRON_FULLDIM = prove
(`aff_dim std_tetrahedron = &3`,
REWRITE_TAC[std_tetrahedron] THEN POLYTOPE_FULLDIM_TAC);;
let STD_CUBE_FULLDIM = prove
(`aff_dim std_cube = &3`,
REWRITE_TAC[std_cube] THEN POLYTOPE_FULLDIM_TAC);;
let STD_OCTAHEDRON_FULLDIM = prove
(`aff_dim std_octahedron = &3`,
REWRITE_TAC[std_octahedron] THEN POLYTOPE_FULLDIM_TAC);;
let STD_DODECAHEDRON_FULLDIM = prove
(`aff_dim std_dodecahedron = &3`,
REWRITE_TAC[STD_DODECAHEDRON] THEN POLYTOPE_FULLDIM_TAC);;
let STD_ICOSAHEDRON_FULLDIM = prove
(`aff_dim std_icosahedron = &3`,
REWRITE_TAC[STD_ICOSAHEDRON] THEN POLYTOPE_FULLDIM_TAC);;
Complete list of edges for each Platonic solid .
let COMPUTE_EDGES_TAC defn fulldim facets =
GEN_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`?f:real^3->bool. (f face_of p /\ aff_dim f = &2) /\
(e face_of f /\ aff_dim e = &1)`) THEN
CONJ_TAC THENL
[EQ_TAC THENL [STRIP_TAC; MESON_TAC[FACE_OF_TRANS]] THEN
MP_TAC(ISPECL [lhs(concl defn); `e:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
CONJ_TAC THEN
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
MATCH_MP_TAC MONO_EXISTS THEN REWRITE_TAC[facet_of] THEN
REWRITE_TAC[fulldim] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_MESON_TAC[FACE_OF_FACE]];
REWRITE_TAC[facets] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
CONV_TAC(LAND_CONV(DEPTH_BINOP_CONV `\/`
(fun tm -> REWR_CONV (COMPUTE_EDGES_CONV(rand(rand(lhand tm)))) tm))) THEN
REWRITE_TAC[INSERT_AC] THEN REWRITE_TAC[DISJ_ACI]];;
let TETRAHEDRON_EDGES = prove
(`!e. e face_of std_tetrahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; &1; &1]}`,
COMPUTE_EDGES_TAC
std_tetrahedron STD_TETRAHEDRON_FULLDIM TETRAHEDRON_FACETS);;
let CUBE_EDGES = prove
(`!e. e face_of std_cube /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&1; -- &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1; &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; -- &1; &1]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&1; &1; -- &1]} \/
e = convex hull {vector[&1; -- &1; &1], vector[&1; &1; &1]} \/
e = convex hull {vector[&1; &1; -- &1], vector[&1; &1; &1]}`,
COMPUTE_EDGES_TAC
std_cube STD_CUBE_FULLDIM CUBE_FACETS);;
let OCTAHEDRON_EDGES = prove
(`!e. e face_of std_octahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1; &0; &0], vector[&0; -- &1; &0]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &1; &0]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[-- &1; &0; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; -- &1; &0]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &1; &0]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&1; &0; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&0; -- &1; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&0; -- &1; &0], vector[&0; &0; &1]} \/
e = convex hull {vector[&0; &1; &0], vector[&0; &0; -- &1]} \/
e = convex hull {vector[&0; &1; &0], vector[&0; &0; &1]}`,
COMPUTE_EDGES_TAC
std_octahedron STD_OCTAHEDRON_FULLDIM OCTAHEDRON_FACETS);;
let DODECAHEDRON_EDGES = prove
(`!e. e face_of std_dodecahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[-- &1; &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[-- &1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1; &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[-- &1; -- &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[-- &1; -- &1; &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[-- &1; &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[-- &1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1; -- &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)], vector[&1; &1; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&1; -- &1; -- &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&1; &1; -- &1]} \/
e = convex hull {vector[-- &1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1; -- &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1; &1], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1; -- &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1; &1], vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)], vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_EDGES_TAC
STD_DODECAHEDRON STD_DODECAHEDRON_FULLDIM DODECAHEDRON_FACETS);;
let ICOSAHEDRON_EDGES = prove
(`!e. e face_of std_icosahedron /\ aff_dim e = &1 <=>
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0], vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&1; &1 / &2 + &1 / &2 * sqrt (&5); &0], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)], vector[&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
e = convex hull {vector[&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)], vector[&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_EDGES_TAC
STD_ICOSAHEDRON STD_ICOSAHEDRON_FULLDIM ICOSAHEDRON_FACETS);;
let COMPUTE_VERTICES_TAC defn fulldim edges =
GEN_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`?e:real^3->bool. (e face_of p /\ aff_dim e = &1) /\
(v face_of e /\ aff_dim v = &0)`) THEN
CONJ_TAC THENL
[EQ_TAC THENL [STRIP_TAC; MESON_TAC[FACE_OF_TRANS]] THEN
MP_TAC(ISPECL [lhs(concl defn); `v:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[ASM_REWRITE_TAC[] THEN CONJ_TAC THENL
[REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
CONJ_TAC THEN
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
REWRITE_TAC[facet_of] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^3->bool` STRIP_ASSUME_TAC)] THEN
MP_TAC(ISPECL [`f:real^3->bool`; `v:real^3->bool`]
FACE_OF_POLYHEDRON_SUBSET_FACET) THEN
ANTS_TAC THENL
[REPEAT CONJ_TAC THENL
[MATCH_MP_TAC FACE_OF_POLYHEDRON_POLYHEDRON THEN
FIRST_ASSUM(fun th ->
EXISTS_TAC (rand(concl th)) THEN
CONJ_TAC THENL [ALL_TAC; ACCEPT_TAC th]) THEN
REWRITE_TAC[defn] THEN
MATCH_MP_TAC POLYHEDRON_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
ASM_MESON_TAC[FACE_OF_FACE];
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV;
DISCH_THEN(MP_TAC o AP_TERM `aff_dim:(real^3->bool)->int`) THEN
ASM_REWRITE_TAC[fulldim; AFF_DIM_EMPTY] THEN
CONV_TAC INT_REDUCE_CONV];
MATCH_MP_TAC MONO_EXISTS THEN REWRITE_TAC[facet_of] THEN
ASM_REWRITE_TAC[fulldim] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_MESON_TAC[FACE_OF_FACE; FACE_OF_TRANS]];
REWRITE_TAC[edges] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
REWRITE_TAC[AFF_DIM_EQ_0; RIGHT_AND_EXISTS_THM] THEN
ONCE_REWRITE_TAC[MESON[]
`v face_of s /\ v = {a} <=> {a} face_of s /\ v = {a}`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL; FACE_OF_SING] THEN
REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`] THEN
REWRITE_TAC[EXISTS_OR_THM; UNWIND_THM2] THEN
REWRITE_TAC[DISJ_ACI]];;
let TETRAHEDRON_VERTICES = prove
(`!v. v face_of std_tetrahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1; -- &1; &1]} \/
v = {vector [-- &1; &1; -- &1]} \/
v = {vector [&1; -- &1; -- &1]} \/
v = {vector [&1; &1; &1]}`,
COMPUTE_VERTICES_TAC
std_tetrahedron STD_TETRAHEDRON_FULLDIM TETRAHEDRON_EDGES);;
let CUBE_VERTICES = prove
(`!v. v face_of std_cube /\ aff_dim v = &0 <=>
v = {vector [-- &1; -- &1; -- &1]} \/
v = {vector [-- &1; -- &1; &1]} \/
v = {vector [-- &1; &1; -- &1]} \/
v = {vector [-- &1; &1; &1]} \/
v = {vector [&1; -- &1; -- &1]} \/
v = {vector [&1; -- &1; &1]} \/
v = {vector [&1; &1; -- &1]} \/
v = {vector [&1; &1; &1]}`,
COMPUTE_VERTICES_TAC
std_cube STD_CUBE_FULLDIM CUBE_EDGES);;
let OCTAHEDRON_VERTICES = prove
(`!v. v face_of std_octahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1; &0; &0]} \/
v = {vector [&1; &0; &0]} \/
v = {vector [&0; -- &1; &0]} \/
v = {vector [&0; &1; &0]} \/
v = {vector [&0; &0; -- &1]} \/
v = {vector [&0; &0; &1]}`,
COMPUTE_VERTICES_TAC
std_octahedron STD_OCTAHEDRON_FULLDIM OCTAHEDRON_EDGES);;
let DODECAHEDRON_VERTICES = prove
(`!v. v face_of std_dodecahedron /\ aff_dim v = &0 <=>
v = {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector[-- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[&1 / &2 + &1 / &2 * sqrt (&5); &0; &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[-- &1; -- &1; -- &1]} \/
v = {vector[-- &1; -- &1; &1]} \/
v = {vector[-- &1; &1; -- &1]} \/
v = {vector[-- &1; &1; &1]} \/
v = {vector[&1; -- &1; -- &1]} \/
v = {vector[&1; -- &1; &1]} \/
v = {vector[&1; &1; -- &1]} \/
v = {vector[&1; &1; &1]} \/
v = {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; -- &1 / &2 + &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector[&0; &1 / &2 + -- &1 / &2 * sqrt (&5); &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_VERTICES_TAC
STD_DODECAHEDRON STD_DODECAHEDRON_FULLDIM DODECAHEDRON_EDGES);;
let ICOSAHEDRON_VERTICES = prove
(`!v. v face_of std_icosahedron /\ aff_dim v = &0 <=>
v = {vector [-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; -- &1]} \/
v = {vector [-- &1 / &2 + -- &1 / &2 * sqrt (&5); &0; &1]} \/
v = {vector [&1 / &2 + &1 / &2 * sqrt (&5); &0; -- &1]} \/
v = {vector [&1 / &2 + &1 / &2 * sqrt (&5); &0; &1]} \/
v = {vector [-- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector [-- &1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&1; -- &1 / &2 + -- &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&1; &1 / &2 + &1 / &2 * sqrt (&5); &0]} \/
v = {vector [&0; -- &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; -- &1; &1 / &2 + &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; &1; -- &1 / &2 + -- &1 / &2 * sqrt (&5)]} \/
v = {vector [&0; &1; &1 / &2 + &1 / &2 * sqrt (&5)]}`,
COMPUTE_VERTICES_TAC
STD_ICOSAHEDRON STD_ICOSAHEDRON_FULLDIM ICOSAHEDRON_EDGES);;
let EDGES_PER_VERTEX_TAC defn edges verts =
REPEAT STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC
(vsubst[lhs(concl defn),`p:real^3->bool`]
`CARD {e | (e face_of p /\ aff_dim(e) = &1) /\
(v:real^3->bool) face_of e}`) THEN
CONJ_TAC THENL
[AP_TERM_TAC THEN REWRITE_TAC[EXTENSION; IN_ELIM_THM] THEN
ASM_MESON_TAC[FACE_OF_FACE];
ALL_TAC] THEN
MP_TAC(ISPEC `v:real^3->bool` verts) THEN
ASM_REWRITE_TAC[] THEN
DISCH_THEN(REPEAT_TCL DISJ_CASES_THEN SUBST1_TAC) THEN
REWRITE_TAC[edges] THEN
REWRITE_TAC[SET_RULE
`{e | (P e \/ Q e) /\ R e} =
{e | P e /\ R e} UNION {e | Q e /\ R e}`] THEN
REWRITE_TAC[MESON[FACE_OF_SING]
`e = a /\ {x} face_of e <=> e = a /\ x extreme_point_of a`] THEN
REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL; EXTREME_POINT_OF_SEGMENT] THEN
ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[EMPTY_GSPEC; UNION_EMPTY] THEN
REWRITE_TAC[SET_RULE `{x | x = a} = {a}`] THEN
REWRITE_TAC[SET_RULE `{x} UNION s = x INSERT s`] THEN MATCH_MP_TAC
(MESON[HAS_SIZE] `s HAS_SIZE n ==> CARD s = n`) THEN
REPEAT
(MATCH_MP_TAC CARD_EQ_LEMMA THEN REPEAT CONJ_TAC THENL
[CONV_TAC NUM_REDUCE_CONV THEN NO_TAC;
REWRITE_TAC[IN_INSERT; NOT_IN_EMPTY; DE_MORGAN_THM; SEGMENT_EQ] THEN
REPEAT CONJ_TAC THEN MATCH_MP_TAC(SET_RULE
`~(a = c /\ b = d) /\ ~(a = d /\ b = c) /\ ~(a = b /\ c = d)
==> ~({a,b} = {c,d})`) THEN
PURE_ONCE_REWRITE_TAC[GSYM VECTOR_SUB_EQ] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_EQ_0_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
ALL_TAC]) THEN
CONV_TAC NUM_REDUCE_CONV THEN REWRITE_TAC[CONJUNCT1 HAS_SIZE_CLAUSES];;
let TETRAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_tetrahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_tetrahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
std_tetrahedron TETRAHEDRON_EDGES TETRAHEDRON_VERTICES);;
let CUBE_EDGES_PER_VERTEX = prove
(`!v. v face_of std_cube /\ aff_dim(v) = &0
==> CARD {e | e face_of std_cube /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
std_cube CUBE_EDGES CUBE_VERTICES);;
let OCTAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_octahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_octahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 4`,
EDGES_PER_VERTEX_TAC
std_octahedron OCTAHEDRON_EDGES OCTAHEDRON_VERTICES);;
let DODECAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_dodecahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_dodecahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 3`,
EDGES_PER_VERTEX_TAC
STD_DODECAHEDRON DODECAHEDRON_EDGES DODECAHEDRON_VERTICES);;
let ICOSAHEDRON_EDGES_PER_VERTEX = prove
(`!v. v face_of std_icosahedron /\ aff_dim(v) = &0
==> CARD {e | e face_of std_icosahedron /\ aff_dim(e) = &1 /\
v SUBSET e} = 5`,
EDGES_PER_VERTEX_TAC
STD_ICOSAHEDRON ICOSAHEDRON_EDGES ICOSAHEDRON_VERTICES);;
Number of Platonic solids .
let MULTIPLE_COUNTING_LEMMA = prove
(`!R:A->B->bool s t.
FINITE s /\ FINITE t /\
(!x. x IN s ==> CARD {y | y IN t /\ R x y} = m) /\
(!y. y IN t ==> CARD {x | x IN s /\ R x y} = n)
==> m * CARD s = n * CARD t`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPECL [`R:A->B->bool`; `\x:A y:B. 1`; `s:A->bool`; `t:B->bool`]
NSUM_NSUM_RESTRICT) THEN
ASM_SIMP_TAC[NSUM_CONST; FINITE_RESTRICT] THEN ARITH_TAC);;
let SIZE_ZERO_DIMENSIONAL_FACES = prove
(`!s:real^N->bool.
polyhedron s
==> CARD {f | f face_of s /\ aff_dim f = &0} =
CARD {v | v extreme_point_of s} /\
(FINITE {f | f face_of s /\ aff_dim f = &0} <=>
FINITE {v | v extreme_point_of s}) /\
(!n. {f | f face_of s /\ aff_dim f = &0} HAS_SIZE n <=>
{v | v extreme_point_of s} HAS_SIZE n)`,
REWRITE_TAC[RIGHT_AND_FORALL_THM] THEN REPEAT GEN_TAC THEN DISCH_TAC THEN
SUBGOAL_THEN `{f | f face_of s /\ aff_dim f = &0} =
IMAGE (\v:real^N. {v}) {v | v extreme_point_of s}`
SUBST1_TAC THENL
[CONV_TAC SYM_CONV THEN MATCH_MP_TAC SURJECTIVE_IMAGE_EQ THEN
REWRITE_TAC[AFF_DIM_SING; FACE_OF_SING; IN_ELIM_THM] THEN
REWRITE_TAC[AFF_DIM_EQ_0] THEN MESON_TAC[];
REPEAT STRIP_TAC THENL
[MATCH_MP_TAC CARD_IMAGE_INJ;
MATCH_MP_TAC FINITE_IMAGE_INJ_EQ;
MATCH_MP_TAC HAS_SIZE_IMAGE_INJ_EQ] THEN
ASM_SIMP_TAC[FINITE_POLYHEDRON_EXTREME_POINTS] THEN SET_TAC[]]);;
let PLATONIC_SOLIDS_LIMITS = prove
(`!p:real^3->bool m n.
polytope p /\ aff_dim p = &3 /\
(!f. f face_of p /\ aff_dim(f) = &2
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ e SUBSET f} = m) /\
(!v. v face_of p /\ aff_dim(v) = &0
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ v SUBSET e} = n)
==> m = 3 /\ n = 3 \/ // Tetrahedron
m = 4 /\ n = 3 \/ // Cube
m = 3 /\ n = 4 \/ // Octahedron
m = 5 /\ n = 3 \/ // Dodecahedron
m = 3 /\ n = 5 // Icosahedron`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPEC `p:real^3->bool` EULER_RELATION) THEN
ASM_REWRITE_TAC[] THEN
SUBGOAL_THEN
`m * CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2} =
2 * CARD {e | e face_of p /\ aff_dim e = &1} /\
n * CARD {v | v face_of p /\ aff_dim v = &0} =
2 * CARD {e | e face_of p /\ aff_dim e = &1}`
MP_TAC THENL
[CONJ_TAC THEN MATCH_MP_TAC MULTIPLE_COUNTING_LEMMA THENL
[EXISTS_TAC `\(f:real^3->bool) (e:real^3->bool). e SUBSET f`;
EXISTS_TAC `\(v:real^3->bool) (e:real^3->bool). v SUBSET e`] THEN
ONCE_REWRITE_TAC[SET_RULE `f face_of s <=> f IN {f | f face_of s}`] THEN
ASM_SIMP_TAC[FINITE_POLYTOPE_FACES; FINITE_RESTRICT] THEN
ASM_REWRITE_TAC[IN_ELIM_THM; GSYM CONJ_ASSOC] THEN
X_GEN_TAC `e:real^3->bool` THEN STRIP_TAC THENL
[MP_TAC(ISPECL [`p:real^3->bool`; `e:real^3->bool`]
POLYHEDRON_RIDGE_TWO_FACETS) THEN
ASM_SIMP_TAC[POLYTOPE_IMP_POLYHEDRON] THEN ANTS_TAC THENL
[CONV_TAC INT_REDUCE_CONV THEN DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_EMPTY]) THEN ASM_INT_ARITH_TAC;
CONV_TAC INT_REDUCE_CONV THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN
MAP_EVERY X_GEN_TAC [`f1:real^3->bool`; `f2:real^3->bool`] THEN
STRIP_TAC THEN MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {f1:real^3->bool,f2}` THEN CONJ_TAC THENL
[AP_TERM_TAC THEN GEN_REWRITE_TAC I [EXTENSION] THEN
REWRITE_TAC[IN_ELIM_THM; IN_INSERT; NOT_IN_EMPTY] THEN
ASM_MESON_TAC[];
ASM_SIMP_TAC[CARD_CLAUSES; IN_INSERT; FINITE_RULES;
NOT_IN_EMPTY; ARITH]]];
SUBGOAL_THEN `?a b:real^3. e = segment[a,b]` STRIP_ASSUME_TAC THENL
[MATCH_MP_TAC COMPACT_CONVEX_COLLINEAR_SEGMENT THEN
REPEAT CONJ_TAC THENL
[DISCH_THEN SUBST_ALL_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[AFF_DIM_EMPTY]) THEN ASM_INT_ARITH_TAC;
MATCH_MP_TAC FACE_OF_IMP_COMPACT THEN
EXISTS_TAC `p:real^3->bool` THEN
ASM_SIMP_TAC[POLYTOPE_IMP_CONVEX; POLYTOPE_IMP_COMPACT];
ASM_MESON_TAC[FACE_OF_IMP_CONVEX];
MP_TAC(ISPEC `e:real^3->bool` AFF_DIM) THEN
DISCH_THEN(X_CHOOSE_THEN `b:real^3->bool` MP_TAC) THEN
ASM_REWRITE_TAC[INT_ARITH `&1:int = b - &1 <=> b = &2`] THEN
DISCH_THEN(CONJUNCTS_THEN2 (ASSUME_TAC o SYM) MP_TAC) THEN
ASM_CASES_TAC `FINITE(b:real^3->bool)` THENL
[ALL_TAC; ASM_MESON_TAC[AFFINE_INDEPENDENT_IMP_FINITE]] THEN
REWRITE_TAC[INT_OF_NUM_EQ] THEN STRIP_TAC THEN
SUBGOAL_THEN `(b:real^3->bool) HAS_SIZE 2` MP_TAC THENL
[ASM_REWRITE_TAC[HAS_SIZE]; CONV_TAC(LAND_CONV HAS_SIZE_CONV)] THEN
REWRITE_TAC[COLLINEAR_AFFINE_HULL] THEN
REPEAT(MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC) THEN
ASM_MESON_TAC[HULL_SUBSET]];
ASM_CASES_TAC `a:real^3 = b` THENL
[UNDISCH_TAC `aff_dim(e:real^3->bool) = &1` THEN
ASM_REWRITE_TAC[SEGMENT_REFL; AFF_DIM_SING; INT_OF_NUM_EQ; ARITH_EQ];
ALL_TAC] THEN
MATCH_MP_TAC EQ_TRANS THEN
EXISTS_TAC `CARD {v:real^3 | v extreme_point_of segment[a,b]}` THEN
CONJ_TAC THENL
[MATCH_MP_TAC CARD_IMAGE_INJ_EQ THEN
EXISTS_TAC `\v:real^3. {v}` THEN
REWRITE_TAC[IN_ELIM_THM; FACE_OF_SING; AFF_DIM_SING] THEN
REPEAT CONJ_TAC THENL
[ASM_REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[SET_RULE `{x | x = a \/ x = b} = {a,b}`] THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
X_GEN_TAC `v:real^3` THEN REWRITE_TAC[GSYM FACE_OF_SING] THEN
ASM_MESON_TAC[FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
X_GEN_TAC `s:real^3->bool` THEN REWRITE_TAC[AFF_DIM_EQ_0] THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN
DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN
DISCH_THEN(X_CHOOSE_THEN `v:real^3` SUBST_ALL_TAC) THEN
REWRITE_TAC[EXISTS_UNIQUE] THEN EXISTS_TAC `v:real^3` THEN
ASM_REWRITE_TAC[GSYM FACE_OF_SING] THEN CONJ_TAC THENL
[ASM_MESON_TAC[FACE_OF_FACE]; SET_TAC[]]];
ASM_REWRITE_TAC[EXTREME_POINT_OF_SEGMENT] THEN
REWRITE_TAC[SET_RULE `{x | x = a \/ x = b} = {a,b}`] THEN
ASM_SIMP_TAC[FINITE_INSERT; CARD_CLAUSES; FINITE_EMPTY] THEN
ASM_REWRITE_TAC[IN_SING; NOT_IN_EMPTY; ARITH]]]];
ALL_TAC] THEN
STRIP_TAC THEN
DISCH_THEN(ASSUME_TAC o MATCH_MP (ARITH_RULE
`(a + b) - c = 2 ==> a + b = c + 2`)) THEN
SUBGOAL_THEN `4 <= CARD {v:real^3->bool | v face_of p /\ aff_dim v = &0}`
ASSUME_TAC THENL
[ASM_SIMP_TAC[SIZE_ZERO_DIMENSIONAL_FACES; POLYTOPE_IMP_POLYHEDRON] THEN
MP_TAC(ISPEC `p:real^3->bool` POLYTOPE_VERTEX_LOWER_BOUND) THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INT_REDUCE_CONV THEN
REWRITE_TAC[INT_OF_NUM_LE];
ALL_TAC] THEN
SUBGOAL_THEN `4 <= CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2}`
ASSUME_TAC THENL
[MP_TAC(ISPEC `p:real^3->bool` POLYTOPE_FACET_LOWER_BOUND) THEN
ASM_REWRITE_TAC[] THEN CONV_TAC INT_REDUCE_CONV THEN
ASM_REWRITE_TAC[INT_OF_NUM_LE; facet_of] THEN
MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN AP_TERM_TAC THEN
GEN_REWRITE_TAC I [EXTENSION] THEN REWRITE_TAC[IN_ELIM_THM] THEN
CONV_TAC INT_REDUCE_CONV THEN GEN_TAC THEN EQ_TAC THEN
STRIP_TAC THEN ASM_REWRITE_TAC[] THEN
ASM_MESON_TAC[INT_ARITH `~(&2:int = -- &1)`; AFF_DIM_EMPTY];
ALL_TAC] THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`v + f = e + 2 ==> 4 <= v /\ 4 <= f ==> 6 <= e`)) THEN
ASM_REWRITE_TAC[] THEN
ASM_CASES_TAC
`CARD {e:real^3->bool | e face_of p /\ aff_dim e = &1} = 0` THEN
ASM_REWRITE_TAC[ARITH] THEN DISCH_TAC THEN
SUBGOAL_THEN `3 <= m` ASSUME_TAC THENL
[ASM_CASES_TAC `{f:real^3->bool | f face_of p /\ aff_dim f = &2} = {}` THENL
[UNDISCH_TAC
`4 <= CARD {f:real^3->bool | f face_of p /\ aff_dim f = &2}` THEN
ASM_REWRITE_TAC[CARD_CLAUSES] THEN ARITH_TAC;
FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [GSYM MEMBER_NOT_EMPTY])] THEN
REWRITE_TAC[IN_ELIM_THM] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^3->bool` MP_TAC) THEN
DISCH_THEN(fun th -> STRIP_ASSUME_TAC th THEN
FIRST_X_ASSUM(SUBST1_TAC o SYM o C MATCH_MP th)) THEN
MP_TAC(ISPEC `f:real^3->bool` POLYTOPE_FACET_LOWER_BOUND) THEN
ASM_REWRITE_TAC[facet_of] THEN CONV_TAC INT_REDUCE_CONV THEN
ANTS_TAC THENL [ASM_MESON_TAC[FACE_OF_POLYTOPE_POLYTOPE]; ALL_TAC] THEN
REWRITE_TAC[INT_OF_NUM_LE] THEN MATCH_MP_TAC EQ_IMP THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN
GEN_REWRITE_TAC I [EXTENSION] THEN REWRITE_TAC[IN_ELIM_THM] THEN
CONV_TAC INT_REDUCE_CONV THEN X_GEN_TAC `e:real^3->bool` THEN
EQ_TAC THEN ASM_CASES_TAC `e:real^3->bool = {}` THEN
ASM_SIMP_TAC[AFF_DIM_EMPTY] THEN CONV_TAC INT_REDUCE_CONV THENL
[ASM_MESON_TAC[FACE_OF_TRANS; FACE_OF_IMP_SUBSET];
ASM_MESON_TAC[FACE_OF_FACE]];
ALL_TAC] THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP (ARITH_RULE `3 <= m ==> ~(m = 0)`)) THEN
ASM_CASES_TAC `n = 0` THENL
[UNDISCH_THEN `n = 0` SUBST_ALL_TAC THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE
`0 * x = 2 * e ==> e = 0`)) THEN ASM_REWRITE_TAC[];
ALL_TAC] THEN
FIRST_ASSUM(MP_TAC o MATCH_MP (NUM_RING
`v + f = e + 2 ==> !m n. m * n * v + n * m * f = m * n * (e + 2)`)) THEN
DISCH_THEN(MP_TAC o SPECL [`m:num`; `n:num`]) THEN ASM_REWRITE_TAC[] THEN
REWRITE_TAC[ARITH_RULE `m * 2 * e + n * 2 * e = m * n * (e + 2) <=>
e * 2 * (m + n) = m * n * (e + 2)`] THEN
ABBREV_TAC `E = CARD {e:real^3->bool | e face_of p /\ aff_dim e = &1}` THEN
ASM_CASES_TAC `n = 1` THENL
[ASM_REWRITE_TAC[MULT_CLAUSES; ARITH_RULE
`E * 2 * (n + 1) = n * (E + 2) <=> E * (n + 2) = 2 * n`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN
MATCH_MP_TAC(ARITH_RULE `n:num < m ==> ~(m = n)`) THEN
MATCH_MP_TAC LTE_TRANS THEN EXISTS_TAC `2 * (m + 2)` THEN
CONJ_TAC THENL [ARITH_TAC; MATCH_MP_TAC LE_MULT2 THEN ASM_ARITH_TAC];
ALL_TAC] THEN
ASM_CASES_TAC `n = 2` THENL
[ASM_REWRITE_TAC[ARITH_RULE `E * 2 * (n + 2) = n * 2 * (E + 2) <=>
E = n`] THEN
DISCH_THEN(SUBST_ALL_TAC o SYM) THEN
FIRST_X_ASSUM(MP_TAC o MATCH_MP (NUM_RING
`E * c = 2 * E ==> E = 0 \/ c = 2`)) THEN
ASM_ARITH_TAC;
ALL_TAC] THEN
SUBGOAL_THEN `3 <= n` ASSUME_TAC THENL [ASM_ARITH_TAC; ALL_TAC] THEN
ASM_CASES_TAC `m * n < 2 * (m + n)` THENL
[DISCH_TAC;
DISCH_TAC THEN RULE_ASSUM_TAC(REWRITE_RULE[NOT_LT]) THEN
SUBGOAL_THEN `E * 2 * (m + n) <= E * m * n` MP_TAC THENL
[REWRITE_TAC[LE_MULT_LCANCEL] THEN ASM_ARITH_TAC;
ASM_REWRITE_TAC[ARITH_RULE `m * n * (E + 2) <= E * m * n <=>
2 * m * n = 0`] THEN
MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN
REWRITE_TAC[MULT_EQ_0] THEN ASM_ARITH_TAC]] THEN
SUBGOAL_THEN `&m - &2:real < &4 /\ &n - &2 < &4` MP_TAC THENL
[CONJ_TAC THENL
[MATCH_MP_TAC REAL_LT_RCANCEL_IMP THEN EXISTS_TAC `&n - &2`;
MATCH_MP_TAC REAL_LT_LCANCEL_IMP THEN EXISTS_TAC `&m - &2`] THEN
ASM_SIMP_TAC[REAL_SUB_LT; REAL_OF_NUM_LT;
ARITH_RULE `2 < n <=> 3 <= n`] THEN
MATCH_MP_TAC REAL_LTE_TRANS THEN EXISTS_TAC `&4` THEN
REWRITE_TAC[REAL_ARITH `(m - &2) * (n - &2) < &4 <=>
m * n < &2 * (m + n)`] THEN
ASM_REWRITE_TAC[REAL_OF_NUM_MUL; REAL_OF_NUM_ADD; REAL_OF_NUM_LT] THEN
REWRITE_TAC[REAL_SUB_LDISTRIB; REAL_SUB_RDISTRIB; REAL_LE_SUB_LADD] THEN
REWRITE_TAC[REAL_OF_NUM_MUL; REAL_OF_NUM_ADD; REAL_OF_NUM_LE] THEN
ASM_ARITH_TAC;
ALL_TAC] THEN
REWRITE_TAC[REAL_LT_SUB_RADD; REAL_OF_NUM_ADD; REAL_OF_NUM_LT] THEN
REWRITE_TAC[ARITH_RULE `m < 4 + 2 <=> m <= 5`] THEN
ASM_SIMP_TAC[ARITH_RULE
`3 <= m ==> (m <= 5 <=> m = 3 \/ m = 4 \/ m = 5)`] THEN
STRIP_TAC THEN UNDISCH_TAC `E * 2 * (m + n) = m * n * (E + 2)` THEN
ASM_REWRITE_TAC[] THEN CONV_TAC NUM_REDUCE_CONV THEN ASM_ARITH_TAC);;
let PLATONIC_SOLIDS = prove
(`!m n.
(?p:real^3->bool.
polytope p /\ aff_dim p = &3 /\
(!f. f face_of p /\ aff_dim(f) = &2
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ e SUBSET f} = m) /\
(!v. v face_of p /\ aff_dim(v) = &0
==> CARD {e | e face_of p /\ aff_dim(e) = &1 /\ v SUBSET e} = n)) <=>
m = 3 /\ n = 3 \/ // Tetrahedron
m = 4 /\ n = 3 \/ // Cube
m = 3 /\ n = 4 \/ // Octahedron
m = 5 /\ n = 3 \/ // Dodecahedron
m = 3 /\ n = 5 // Icosahedron`,
REPEAT GEN_TAC THEN EQ_TAC THEN
REWRITE_TAC[LEFT_IMP_EXISTS_THM; PLATONIC_SOLIDS_LIMITS] THEN
STRIP_TAC THENL
[EXISTS_TAC `std_tetrahedron` THEN
ASM_REWRITE_TAC[TETRAHEDRON_EDGES_PER_VERTEX; TETRAHEDRON_EDGES_PER_FACE;
STD_TETRAHEDRON_FULLDIM] THEN
REWRITE_TAC[std_tetrahedron] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_cube` THEN
ASM_REWRITE_TAC[CUBE_EDGES_PER_VERTEX; CUBE_EDGES_PER_FACE;
STD_CUBE_FULLDIM] THEN
REWRITE_TAC[std_cube] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_octahedron` THEN
ASM_REWRITE_TAC[OCTAHEDRON_EDGES_PER_VERTEX; OCTAHEDRON_EDGES_PER_FACE;
STD_OCTAHEDRON_FULLDIM] THEN
REWRITE_TAC[std_octahedron] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_dodecahedron` THEN
ASM_REWRITE_TAC[DODECAHEDRON_EDGES_PER_VERTEX; DODECAHEDRON_EDGES_PER_FACE;
STD_DODECAHEDRON_FULLDIM] THEN
REWRITE_TAC[STD_DODECAHEDRON] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY];
EXISTS_TAC `std_icosahedron` THEN
ASM_REWRITE_TAC[ICOSAHEDRON_EDGES_PER_VERTEX; ICOSAHEDRON_EDGES_PER_FACE;
STD_ICOSAHEDRON_FULLDIM] THEN
REWRITE_TAC[STD_ICOSAHEDRON] THEN MATCH_MP_TAC POLYTOPE_CONVEX_HULL THEN
REWRITE_TAC[FINITE_INSERT; FINITE_EMPTY]]);;
parse_as_infix("congruent",(12,"right"));;
let congruent = new_definition
`(s:real^N->bool) congruent (t:real^N->bool) <=>
?c f. orthogonal_transformation f /\ t = IMAGE (\x. c + f x) s`;;
let CONGRUENT_SIMPLE = prove
(`(?A:real^3^3. orthogonal_matrix A /\ IMAGE (\x:real^3. A ** x) s = t)
==> (convex hull s) congruent (convex hull t)`,
REPEAT GEN_TAC THEN
DISCH_THEN(CHOOSE_THEN (CONJUNCTS_THEN2 ASSUME_TAC (SUBST1_TAC o SYM))) THEN
SIMP_TAC[CONVEX_HULL_LINEAR_IMAGE; MATRIX_VECTOR_MUL_LINEAR] THEN
REWRITE_TAC[congruent] THEN EXISTS_TAC `vec 0:real^3` THEN
EXISTS_TAC `\x:real^3. (A:real^3^3) ** x` THEN
REWRITE_TAC[VECTOR_ADD_LID; ORTHOGONAL_TRANSFORMATION_MATRIX] THEN
ASM_SIMP_TAC[MATRIX_OF_MATRIX_VECTOR_MUL; MATRIX_VECTOR_MUL_LINEAR]);;
let CONGRUENT_SEGMENTS = prove
(`!a b c d:real^N.
dist(a,b) = dist(c,d)
==> segment[a,b] congruent segment[c,d]`,
REPEAT STRIP_TAC THEN
MP_TAC(ISPECL [`b - a:real^N`; `d - c:real^N`]
ORTHOGONAL_TRANSFORMATION_EXISTS) THEN
ANTS_TAC THENL [POP_ASSUM MP_TAC THEN NORM_ARITH_TAC; ALL_TAC] THEN
DISCH_THEN(X_CHOOSE_THEN `f:real^N->real^N` STRIP_ASSUME_TAC) THEN
REWRITE_TAC[congruent] THEN
EXISTS_TAC `c - (f:real^N->real^N) a` THEN
EXISTS_TAC `f:real^N->real^N` THEN
FIRST_ASSUM(ASSUME_TAC o MATCH_MP ORTHOGONAL_TRANSFORMATION_LINEAR) THEN
SUBGOAL_THEN
`(\x. (c - f a) + (f:real^N->real^N) x) = (\x. (c - f a) + x) o f`
SUBST1_TAC THENL [REWRITE_TAC[FUN_EQ_THM; o_THM]; ALL_TAC] THEN
ASM_SIMP_TAC[GSYM CONVEX_HULL_LINEAR_IMAGE; SEGMENT_CONVEX_HULL; IMAGE_o;
GSYM CONVEX_HULL_TRANSLATION] THEN
REWRITE_TAC[IMAGE_CLAUSES] THEN
AP_TERM_TAC THEN BINOP_TAC THENL
[VECTOR_ARITH_TAC; AP_THM_TAC THEN AP_TERM_TAC] THEN
REWRITE_TAC[VECTOR_ARITH `d:real^N = c - a + b <=> b - a = d - c`] THEN
ASM_MESON_TAC[LINEAR_SUB]);;
let compute_dist =
let mk_sub = mk_binop `(-):real^3->real^3->real^3`
and dot_tm = `(dot):real^3->real^3->real` in
fun v1 v2 -> let vth = VECTOR3_SUB_CONV(mk_sub v1 v2) in
let dth = CONV_RULE(RAND_CONV VECTOR3_DOT_CONV)
(MK_COMB(AP_TERM dot_tm vth,vth)) in
rand(concl dth);;
let le_rat5 =
let mk_le = mk_binop `(<=):real->real->bool` and t_tm = `T` in
fun r1 r2 -> rand(concl(REAL_RAT5_LE_CONV(mk_le r1 r2))) = t_tm;;
let three_adjacent_points s =
match s with
| x::t -> let (y,_)::(z,_)::_ =
sort (fun (_,r1) (_,r2) -> le_rat5 r1 r2)
(map (fun y -> y,compute_dist x y) t) in
x,y,z
| _ -> failwith "three_adjacent_points: no points";;
let mk_33matrix =
let a11_tm = `a11:real`
and a12_tm = `a12:real`
and a13_tm = `a13:real`
and a21_tm = `a21:real`
and a22_tm = `a22:real`
and a23_tm = `a23:real`
and a31_tm = `a31:real`
and a32_tm = `a32:real`
and a33_tm = `a33:real`
and pat_tm =
`vector[vector[a11; a12; a13];
vector[a21; a22; a23];
vector[a31; a32; a33]]:real^3^3` in
fun [a11;a12;a13;a21;a22;a23;a31;a32;a33] ->
vsubst[a11,a11_tm;
a12,a12_tm;
a13,a13_tm;
a21,a21_tm;
a22,a22_tm;
a23,a23_tm;
a31,a31_tm;
a32,a32_tm;
a33,a33_tm] pat_tm;;
let MATRIX_VECTOR_MUL_3 = prove
(`(vector[vector[a11;a12;a13];
vector[a21; a22; a23];
vector[a31; a32; a33]]:real^3^3) **
(vector[x1;x2;x3]:real^3) =
vector[a11 * x1 + a12 * x2 + a13 * x3;
a21 * x1 + a22 * x2 + a23 * x3;
a31 * x1 + a32 * x2 + a33 * x3]`,
SIMP_TAC[CART_EQ; matrix_vector_mul; LAMBDA_BETA] THEN
REWRITE_TAC[DIMINDEX_3; FORALL_3; SUM_3; VECTOR_3]);;
let MATRIX_LEMMA = prove
(`!A:real^3^3.
A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
(vector [x1; y1; z1]:real^3^3) ** (row 1 A:real^3) =
vector [x2$1; y2$1; z2$1] /\
(vector [x1; y1; z1]:real^3^3) ** (row 2 A:real^3) =
vector [x2$2; y2$2; z2$2] /\
(vector [x1; y1; z1]:real^3^3) ** (row 3 A:real^3) =
vector [x2$3; y2$3; z2$3]`,
SIMP_TAC[CART_EQ; transp; matrix_vector_mul; row; VECTOR_3; LAMBDA_BETA] THEN
REWRITE_TAC[FORALL_3; DIMINDEX_3; VECTOR_3; SUM_3] THEN REAL_ARITH_TAC);;
let MATRIX_BY_CRAMER_LEMMA = prove
(`!A:real^3^3.
~(det(vector[x1; y1; z1]:real^3^3) = &0)
==> (A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
A = lambda m k. det((lambda i j.
if j = k
then (vector[x2$m; y2$m; z2$m]:real^3)$i
else (vector[x1; y1; z1]:real^3^3)$i$j)
:real^3^3) /
det(vector[x1;y1;z1]:real^3^3))`,
REPEAT STRIP_TAC THEN GEN_REWRITE_TAC LAND_CONV [MATRIX_LEMMA] THEN
ASM_SIMP_TAC[CRAMER] THEN REWRITE_TAC[CART_EQ; row] THEN
SIMP_TAC[LAMBDA_BETA] THEN REWRITE_TAC[DIMINDEX_3; FORALL_3]);;
let MATRIX_BY_CRAMER = prove
(`!A:real^3^3 x1 y1 z1 x2 y2 z2.
let d = det(vector[x1; y1; z1]:real^3^3) in
~(d = &0)
==> (A ** x1 = x2 /\
A ** y1 = y2 /\
A ** z1 = z2 <=>
A$1$1 =
(x2$1 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$1 +
x1$3 * y2$1 * z1$2 -
x2$1 * y1$3 * z1$2 -
x1$2 * y2$1 * z1$3 -
x1$3 * y1$2 * z2$1) / d /\
A$1$2 =
(x1$1 * y2$1 * z1$3 +
x2$1 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$1 -
x1$1 * y1$3 * z2$1 -
x2$1 * y1$1 * z1$3 -
x1$3 * y2$1 * z1$1) / d /\
A$1$3 =
(x1$1 * y1$2 * z2$1 +
x1$2 * y2$1 * z1$1 +
x2$1 * y1$1 * z1$2 -
x1$1 * y2$1 * z1$2 -
x1$2 * y1$1 * z2$1 -
x2$1 * y1$2 * z1$1) / d /\
A$2$1 =
(x2$2 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$2 +
x1$3 * y2$2 * z1$2 -
x2$2 * y1$3 * z1$2 -
x1$2 * y2$2 * z1$3 -
x1$3 * y1$2 * z2$2) / d /\
A$2$2 =
(x1$1 * y2$2 * z1$3 +
x2$2 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$2 -
x1$1 * y1$3 * z2$2 -
x2$2 * y1$1 * z1$3 -
x1$3 * y2$2 * z1$1) / d /\
A$2$3 =
(x1$1 * y1$2 * z2$2 +
x1$2 * y2$2 * z1$1 +
x2$2 * y1$1 * z1$2 -
x1$1 * y2$2 * z1$2 -
x1$2 * y1$1 * z2$2 -
x2$2 * y1$2 * z1$1) / d /\
A$3$1 =
(x2$3 * y1$2 * z1$3 +
x1$2 * y1$3 * z2$3 +
x1$3 * y2$3 * z1$2 -
x2$3 * y1$3 * z1$2 -
x1$2 * y2$3 * z1$3 -
x1$3 * y1$2 * z2$3) / d /\
A$3$2 =
(x1$1 * y2$3 * z1$3 +
x2$3 * y1$3 * z1$1 +
x1$3 * y1$1 * z2$3 -
x1$1 * y1$3 * z2$3 -
x2$3 * y1$1 * z1$3 -
x1$3 * y2$3 * z1$1) / d /\
A$3$3 =
(x1$1 * y1$2 * z2$3 +
x1$2 * y2$3 * z1$1 +
x2$3 * y1$1 * z1$2 -
x1$1 * y2$3 * z1$2 -
x1$2 * y1$1 * z2$3 -
x2$3 * y1$2 * z1$1) / d)`,
REPEAT GEN_TAC THEN CONV_TAC let_CONV THEN DISCH_TAC THEN
ASM_SIMP_TAC[MATRIX_BY_CRAMER_LEMMA] THEN
REWRITE_TAC[DET_3; CART_EQ] THEN
SIMP_TAC[LAMBDA_BETA; DIMINDEX_3; ARITH; VECTOR_3] THEN
REWRITE_TAC[FORALL_3; ARITH; VECTOR_3] THEN REWRITE_TAC[CONJ_ACI]);;
let CONGRUENT_EDGES_TAC edges =
REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM] THEN REWRITE_TAC[IMP_IMP] THEN
REWRITE_TAC[edges] THEN
REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[GSYM SEGMENT_CONVEX_HULL] THEN
MATCH_MP_TAC CONGRUENT_SEGMENTS THEN REWRITE_TAC[DIST_EQ] THEN
REWRITE_TAC[dist; NORM_POW_2] THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_SUB_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV VECTOR3_DOT_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[];;
let CONGRUENT_FACES_TAC facets =
REWRITE_TAC[IMP_CONJ; RIGHT_FORALL_IMP_THM] THEN REWRITE_TAC[IMP_IMP] THEN
REWRITE_TAC[facets] THEN
REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[] THEN
W(fun (asl,w) ->
let t1 = rand(lhand w) and t2 = rand(rand w) in
let (x1,y1,z1) = three_adjacent_points (dest_setenum t1)
and (x2,y2,z2) = three_adjacent_points (dest_setenum t2) in
let th1 = SPECL [`A:real^3^3`;x1;y1;z1;x2;y2;z2] MATRIX_BY_CRAMER in
let th2 = REWRITE_RULE[VECTOR_3; DET_3] th1 in
let th3 = CONV_RULE (DEPTH_CONV REAL_RAT5_MUL_CONV) th2 in
let th4 = CONV_RULE (DEPTH_CONV
(REAL_RAT5_ADD_CONV ORELSEC REAL_RAT5_SUB_CONV)) th3 in
let th5 = CONV_RULE let_CONV th4 in
let th6 = CONV_RULE(ONCE_DEPTH_CONV REAL_RAT5_DIV_CONV) th5 in
let th7 = CONV_RULE(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) th6 in
let th8 = MP th7 (EQT_ELIM(REWRITE_CONV[] (lhand(concl th7)))) in
let tms = map rhs (conjuncts(rand(concl th8))) in
let matt = mk_33matrix tms in
MATCH_MP_TAC CONGRUENT_SIMPLE THEN EXISTS_TAC matt THEN CONJ_TAC THENL
[REWRITE_TAC[ORTHOGONAL_MATRIX; CART_EQ] THEN
SIMP_TAC[transp; LAMBDA_BETA; matrix_mul; mat] THEN
REWRITE_TAC[DIMINDEX_3; SUM_3; FORALL_3; VECTOR_3; ARITH] THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_MUL_CONV) THEN
CONV_TAC(DEPTH_CONV REAL_RAT5_ADD_CONV) THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_EQ_CONV) THEN
REWRITE_TAC[] THEN NO_TAC;
REWRITE_TAC[IMAGE_CLAUSES; MATRIX_VECTOR_MUL_3] THEN
CONV_TAC(ONCE_DEPTH_CONV REAL_RAT5_MUL_CONV) THEN
CONV_TAC(DEPTH_CONV REAL_RAT5_ADD_CONV) THEN
REWRITE_TAC[INSERT_AC]]);;
let TETRAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_tetrahedron /\ aff_dim e1 = &1 /\
e2 face_of std_tetrahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC TETRAHEDRON_EDGES);;
let TETRAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_tetrahedron /\ aff_dim f1 = &2 /\
f2 face_of std_tetrahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC TETRAHEDRON_FACETS);;
let CUBE_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_cube /\ aff_dim e1 = &1 /\
e2 face_of std_cube /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC CUBE_EDGES);;
let CUBE_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_cube /\ aff_dim f1 = &2 /\
f2 face_of std_cube /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC CUBE_FACETS);;
let OCTAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_octahedron /\ aff_dim e1 = &1 /\
e2 face_of std_octahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC OCTAHEDRON_EDGES);;
let OCTAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_octahedron /\ aff_dim f1 = &2 /\
f2 face_of std_octahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC OCTAHEDRON_FACETS);;
let DODECAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_dodecahedron /\ aff_dim e1 = &1 /\
e2 face_of std_dodecahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC DODECAHEDRON_EDGES);;
let DODECAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_dodecahedron /\ aff_dim f1 = &2 /\
f2 face_of std_dodecahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC DODECAHEDRON_FACETS);;
let ICOSAHEDRON_CONGRUENT_EDGES = prove
(`!e1 e2. e1 face_of std_icosahedron /\ aff_dim e1 = &1 /\
e2 face_of std_icosahedron /\ aff_dim e2 = &1
==> e1 congruent e2`,
CONGRUENT_EDGES_TAC ICOSAHEDRON_EDGES);;
let ICOSAHEDRON_CONGRUENT_FACETS = prove
(`!f1 f2. f1 face_of std_icosahedron /\ aff_dim f1 = &2 /\
f2 face_of std_icosahedron /\ aff_dim f2 = &2
==> f1 congruent f2`,
CONGRUENT_FACES_TAC ICOSAHEDRON_FACETS);;
|
dc8f4676c6f6b7b0553cd8b89c168b34c442f79cf73426f5d4d014e4cdd22b84 | futurice/haskell-mega-repo | Auth.hs | module Futurice.App.FUM.Auth where
import Control.Concurrent.STM (atomically, readTVar)
import Control.Lens (has)
import Futurice.Prelude
import Futurice.Exit
import Prelude ()
import Servant (Handler)
import Futurice.App.FUM.ACL
import Futurice.App.FUM.Ctx
import Futurice.App.FUM.Types
import qualified Futurice.IdMap as IdMap
import qualified Personio
-- | Wrap endpoint requiring authentication.
withAuthUser'
:: a -- ^ Response to unauthenticated users
-> Ctx
-> Maybe Login
-> (AuthUser -> World -> IdMap.IdMap Personio.Employee -> LogT Handler a)
-> LogT Handler a
withAuthUser' def ctx mfu f = case mfu <|> ctxMockUser ctx of
Nothing -> pure def
Just fu -> do
(world, es) <- liftIO $ atomically $ (,)
<$> readTVar (ctxWorld ctx)
<*> readTVar (ctxPersonio ctx)
let rights = runExit $ do
when (isSudoer fu world) $ exit RightsIT
when (has (worldEmployees . ix fu) world) $ exit RightsNormal
return RightsOther
f (AuthUser fu rights) world es
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/fum-carbon-app/src/Futurice/App/FUM/Auth.hs | haskell | | Wrap endpoint requiring authentication.
^ Response to unauthenticated users | module Futurice.App.FUM.Auth where
import Control.Concurrent.STM (atomically, readTVar)
import Control.Lens (has)
import Futurice.Prelude
import Futurice.Exit
import Prelude ()
import Servant (Handler)
import Futurice.App.FUM.ACL
import Futurice.App.FUM.Ctx
import Futurice.App.FUM.Types
import qualified Futurice.IdMap as IdMap
import qualified Personio
withAuthUser'
-> Ctx
-> Maybe Login
-> (AuthUser -> World -> IdMap.IdMap Personio.Employee -> LogT Handler a)
-> LogT Handler a
withAuthUser' def ctx mfu f = case mfu <|> ctxMockUser ctx of
Nothing -> pure def
Just fu -> do
(world, es) <- liftIO $ atomically $ (,)
<$> readTVar (ctxWorld ctx)
<*> readTVar (ctxPersonio ctx)
let rights = runExit $ do
when (isSudoer fu world) $ exit RightsIT
when (has (worldEmployees . ix fu) world) $ exit RightsNormal
return RightsOther
f (AuthUser fu rights) world es
|
a4b36e34ea4305bfafbbe6986f3ecb08c7bcfad664e549a323cfe584b584bc76 | s-expressionists/ctype | classes.lisp | (in-package #:ctype)
(defclass ctype () ())
(defmethod make-load-form ((obj ctype) &optional env)
(make-load-form-saving-slots obj :environment env))
;; A ctype corresponding to a class.
;; Note that to avoid complication, classes that could be some other ctype must
be instead of this . E.g. T , CONS , LIST , ARRAY , INTEGER must not end up as
cclass ctypes . SEQUENCE and subclasses of FUNCTION are handled specially
in pairwise.lisp ( FUNCTION itself ends up as a CFUNCTION ) .
(defclass cclass (ctype)
((%class :initarg :class :reader cclass-class :type class)))
(defclass negation (ctype)
((%ctype :initarg :ctype :reader negation-ctype :type ctype)))
(defclass junction (ctype)
((%ctypes :initarg :ctypes :reader junction-ctypes
:type list)))
(defclass conjunction (junction) ())
(defclass disjunction (junction) ())
(defclass ccons (ctype)
((%car :initarg :car :reader ccons-car :type ctype)
(%cdr :initarg :cdr :reader ccons-cdr :type ctype)))
(defclass range (ctype)
((%kind :initarg :kind :reader range-kind
:type (member integer ratio
short-float single-float double-float long-float))
;; NIL means no bound, i.e. * in the type specifier.
(%low :initarg :low :reader range-low :type (or real null))
(%high :initarg :high :reader range-high :type (or real null))
(%low-xp :initarg :lxp :reader range-low-exclusive-p :type boolean)
(%high-xp :initarg :hxp :reader range-high-exclusive-p :type boolean)))
(defclass fpzero (ctype)
((%kind :initarg :kind :reader fpzero-kind
:type (member short-float single-float double-float long-float))
(%zero :initarg :zero :reader fpzero-zero :type float)))
(defclass ccomplex (ctype)
(;; The upgraded complex part type is some thing that can be meaningfully
compared with EQUAL . CL :* is always allowed and has the standard meaning .
(%ucpt :initarg :ucpt :reader ccomplex-ucpt)))
(defclass cmember (ctype)
((%members :initarg :members :reader cmember-members :type list)))
(defclass carray (ctype)
((%simplicity :initarg :simplicity :reader carray-simplicity
:type (member :simple :complex))
;; Can be * to indicate all possible. Should be more efficient that way.
;; Other than that, it's just something equal-comparable. Also should
;; be what's returned by array-element-type.
(%uaet :initarg :uaet :reader carray-uaet)
;; Expressed element type. Provided for use by compilers, but does not
affect typep , subtypep , etc .
(%eaet :initarg :eaet :reader carray-eaet :type ctype)
;; Either a list of dimensions (which are either positive integers or *)
;; or * indicating nothing specified.
(%dims :initarg :dims :reader carray-dims :type (or list (eql *)))))
(defclass charset (ctype)
((%pairs :initarg :pairs :reader charset-pairs
;; A list of (char-code . char-code) pairs, each representing
;; an inclusive interval of codepoints, in order and exclusive.
:type list)))
(defclass cvalues (ctype)
((%required :initarg :required :reader cvalues-required
A proper list of ctypes .
:type list)
(%optional :initarg :optional :reader cvalues-optional
A proper list of ctypes .
:type list)
(%rest :initarg :rest :reader cvalues-rest :type ctype)))
(defclass lambda-list (ctype)
((%required :initarg :required :reader lambda-list-required
A proper list of ctypes .
:type list)
(%optional :initarg :optional :reader lambda-list-optional
A proper list of ctypes .
:type list)
(%rest :initarg :rest :reader lambda-list-rest
;; Having no &rest is indicated by setting this to (bot).
:type ctype)
;; Is there a &key? This may be true even if no actual ctypes are
;; specified for keyword parameters.
(%keyp :initarg :keyp :reader lambda-list-keyp :type boolean)
(%keys :initarg :keys :reader lambda-list-key
;; A proper list of (keyword . ctype) pairs.
:type list)
;; Is there &allow-other-keys?
(%aokp :initarg :aokp :reader lambda-list-aokp :type boolean)))
(defclass cfunction (ctype)
(;; A specification of * is equivalent to (&rest t).
(%lambda-list :initarg :lambda-list :reader cfunction-lambda-list
:type lambda-list)
A specification of * is equivalent to ( values & rest t ) .
(%returns :initarg :returns :reader cfunction-returns :type cvalues)))
(defclass csatisfies (ctype)
((%fname :initarg :fname :reader csatisfies-fname)))
| null | https://raw.githubusercontent.com/s-expressionists/ctype/977f4bfce65c721ac1bb545ae52ec3873068831e/classes.lisp | lisp | A ctype corresponding to a class.
Note that to avoid complication, classes that could be some other ctype must
NIL means no bound, i.e. * in the type specifier.
The upgraded complex part type is some thing that can be meaningfully
Can be * to indicate all possible. Should be more efficient that way.
Other than that, it's just something equal-comparable. Also should
be what's returned by array-element-type.
Expressed element type. Provided for use by compilers, but does not
Either a list of dimensions (which are either positive integers or *)
or * indicating nothing specified.
A list of (char-code . char-code) pairs, each representing
an inclusive interval of codepoints, in order and exclusive.
Having no &rest is indicated by setting this to (bot).
Is there a &key? This may be true even if no actual ctypes are
specified for keyword parameters.
A proper list of (keyword . ctype) pairs.
Is there &allow-other-keys?
A specification of * is equivalent to (&rest t). | (in-package #:ctype)
(defclass ctype () ())
(defmethod make-load-form ((obj ctype) &optional env)
(make-load-form-saving-slots obj :environment env))
be instead of this . E.g. T , CONS , LIST , ARRAY , INTEGER must not end up as
cclass ctypes . SEQUENCE and subclasses of FUNCTION are handled specially
in pairwise.lisp ( FUNCTION itself ends up as a CFUNCTION ) .
(defclass cclass (ctype)
((%class :initarg :class :reader cclass-class :type class)))
(defclass negation (ctype)
((%ctype :initarg :ctype :reader negation-ctype :type ctype)))
(defclass junction (ctype)
((%ctypes :initarg :ctypes :reader junction-ctypes
:type list)))
(defclass conjunction (junction) ())
(defclass disjunction (junction) ())
(defclass ccons (ctype)
((%car :initarg :car :reader ccons-car :type ctype)
(%cdr :initarg :cdr :reader ccons-cdr :type ctype)))
(defclass range (ctype)
((%kind :initarg :kind :reader range-kind
:type (member integer ratio
short-float single-float double-float long-float))
(%low :initarg :low :reader range-low :type (or real null))
(%high :initarg :high :reader range-high :type (or real null))
(%low-xp :initarg :lxp :reader range-low-exclusive-p :type boolean)
(%high-xp :initarg :hxp :reader range-high-exclusive-p :type boolean)))
(defclass fpzero (ctype)
((%kind :initarg :kind :reader fpzero-kind
:type (member short-float single-float double-float long-float))
(%zero :initarg :zero :reader fpzero-zero :type float)))
(defclass ccomplex (ctype)
compared with EQUAL . CL :* is always allowed and has the standard meaning .
(%ucpt :initarg :ucpt :reader ccomplex-ucpt)))
(defclass cmember (ctype)
((%members :initarg :members :reader cmember-members :type list)))
(defclass carray (ctype)
((%simplicity :initarg :simplicity :reader carray-simplicity
:type (member :simple :complex))
(%uaet :initarg :uaet :reader carray-uaet)
affect typep , subtypep , etc .
(%eaet :initarg :eaet :reader carray-eaet :type ctype)
(%dims :initarg :dims :reader carray-dims :type (or list (eql *)))))
(defclass charset (ctype)
((%pairs :initarg :pairs :reader charset-pairs
:type list)))
(defclass cvalues (ctype)
((%required :initarg :required :reader cvalues-required
A proper list of ctypes .
:type list)
(%optional :initarg :optional :reader cvalues-optional
A proper list of ctypes .
:type list)
(%rest :initarg :rest :reader cvalues-rest :type ctype)))
(defclass lambda-list (ctype)
((%required :initarg :required :reader lambda-list-required
A proper list of ctypes .
:type list)
(%optional :initarg :optional :reader lambda-list-optional
A proper list of ctypes .
:type list)
(%rest :initarg :rest :reader lambda-list-rest
:type ctype)
(%keyp :initarg :keyp :reader lambda-list-keyp :type boolean)
(%keys :initarg :keys :reader lambda-list-key
:type list)
(%aokp :initarg :aokp :reader lambda-list-aokp :type boolean)))
(defclass cfunction (ctype)
(%lambda-list :initarg :lambda-list :reader cfunction-lambda-list
:type lambda-list)
A specification of * is equivalent to ( values & rest t ) .
(%returns :initarg :returns :reader cfunction-returns :type cvalues)))
(defclass csatisfies (ctype)
((%fname :initarg :fname :reader csatisfies-fname)))
|
e8697009e096adb8f6cbb373c5f9ff1d9ed7e53bcb286bb9470b668728938455 | xach/octree | hex-art.lisp | ;;;; hex-art.lisp
(in-package #:octree)
(defun hex-path (centerpoint radius)
"Create a hexagon path centered at CENTERPOINT."
(let ((step (* pi 1/3))
(angle 0))
(move-to (add centerpoint (apoint angle radius)))
(dotimes (i 5)
(incf angle step)
(line-to (add centerpoint (apoint angle radius))))
(close-subpath)))
(defun containsp (point box)
(let ((min (minpoint box))
(max (maxpoint box)))
(and (<= (x min) (x point) (x max))
(<= (y min) (y point) (y max)))))
(defun call-for-hex-centerpoints (fun canvas radius)
(let* ((3r (* radius 3))
(margin-box (expand canvas 3r))
(min (minpoint margin-box))
(max (maxpoint margin-box))
(min-x (x min))
(min-y (y min))
(max-x (x max))
(max-y (y max))
(centerpoint (centerpoint canvas))
(center-delta (add (apoint 0 radius)
(apoint (/ pi 3) radius))))
(flet ((do-row (point)
(let* ((start-x (- (x point)
(* 3r (ceiling (abs (- (x point) min-x))
3r))))
(steps (ceiling (vectometry:width margin-box) 3r)))
(loop for x from start-x by 3r
for p = (point x (y point))
repeat steps
do (funcall fun p)))))
(loop for p = centerpoint then (add p center-delta)
while (< (y p) max-y)
do (do-row p))
(setf center-delta (point (x center-delta)
(- (y center-delta))))
(loop for p = (add centerpoint center-delta) then (add p center-delta)
while (< min-y (y p))
do (do-row p)))))
(defun ilerper (min max)
"Return a function that maps values between min and max to a
normalized value between 0 and 1.0."
(let ((magnitude (- max min)))
(lambda (value)
(cond ((<= value min)
0.0)
((<= max value)
1.0)
(t
(float (/ (- value min) magnitude)))))))
(defun range-mapper (input-min input-max output-min output-max)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(lambda (value)
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* norm out-magnitude))))))
(defun remap (input-min input-max output-min output-max value)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* norm out-magnitude)))))
(defun remap-sine (input-min input-max output-min output-max value)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* (sin (* pi norm)) norm out-magnitude)))) )
(defun remapper (ilerp-fun min max)
(let ((magnitude (- max min)))
(lambda (value)
(+ min (* magnitude (funcall ilerp-fun value))))))
(defun revmapper (ilerp-fun min max)
(let ((magnitude (- max min)))
(lambda (value)
(- max (* magnitude (funcall ilerp-fun value))))))
(defun test-hex (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(p (centerpoint canvas))
(radius 25))
(declare (ignore ds))
(with-box-canvas canvas
(set-fill-color (hsv-color 45 1.0 1.0))
(clear-canvas)
(set-line-width 3)
(set-line-join :round)
(let* ((ilerp (ilerper 0 (distance p (minpoint canvas))))
(revmap (remapper ilerp 0.5 1.0))
(thickmap (revmapper ilerp 2 4)))
(call-for-hex-centerpoints (lambda (p)
(let ((mag (distance p (centerpoint canvas))))
(set-line-width (funcall thickmap mag))
(hex-path p
(* radius
0.9
(funcall revmap mag))))
(stroke))
canvas
radius))
(save-png file))
#+nil
(output-data-stream ds file)))
(defun test-hex-animation (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(p (centerpoint canvas))
(radius 15)
(frames 48)
(anglestep (/ (* pi 2) frames)))
(with-box-canvas canvas
(set-fill-color (hsv-color 45 0.0 0.5))
(dotimes (i frames)
(clear-canvas)
(set-line-width 3)
(set-line-join :round)
(let* ((ilerp (ilerper 0 256))
(revmap (remapper ilerp 0.25 1.0))
(colormap (revmapper ilerp 0 360))
(thickmap (revmapper ilerp 1 1))
(refpoint (add p
(apoint (* anglestep i) 100))))
(call-for-hex-centerpoints (lambda (p)
(with-graphics-state
(let* ((mag (distance p refpoint))
(fill-color
(hsv-color (funcall colormap mag)
(funcall ilerp mag)
0.5))
(stroke-color
(hsv-color (funcall colormap mag)
(funcall ilerp mag)
0.25)))
(set-line-width (funcall thickmap mag))
(set-stroke-color stroke-color)
(set-fill-color fill-color)
(hex-path p
(* radius
0.9
(funcall revmap mag)))
(fill-and-stroke))))
canvas
radius))
(add-image (vimage-gif-image :delay-time 7) ds)))
(output-data-stream ds file)))
(defmacro do-hexes ((centerpoint canvas radius) &body body)
`(call-for-hex-centerpoints (lambda (,centerpoint) ,@body)
,canvas ,radius))
(defun hexleg (radius)
(let ((halfradius (/ radius 2)))
(sqrt (- (* radius radius)
(* halfradius halfradius)))))
(defun jitter (value magnitude)
(+ value (- magnitude (random (* 2 magnitude)))))
(defun test-hex-overlap-animation (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(radius 48)
(r/2 (/ radius 2))
(j (/ radius 20.0))
(frames 48)
(red (hsv-color 0 1 1))
(green (hsv-color 120 1 1))
(blue (hsv-color 240 1 1)))
(with-box-canvas canvas
(setf (vecto::blend-style vecto::*graphics-state*) :add)
(dotimes (i frames)
(let ((horizontal-displacement (remap-sine 0 frames
0 (* 3 radius)
i))
(vertical-displacement (remap-sine 0 frames
0 (* 2 (hexleg radius))
i)))
(set-fill-color *black*)
(clear-canvas)
(set-line-width 2)
(do-hexes (hex canvas radius)
(set-fill-color red)
(centered-circle-path (add hex
(point (jitter 0 j)
(jitter vertical-displacement j)))
r/2)
(fill-path))
(do-hexes (hex canvas radius)
(set-fill-color green)
(centered-circle-path (add hex
(point (jitter 0 j)
(jitter (- vertical-displacement) j)))
r/2)
(fill-path))
(do-hexes (hex canvas radius)
(set-fill-color blue)
(centered-circle-path (add hex
(point (jitter horizontal-displacement j)
(jitter 0 j)))
r/2)
(fill-path)))
(add-image (vimage-gif-image :delay-time (+ 7 (if (zerop i) 25 0))) ds)))
(output-data-stream ds file)))
| null | https://raw.githubusercontent.com/xach/octree/70c5ba6a5ddbf6d05540dad561e9ceffe6255da7/hex-art.lisp | lisp | hex-art.lisp |
(in-package #:octree)
(defun hex-path (centerpoint radius)
"Create a hexagon path centered at CENTERPOINT."
(let ((step (* pi 1/3))
(angle 0))
(move-to (add centerpoint (apoint angle radius)))
(dotimes (i 5)
(incf angle step)
(line-to (add centerpoint (apoint angle radius))))
(close-subpath)))
(defun containsp (point box)
(let ((min (minpoint box))
(max (maxpoint box)))
(and (<= (x min) (x point) (x max))
(<= (y min) (y point) (y max)))))
(defun call-for-hex-centerpoints (fun canvas radius)
(let* ((3r (* radius 3))
(margin-box (expand canvas 3r))
(min (minpoint margin-box))
(max (maxpoint margin-box))
(min-x (x min))
(min-y (y min))
(max-x (x max))
(max-y (y max))
(centerpoint (centerpoint canvas))
(center-delta (add (apoint 0 radius)
(apoint (/ pi 3) radius))))
(flet ((do-row (point)
(let* ((start-x (- (x point)
(* 3r (ceiling (abs (- (x point) min-x))
3r))))
(steps (ceiling (vectometry:width margin-box) 3r)))
(loop for x from start-x by 3r
for p = (point x (y point))
repeat steps
do (funcall fun p)))))
(loop for p = centerpoint then (add p center-delta)
while (< (y p) max-y)
do (do-row p))
(setf center-delta (point (x center-delta)
(- (y center-delta))))
(loop for p = (add centerpoint center-delta) then (add p center-delta)
while (< min-y (y p))
do (do-row p)))))
(defun ilerper (min max)
"Return a function that maps values between min and max to a
normalized value between 0 and 1.0."
(let ((magnitude (- max min)))
(lambda (value)
(cond ((<= value min)
0.0)
((<= max value)
1.0)
(t
(float (/ (- value min) magnitude)))))))
(defun range-mapper (input-min input-max output-min output-max)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(lambda (value)
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* norm out-magnitude))))))
(defun remap (input-min input-max output-min output-max value)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* norm out-magnitude)))))
(defun remap-sine (input-min input-max output-min output-max value)
(let ((in-magnitude (- input-max input-min))
(out-magnitude (- output-max output-min)))
(let ((norm
(cond ((<= value input-min)
0.0)
((<= input-max value)
1.0)
(t
(float (/ (- value input-min) in-magnitude))))))
(+ output-min (* (sin (* pi norm)) norm out-magnitude)))) )
(defun remapper (ilerp-fun min max)
(let ((magnitude (- max min)))
(lambda (value)
(+ min (* magnitude (funcall ilerp-fun value))))))
(defun revmapper (ilerp-fun min max)
(let ((magnitude (- max min)))
(lambda (value)
(- max (* magnitude (funcall ilerp-fun value))))))
(defun test-hex (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(p (centerpoint canvas))
(radius 25))
(declare (ignore ds))
(with-box-canvas canvas
(set-fill-color (hsv-color 45 1.0 1.0))
(clear-canvas)
(set-line-width 3)
(set-line-join :round)
(let* ((ilerp (ilerper 0 (distance p (minpoint canvas))))
(revmap (remapper ilerp 0.5 1.0))
(thickmap (revmapper ilerp 2 4)))
(call-for-hex-centerpoints (lambda (p)
(let ((mag (distance p (centerpoint canvas))))
(set-line-width (funcall thickmap mag))
(hex-path p
(* radius
0.9
(funcall revmap mag))))
(stroke))
canvas
radius))
(save-png file))
#+nil
(output-data-stream ds file)))
(defun test-hex-animation (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(p (centerpoint canvas))
(radius 15)
(frames 48)
(anglestep (/ (* pi 2) frames)))
(with-box-canvas canvas
(set-fill-color (hsv-color 45 0.0 0.5))
(dotimes (i frames)
(clear-canvas)
(set-line-width 3)
(set-line-join :round)
(let* ((ilerp (ilerper 0 256))
(revmap (remapper ilerp 0.25 1.0))
(colormap (revmapper ilerp 0 360))
(thickmap (revmapper ilerp 1 1))
(refpoint (add p
(apoint (* anglestep i) 100))))
(call-for-hex-centerpoints (lambda (p)
(with-graphics-state
(let* ((mag (distance p refpoint))
(fill-color
(hsv-color (funcall colormap mag)
(funcall ilerp mag)
0.5))
(stroke-color
(hsv-color (funcall colormap mag)
(funcall ilerp mag)
0.25)))
(set-line-width (funcall thickmap mag))
(set-stroke-color stroke-color)
(set-fill-color fill-color)
(hex-path p
(* radius
0.9
(funcall revmap mag)))
(fill-and-stroke))))
canvas
radius))
(add-image (vimage-gif-image :delay-time 7) ds)))
(output-data-stream ds file)))
(defmacro do-hexes ((centerpoint canvas radius) &body body)
`(call-for-hex-centerpoints (lambda (,centerpoint) ,@body)
,canvas ,radius))
(defun hexleg (radius)
(let ((halfradius (/ radius 2)))
(sqrt (- (* radius radius)
(* halfradius halfradius)))))
(defun jitter (value magnitude)
(+ value (- magnitude (random (* 2 magnitude)))))
(defun test-hex-overlap-animation (file)
(let* ((canvas (box 0 0 512 512))
(ds (make-data-stream :width (vectometry:width canvas)
:height (vectometry:height canvas)
:loopingp t))
(radius 48)
(r/2 (/ radius 2))
(j (/ radius 20.0))
(frames 48)
(red (hsv-color 0 1 1))
(green (hsv-color 120 1 1))
(blue (hsv-color 240 1 1)))
(with-box-canvas canvas
(setf (vecto::blend-style vecto::*graphics-state*) :add)
(dotimes (i frames)
(let ((horizontal-displacement (remap-sine 0 frames
0 (* 3 radius)
i))
(vertical-displacement (remap-sine 0 frames
0 (* 2 (hexleg radius))
i)))
(set-fill-color *black*)
(clear-canvas)
(set-line-width 2)
(do-hexes (hex canvas radius)
(set-fill-color red)
(centered-circle-path (add hex
(point (jitter 0 j)
(jitter vertical-displacement j)))
r/2)
(fill-path))
(do-hexes (hex canvas radius)
(set-fill-color green)
(centered-circle-path (add hex
(point (jitter 0 j)
(jitter (- vertical-displacement) j)))
r/2)
(fill-path))
(do-hexes (hex canvas radius)
(set-fill-color blue)
(centered-circle-path (add hex
(point (jitter horizontal-displacement j)
(jitter 0 j)))
r/2)
(fill-path)))
(add-image (vimage-gif-image :delay-time (+ 7 (if (zerop i) 25 0))) ds)))
(output-data-stream ds file)))
|
8259b99df875b9d5b3f4968cae31230519d30bd5ee5f98a9dc71f46d3e0c3bdd | manetu/temporal-clojure-sdk | env.clj | Copyright © 2022 , Inc. All rights reserved
(ns temporal.testing.env
"Methods and utilities to assist with unit-testing Temporal workflows"
(:require [temporal.client.worker :as worker]
[temporal.internal.utils :as u])
(:import [io.temporal.testing TestWorkflowEnvironment]))
(defn create
"
Creates a mock Temporal backend, suitable for unit testing.
A worker may be created with [[start]] and a client may be connected with [[get-client]]
"
[]
(TestWorkflowEnvironment/newInstance))
(defn start
"
Starts a Temporal worker associated with the mock environment created with [[create]].
Arguments:
- `options`: See [[temporal.client.worker/worker-options]]
```clojure
(let [env (create)]
(start env {:task-queue ::my-queue :ctx {:some \"context\"}})
;; create and invoke workflows
(stop env))
```
"
[env {:keys [task-queue] :as options}]
(let [worker (.newWorker env (u/namify task-queue))]
(worker/init worker options)
(.start env)
:ok))
(defn stop
"
Stops the test environment created by [[create]]. Does not wait for shutdown to complete. For coordinated shutdown,
see [[synchronized-stop]].
```clojure
(stop instance)
```
"
[^TestWorkflowEnvironment env]
(.shutdown env))
(defn synchronized-stop
"
Stops the test environment created by [[create]]. Blocks until the environment has shut down. For async termination,
see [[stop]]
```clojure
(synchronized-stop instance)
```
"
[^TestWorkflowEnvironment env]
(.close env))
(defn get-client
"Returns a client instance associated with the mock environment created by [[create]]"
[env]
(.getWorkflowClient env))
| null | https://raw.githubusercontent.com/manetu/temporal-clojure-sdk/aa148b656c523d95b6b377081aa8c2ae68b32828/src/temporal/testing/env.clj | clojure | create and invoke workflows | Copyright © 2022 , Inc. All rights reserved
(ns temporal.testing.env
"Methods and utilities to assist with unit-testing Temporal workflows"
(:require [temporal.client.worker :as worker]
[temporal.internal.utils :as u])
(:import [io.temporal.testing TestWorkflowEnvironment]))
(defn create
"
Creates a mock Temporal backend, suitable for unit testing.
A worker may be created with [[start]] and a client may be connected with [[get-client]]
"
[]
(TestWorkflowEnvironment/newInstance))
(defn start
"
Starts a Temporal worker associated with the mock environment created with [[create]].
Arguments:
- `options`: See [[temporal.client.worker/worker-options]]
```clojure
(let [env (create)]
(start env {:task-queue ::my-queue :ctx {:some \"context\"}})
(stop env))
```
"
[env {:keys [task-queue] :as options}]
(let [worker (.newWorker env (u/namify task-queue))]
(worker/init worker options)
(.start env)
:ok))
(defn stop
"
Stops the test environment created by [[create]]. Does not wait for shutdown to complete. For coordinated shutdown,
see [[synchronized-stop]].
```clojure
(stop instance)
```
"
[^TestWorkflowEnvironment env]
(.shutdown env))
(defn synchronized-stop
"
Stops the test environment created by [[create]]. Blocks until the environment has shut down. For async termination,
see [[stop]]
```clojure
(synchronized-stop instance)
```
"
[^TestWorkflowEnvironment env]
(.close env))
(defn get-client
"Returns a client instance associated with the mock environment created by [[create]]"
[env]
(.getWorkflowClient env))
|
f40c798f99117c12245da099544fec3fbaaa918dbe27c53dded5c6e06ce1b4f3 | mzp/coq-ruby | extract_env.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : extract_env.mli 10895 2008 - 05 - 07 16:06:26Z letouzey $ i
(*s This module declares the extraction commands. *)
open Names
open Libnames
val simple_extraction : reference -> unit
val full_extraction : string option -> reference list -> unit
val extraction_library : bool -> identifier -> unit
(* For debug / external output via coqtop.byte + Drop : *)
val mono_environment :
global_reference list -> module_path list -> Miniml.ml_structure
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/contrib/extraction/extract_env.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
s This module declares the extraction commands.
For debug / external output via coqtop.byte + Drop : | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : extract_env.mli 10895 2008 - 05 - 07 16:06:26Z letouzey $ i
open Names
open Libnames
val simple_extraction : reference -> unit
val full_extraction : string option -> reference list -> unit
val extraction_library : bool -> identifier -> unit
val mono_environment :
global_reference list -> module_path list -> Miniml.ml_structure
|
d312f06cb87e861a012ba100a441219d88e1dcd7fcb3f16cade66ac26933106e | sapur/hexe | Hexe.hs | # LANGUAGE RecordWildCards #
module Hexe (hexeMain) where
import Control.Exception
import Control.Monad
import Data.Maybe
import System.Directory
import System.FilePath
import System.IO
import Text.Printf
import Graphics.Vty hiding (update, setMode)
import Command.Execute
import Command.Parser
import Control
import Editor
import Helpers
import Keymap
import Keymap.Default
import Keymap.Render
import Options
import qualified Buffer as Buf
hexeMain version gdf = run gdf =<< parseOptions version
run :: (String -> IO String) -> Options -> IO ()
run getDataFileName opts@Options{..} = action `catch` exception where
action = do
buf <- case optAction of
Edit file -> do
eiBuffer <- try $ Buf.readFile file
case eiBuffer of
Right buf ->
return buf
Left ex -> do
let _ = ex :: IOException
return $ Buf.mkBuffer file
_ -> return $ Buf.mkBuffer "unnamed"
let check fileM = do
file <- fileM
b <- doesFileExist file
return $ if b then Just file else Nothing
globalCfg <- check $ getDataFileName "config"
userCfg <- check $ (</> "config") <$> getXdgDirectory XdgConfig "hexe"
let files = catMaybes $ globalCfg : userCfg : map Just optScripts
pScripts <- forM files $ \fn -> do
raw <- readFile fn
return $ parseScript fn raw
let pCdl = mapM (parseScript "<ARG>") optCommands
pCmds = (++) <$> sequence pScripts <*> pCdl
case pCmds of
Left err ->
hPrint stderr err
Right scripts -> do
let cmds = concat scripts
runUI buf opts cmds
exception =
hPutStrLn stderr . formatIOEx
runUI buf Options{..} cmds = do
cfg <- standardIOConfig
vty <- mkVty cfg
ed0 <- mkEditor vty buf defaultKeymaps
EditorState ed1 _ <- (`execCommand` mkEditorState ed0) $ do
when (Buf.length buf == 0)
$ setMode HexInsert
(twdt,_) <- displayBounds $ outputIface vty
setColumnWdtAbs $ if twdt == 80 then 4 else 1
let colors = contextColorCount $ outputIface vty
when (colors <= 16) $ setStyle color16
-- defaults above --
executeScript cmds
-- command-line arguments below --
let ifSet o a = maybe (return ()) a o
ifSet optColumnWdt setColumnWdtAbs
ifSet opt256Colors $ setStyle . \b -> if b then color256 else color16
ifSet optCursor $ withEditor . setCursor
let marks = map (\o -> (o, Just "")) optMarks
++ map (\(o,t) -> (o, Just t )) optNamedMarks
forM_ marks $ \(offset, text) -> do
withEditor $ setCursor offset
setMark text
showNotice $ printf "Loaded '%s'." (Buf.bufPath buf)
finalCmd <- case optAction of
Edit _ -> do
eiEx <- try $ mainLoop ed1
return $ case eiEx of
Left ex -> hPrint stderr (ex :: SomeException)
Right _ -> return ()
ListKeymap ->
return $ putStr $ renderKeymapByMode $ edKeymaps ed1
ListBindings ->
return $ putStr $ renderKeymapByCategory $ edKeymaps ed1
shutdown vty
finalCmd
mainLoop ed0 = do
renderView ed0
let vty = edVty ed0
ed1 = clearMessage ed0
nextEvent vty >>= \ev -> case ev of
EvKey (KChar 'q') [MCtrl] ->
return ()
EvKey (KChar 'l') [MCtrl] -> do
refresh vty
mainLoop ed1
EvResize wdt hgt ->
mainLoop (reshape wdt hgt ed1)
ev -> do
let cmd = lookupScript ev (edMode ed1) $ edKeymaps ed1
EditorState ed2 bQuit <- execCommand cmd (mkEditorState ed1)
let ed3 = updateInfo ed2
unless bQuit (mainLoop ed3)
| null | https://raw.githubusercontent.com/sapur/hexe/e01036a1f8213938f9e1c72afc6aff48ba7fb0fd/src/Hexe.hs | haskell | defaults above --
command-line arguments below -- | # LANGUAGE RecordWildCards #
module Hexe (hexeMain) where
import Control.Exception
import Control.Monad
import Data.Maybe
import System.Directory
import System.FilePath
import System.IO
import Text.Printf
import Graphics.Vty hiding (update, setMode)
import Command.Execute
import Command.Parser
import Control
import Editor
import Helpers
import Keymap
import Keymap.Default
import Keymap.Render
import Options
import qualified Buffer as Buf
hexeMain version gdf = run gdf =<< parseOptions version
run :: (String -> IO String) -> Options -> IO ()
run getDataFileName opts@Options{..} = action `catch` exception where
action = do
buf <- case optAction of
Edit file -> do
eiBuffer <- try $ Buf.readFile file
case eiBuffer of
Right buf ->
return buf
Left ex -> do
let _ = ex :: IOException
return $ Buf.mkBuffer file
_ -> return $ Buf.mkBuffer "unnamed"
let check fileM = do
file <- fileM
b <- doesFileExist file
return $ if b then Just file else Nothing
globalCfg <- check $ getDataFileName "config"
userCfg <- check $ (</> "config") <$> getXdgDirectory XdgConfig "hexe"
let files = catMaybes $ globalCfg : userCfg : map Just optScripts
pScripts <- forM files $ \fn -> do
raw <- readFile fn
return $ parseScript fn raw
let pCdl = mapM (parseScript "<ARG>") optCommands
pCmds = (++) <$> sequence pScripts <*> pCdl
case pCmds of
Left err ->
hPrint stderr err
Right scripts -> do
let cmds = concat scripts
runUI buf opts cmds
exception =
hPutStrLn stderr . formatIOEx
runUI buf Options{..} cmds = do
cfg <- standardIOConfig
vty <- mkVty cfg
ed0 <- mkEditor vty buf defaultKeymaps
EditorState ed1 _ <- (`execCommand` mkEditorState ed0) $ do
when (Buf.length buf == 0)
$ setMode HexInsert
(twdt,_) <- displayBounds $ outputIface vty
setColumnWdtAbs $ if twdt == 80 then 4 else 1
let colors = contextColorCount $ outputIface vty
when (colors <= 16) $ setStyle color16
executeScript cmds
let ifSet o a = maybe (return ()) a o
ifSet optColumnWdt setColumnWdtAbs
ifSet opt256Colors $ setStyle . \b -> if b then color256 else color16
ifSet optCursor $ withEditor . setCursor
let marks = map (\o -> (o, Just "")) optMarks
++ map (\(o,t) -> (o, Just t )) optNamedMarks
forM_ marks $ \(offset, text) -> do
withEditor $ setCursor offset
setMark text
showNotice $ printf "Loaded '%s'." (Buf.bufPath buf)
finalCmd <- case optAction of
Edit _ -> do
eiEx <- try $ mainLoop ed1
return $ case eiEx of
Left ex -> hPrint stderr (ex :: SomeException)
Right _ -> return ()
ListKeymap ->
return $ putStr $ renderKeymapByMode $ edKeymaps ed1
ListBindings ->
return $ putStr $ renderKeymapByCategory $ edKeymaps ed1
shutdown vty
finalCmd
mainLoop ed0 = do
renderView ed0
let vty = edVty ed0
ed1 = clearMessage ed0
nextEvent vty >>= \ev -> case ev of
EvKey (KChar 'q') [MCtrl] ->
return ()
EvKey (KChar 'l') [MCtrl] -> do
refresh vty
mainLoop ed1
EvResize wdt hgt ->
mainLoop (reshape wdt hgt ed1)
ev -> do
let cmd = lookupScript ev (edMode ed1) $ edKeymaps ed1
EditorState ed2 bQuit <- execCommand cmd (mkEditorState ed1)
let ed3 = updateInfo ed2
unless bQuit (mainLoop ed3)
|
17bb198dbee0fc50614ac80b939ef391395c856f542b678bf48876b7a03e4cd2 | ghcjs/ghcjs-dom | SpeechRecognition.hs | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.SpeechRecognition
(newSpeechRecognition, getMaxAlternatives, setMaxAlternatives,
getGrammars, setGrammars, getLang, setLang,
getInterimResults, setInterimResults,
getContinuous, setContinuous,
audiostart, audioend, end, error, nomatch,
result, soundstart, soundend, speechstart, speechend, start,
abort, startRecognition, stop,
SpeechRecognition(..), gTypeSpeechRecognition)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"new window[\"webkitSpeechRecognition\"]()"
js_newSpeechRecognition :: IO SpeechRecognition
-- | <-US/docs/Web/API/SpeechRecognition Mozilla SpeechRecognition documentation>
newSpeechRecognition :: (MonadIO m) => m SpeechRecognition
newSpeechRecognition = liftIO (js_newSpeechRecognition)
foreign import javascript unsafe
"$1[\"maxAlternatives\"]"
js_speechRecognitionGetMaxAlternatives ::
SpeechRecognition -> IO (Word)
| < -US/docs/Web/API/SpeechRecognition.maxAlternatives Mozilla SpeechRecognition.maxAlternatives documentation >
getMaxAlternatives :: (MonadIO m)
=> SpeechRecognition -> m Word
getMaxAlternatives self
= liftIO (js_speechRecognitionGetMaxAlternatives self)
foreign import javascript unsafe
"$1[\"maxAlternatives\"] = $2;"
js_speechRecognitionMaxAlternatives ::
SpeechRecognition -> Word -> IO ()
| < -US/docs/Web/API/SpeechRecognition.maxAlternatives Mozilla SpeechRecognition.maxAlternatives documentation >
setMaxAlternatives :: (MonadIO m)
=> SpeechRecognition -> Word -> m ()
setMaxAlternatives self maxAlt
= liftIO (js_speechRecognitionMaxAlternatives self maxAlt)
foreign import javascript unsafe
"$1[\"grammars\"]"
js_speechRecognitionGetGrammars ::
SpeechRecognition -> IO SpeechGrammarList
-- | <-US/docs/Web/API/SpeechRecognition.grammars Mozilla SpeechRecognition.grammars documentation>
getGrammars :: (MonadIO m)
=> SpeechRecognition -> m (SpeechGrammarList)
getGrammars self
= liftIO (js_speechRecognitionGetGrammars self)
foreign import javascript unsafe
"$1[\"grammars\"] = $2;"
js_speechRecognitionSetGrammars ::
SpeechRecognition -> SpeechGrammarList -> IO ()
-- | <-US/docs/Web/API/SpeechRecognition.grammars Mozilla SpeechRecognition.grammars documentation>
setGrammars :: (MonadIO m)
=> SpeechRecognition -> SpeechGrammarList -> m ()
setGrammars self grammars
= liftIO (js_speechRecognitionSetGrammars self grammars)
foreign import javascript unsafe
"$1[\"lang\"]"
js_speechRecognitionGetLang ::
SpeechRecognition -> IO JSString
| < -US/docs/Web/API/SpeechRecognition.lang Mozilla SpeechRecognition.lang documentation >
getLang :: (MonadIO m, FromJSString result)
=> SpeechRecognition -> m (result)
getLang self
= liftIO (fromJSString <$> (js_speechRecognitionGetLang self))
foreign import javascript unsafe
"$1[\"lang\"] = $2;"
js_speechRecognitionSetLang ::
SpeechRecognition -> JSString -> IO ()
| < -US/docs/Web/API/SpeechRecognition.lang Mozilla SpeechRecognition.lang documentation >
setLang :: (MonadIO m, ToJSString lang)
=> SpeechRecognition -> lang -> m ()
setLang self lang
= liftIO (js_speechRecognitionSetLang self (toJSString lang))
foreign import javascript unsafe
"$1[\"interimResults\"]"
js_speechRecognitionGetInterimResults ::
SpeechRecognition -> IO Bool
| < -US/docs/Web/API/SpeechRecognition.interimResults Mozilla SpeechRecognition.interimResults documentation >
getInterimResults :: (MonadIO m)
=> SpeechRecognition -> m (Bool)
getInterimResults self
= liftIO (js_speechRecognitionGetInterimResults self)
foreign import javascript unsafe
"$1[\"interimResults\"] = $2;"
js_speechRecognitionSetInterimResults ::
SpeechRecognition -> Bool -> IO ()
| < -US/docs/Web/API/SpeechRecognition.interimResults Mozilla SpeechRecognition.interimResults documentation >
setInterimResults :: (MonadIO m)
=> SpeechRecognition -> Bool -> m ()
setInterimResults self val
= liftIO (js_speechRecognitionSetInterimResults self val)
foreign import javascript unsafe
"$1[\"continuous\"]"
js_speechRecognitionGetContinuous ::
SpeechRecognition -> IO Bool
| < -US/docs/Web/API/SpeechRecognition.continuous Mozilla SpeechRecognition.continuous documentation >
getContinuous :: (MonadIO m)
=> SpeechRecognition -> m (Bool)
getContinuous self
= liftIO (js_speechRecognitionGetContinuous self)
foreign import javascript unsafe
"$1[\"continuous\"] = $2;"
js_speechRecognitionSetContinuous ::
SpeechRecognition -> Bool -> IO ()
| < -US/docs/Web/API/SpeechRecognition.continuous Mozilla SpeechRecognition.continuous documentation >
setContinuous :: (MonadIO m)
=> SpeechRecognition -> Bool -> m ()
setContinuous self val
= liftIO (js_speechRecognitionSetContinuous self val)
| < -US/docs/Web/API/SpeechRecognition.onaudiostart Mozilla SpeechRecognition.onaudiostart documentation >
audiostart :: EventName SpeechRecognition Event
audiostart = unsafeEventName (toJSString "audiostart")
-- | <-US/docs/Web/API/SpeechRecognition.onaudioend Mozilla SpeechRecognition.onaudioend documentation>
audioend :: EventName SpeechRecognition Event
audioend = unsafeEventName (toJSString "audioend")
| < -US/docs/Web/API/SpeechRecognition.onend Mozilla SpeechRecognition.onend documentation >
end :: EventName SpeechRecognition Event
end = unsafeEventName (toJSString "end")
-- | <-US/docs/Web/API/SpeechRecognition.onerror Mozilla SpeechRecognition.onerror documentation>
error :: EventName SpeechRecognition SpeechRecognitionError
error = unsafeEventName (toJSString "error")
| < -US/docs/Web/API/SpeechRecognition.onnomatch Mozilla SpeechRecognition.onnomatch documentation >
nomatch :: EventName SpeechRecognition SpeechRecognitionEvent
nomatch = unsafeEventName (toJSString "nomatch")
-- | <-US/docs/Web/API/SpeechRecognition.onresult Mozilla SpeechRecognition.onresult documentation>
result :: EventName SpeechRecognition SpeechRecognitionEvent
result = unsafeEventName (toJSString "result")
-- | <-US/docs/Web/API/SpeechRecognition.onsoundstart Mozilla SpeechRecognition.onsoundstart documentation>
soundstart :: EventName SpeechRecognition Event
soundstart = unsafeEventName (toJSString "soundstart")
| < -US/docs/Web/API/SpeechRecognition.onsoundend Mozilla SpeechRecognition.onsoundend documentation >
soundend :: EventName SpeechRecognition Event
soundend = unsafeEventName (toJSString "soundend")
-- | <-US/docs/Web/API/SpeechRecognition.onspeechstart Mozilla SpeechRecognition.onspeechstart documentation>
speechstart :: EventName SpeechRecognition Event
speechstart = unsafeEventName (toJSString "speechstart")
-- | <-US/docs/Web/API/SpeechRecognition.onspeechend Mozilla SpeechRecognition.onspeechend documentation>
speechend :: EventName SpeechRecognition Event
speechend = unsafeEventName (toJSString "speechend")
| < -US/docs/Web/API/SpeechRecognition.onstart Mozilla SpeechRecognition.onstart documentation >
start :: EventName SpeechRecognition Event
start = unsafeEventName (toJSString "start")
foreign import javascript unsafe
"$1[\"abort\"]()"
js_speechRecognitionAbort ::
SpeechRecognition -> IO ()
| < -US/docs/Web/API/SpeechRecognition.abort Mozilla SpeechRecognition.abort documentation >
abort :: (MonadIO m)
=> SpeechRecognition -> m ()
abort self
= liftIO (js_speechRecognitionAbort self)
foreign import javascript unsafe
"$1[\"start\"]()"
js_speechRecognitionStart ::
SpeechRecognition -> IO ()
-- | <-US/docs/Web/API/SpeechRecognition.start Mozilla SpeechRecognition.start documentation>
startRecognition :: (MonadIO m)
=> SpeechRecognition -> m ()
startRecognition self
= liftIO (js_speechRecognitionStart self)
foreign import javascript unsafe
"$1[\"stop\"]()"
js_speechRecognitionStop ::
SpeechRecognition -> IO ()
-- | <-US/docs/Web/API/SpeechRecognition.stop Mozilla SpeechRecognition.stop documentation>
stop :: (MonadIO m)
=> SpeechRecognition -> m ()
stop self
= liftIO (js_speechRecognitionStop self)
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/SpeechRecognition.hs | haskell | | <-US/docs/Web/API/SpeechRecognition Mozilla SpeechRecognition documentation>
| <-US/docs/Web/API/SpeechRecognition.grammars Mozilla SpeechRecognition.grammars documentation>
| <-US/docs/Web/API/SpeechRecognition.grammars Mozilla SpeechRecognition.grammars documentation>
| <-US/docs/Web/API/SpeechRecognition.onaudioend Mozilla SpeechRecognition.onaudioend documentation>
| <-US/docs/Web/API/SpeechRecognition.onerror Mozilla SpeechRecognition.onerror documentation>
| <-US/docs/Web/API/SpeechRecognition.onresult Mozilla SpeechRecognition.onresult documentation>
| <-US/docs/Web/API/SpeechRecognition.onsoundstart Mozilla SpeechRecognition.onsoundstart documentation>
| <-US/docs/Web/API/SpeechRecognition.onspeechstart Mozilla SpeechRecognition.onspeechstart documentation>
| <-US/docs/Web/API/SpeechRecognition.onspeechend Mozilla SpeechRecognition.onspeechend documentation>
| <-US/docs/Web/API/SpeechRecognition.start Mozilla SpeechRecognition.start documentation>
| <-US/docs/Web/API/SpeechRecognition.stop Mozilla SpeechRecognition.stop documentation> | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.SpeechRecognition
(newSpeechRecognition, getMaxAlternatives, setMaxAlternatives,
getGrammars, setGrammars, getLang, setLang,
getInterimResults, setInterimResults,
getContinuous, setContinuous,
audiostart, audioend, end, error, nomatch,
result, soundstart, soundend, speechstart, speechend, start,
abort, startRecognition, stop,
SpeechRecognition(..), gTypeSpeechRecognition)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"new window[\"webkitSpeechRecognition\"]()"
js_newSpeechRecognition :: IO SpeechRecognition
newSpeechRecognition :: (MonadIO m) => m SpeechRecognition
newSpeechRecognition = liftIO (js_newSpeechRecognition)
foreign import javascript unsafe
"$1[\"maxAlternatives\"]"
js_speechRecognitionGetMaxAlternatives ::
SpeechRecognition -> IO (Word)
| < -US/docs/Web/API/SpeechRecognition.maxAlternatives Mozilla SpeechRecognition.maxAlternatives documentation >
getMaxAlternatives :: (MonadIO m)
=> SpeechRecognition -> m Word
getMaxAlternatives self
= liftIO (js_speechRecognitionGetMaxAlternatives self)
foreign import javascript unsafe
"$1[\"maxAlternatives\"] = $2;"
js_speechRecognitionMaxAlternatives ::
SpeechRecognition -> Word -> IO ()
| < -US/docs/Web/API/SpeechRecognition.maxAlternatives Mozilla SpeechRecognition.maxAlternatives documentation >
setMaxAlternatives :: (MonadIO m)
=> SpeechRecognition -> Word -> m ()
setMaxAlternatives self maxAlt
= liftIO (js_speechRecognitionMaxAlternatives self maxAlt)
foreign import javascript unsafe
"$1[\"grammars\"]"
js_speechRecognitionGetGrammars ::
SpeechRecognition -> IO SpeechGrammarList
getGrammars :: (MonadIO m)
=> SpeechRecognition -> m (SpeechGrammarList)
getGrammars self
= liftIO (js_speechRecognitionGetGrammars self)
foreign import javascript unsafe
"$1[\"grammars\"] = $2;"
js_speechRecognitionSetGrammars ::
SpeechRecognition -> SpeechGrammarList -> IO ()
setGrammars :: (MonadIO m)
=> SpeechRecognition -> SpeechGrammarList -> m ()
setGrammars self grammars
= liftIO (js_speechRecognitionSetGrammars self grammars)
foreign import javascript unsafe
"$1[\"lang\"]"
js_speechRecognitionGetLang ::
SpeechRecognition -> IO JSString
| < -US/docs/Web/API/SpeechRecognition.lang Mozilla SpeechRecognition.lang documentation >
getLang :: (MonadIO m, FromJSString result)
=> SpeechRecognition -> m (result)
getLang self
= liftIO (fromJSString <$> (js_speechRecognitionGetLang self))
foreign import javascript unsafe
"$1[\"lang\"] = $2;"
js_speechRecognitionSetLang ::
SpeechRecognition -> JSString -> IO ()
| < -US/docs/Web/API/SpeechRecognition.lang Mozilla SpeechRecognition.lang documentation >
setLang :: (MonadIO m, ToJSString lang)
=> SpeechRecognition -> lang -> m ()
setLang self lang
= liftIO (js_speechRecognitionSetLang self (toJSString lang))
foreign import javascript unsafe
"$1[\"interimResults\"]"
js_speechRecognitionGetInterimResults ::
SpeechRecognition -> IO Bool
| < -US/docs/Web/API/SpeechRecognition.interimResults Mozilla SpeechRecognition.interimResults documentation >
getInterimResults :: (MonadIO m)
=> SpeechRecognition -> m (Bool)
getInterimResults self
= liftIO (js_speechRecognitionGetInterimResults self)
foreign import javascript unsafe
"$1[\"interimResults\"] = $2;"
js_speechRecognitionSetInterimResults ::
SpeechRecognition -> Bool -> IO ()
| < -US/docs/Web/API/SpeechRecognition.interimResults Mozilla SpeechRecognition.interimResults documentation >
setInterimResults :: (MonadIO m)
=> SpeechRecognition -> Bool -> m ()
setInterimResults self val
= liftIO (js_speechRecognitionSetInterimResults self val)
foreign import javascript unsafe
"$1[\"continuous\"]"
js_speechRecognitionGetContinuous ::
SpeechRecognition -> IO Bool
| < -US/docs/Web/API/SpeechRecognition.continuous Mozilla SpeechRecognition.continuous documentation >
getContinuous :: (MonadIO m)
=> SpeechRecognition -> m (Bool)
getContinuous self
= liftIO (js_speechRecognitionGetContinuous self)
foreign import javascript unsafe
"$1[\"continuous\"] = $2;"
js_speechRecognitionSetContinuous ::
SpeechRecognition -> Bool -> IO ()
| < -US/docs/Web/API/SpeechRecognition.continuous Mozilla SpeechRecognition.continuous documentation >
setContinuous :: (MonadIO m)
=> SpeechRecognition -> Bool -> m ()
setContinuous self val
= liftIO (js_speechRecognitionSetContinuous self val)
| < -US/docs/Web/API/SpeechRecognition.onaudiostart Mozilla SpeechRecognition.onaudiostart documentation >
audiostart :: EventName SpeechRecognition Event
audiostart = unsafeEventName (toJSString "audiostart")
audioend :: EventName SpeechRecognition Event
audioend = unsafeEventName (toJSString "audioend")
| < -US/docs/Web/API/SpeechRecognition.onend Mozilla SpeechRecognition.onend documentation >
end :: EventName SpeechRecognition Event
end = unsafeEventName (toJSString "end")
error :: EventName SpeechRecognition SpeechRecognitionError
error = unsafeEventName (toJSString "error")
| < -US/docs/Web/API/SpeechRecognition.onnomatch Mozilla SpeechRecognition.onnomatch documentation >
nomatch :: EventName SpeechRecognition SpeechRecognitionEvent
nomatch = unsafeEventName (toJSString "nomatch")
result :: EventName SpeechRecognition SpeechRecognitionEvent
result = unsafeEventName (toJSString "result")
soundstart :: EventName SpeechRecognition Event
soundstart = unsafeEventName (toJSString "soundstart")
| < -US/docs/Web/API/SpeechRecognition.onsoundend Mozilla SpeechRecognition.onsoundend documentation >
soundend :: EventName SpeechRecognition Event
soundend = unsafeEventName (toJSString "soundend")
speechstart :: EventName SpeechRecognition Event
speechstart = unsafeEventName (toJSString "speechstart")
speechend :: EventName SpeechRecognition Event
speechend = unsafeEventName (toJSString "speechend")
| < -US/docs/Web/API/SpeechRecognition.onstart Mozilla SpeechRecognition.onstart documentation >
start :: EventName SpeechRecognition Event
start = unsafeEventName (toJSString "start")
foreign import javascript unsafe
"$1[\"abort\"]()"
js_speechRecognitionAbort ::
SpeechRecognition -> IO ()
| < -US/docs/Web/API/SpeechRecognition.abort Mozilla SpeechRecognition.abort documentation >
abort :: (MonadIO m)
=> SpeechRecognition -> m ()
abort self
= liftIO (js_speechRecognitionAbort self)
foreign import javascript unsafe
"$1[\"start\"]()"
js_speechRecognitionStart ::
SpeechRecognition -> IO ()
startRecognition :: (MonadIO m)
=> SpeechRecognition -> m ()
startRecognition self
= liftIO (js_speechRecognitionStart self)
foreign import javascript unsafe
"$1[\"stop\"]()"
js_speechRecognitionStop ::
SpeechRecognition -> IO ()
stop :: (MonadIO m)
=> SpeechRecognition -> m ()
stop self
= liftIO (js_speechRecognitionStop self)
|
a443b6760052e24a386fc04a63fbedbc035f3d92a5a3f57aeeab6969db5539e9 | cpeikert/Lol | Benchmarks.hs | |
Module : Crypto . Lol . Applications . Examples
Description : Benchmarks for cryptographic applications .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Tensor - polymorphic benchmarks for cryptographic applications . Note that
benchmarks for HomomPRF are included in the example .
Module : Crypto.Lol.Applications.Examples
Description : Benchmarks for cryptographic applications.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Tensor-polymorphic benchmarks for cryptographic applications. Note that
benchmarks for HomomPRF are included in the example.
-}
module Crypto.Lol.Applications.Benchmarks
( module Crypto.Lol.Applications.Benchmarks.Default
, module Crypto.Lol.Applications.Benchmarks.BGVBenches
, module Crypto.Lol.Applications.Benchmarks.KHPRFBenches
) where
import Crypto.Lol.Applications.Benchmarks.Default
import Crypto.Lol.Applications.Benchmarks.BGVBenches
import Crypto.Lol.Applications.Benchmarks.KHPRFBenches
| null | https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol-apps/Crypto/Lol/Applications/Benchmarks.hs | haskell | |
Module : Crypto . Lol . Applications . Examples
Description : Benchmarks for cryptographic applications .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Tensor - polymorphic benchmarks for cryptographic applications . Note that
benchmarks for HomomPRF are included in the example .
Module : Crypto.Lol.Applications.Examples
Description : Benchmarks for cryptographic applications.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Tensor-polymorphic benchmarks for cryptographic applications. Note that
benchmarks for HomomPRF are included in the example.
-}
module Crypto.Lol.Applications.Benchmarks
( module Crypto.Lol.Applications.Benchmarks.Default
, module Crypto.Lol.Applications.Benchmarks.BGVBenches
, module Crypto.Lol.Applications.Benchmarks.KHPRFBenches
) where
import Crypto.Lol.Applications.Benchmarks.Default
import Crypto.Lol.Applications.Benchmarks.BGVBenches
import Crypto.Lol.Applications.Benchmarks.KHPRFBenches
|
|
8fdf9b4359e9a6762b4640ef65eeac6ae31a09859bee96e3b9674ada713ee304 | serokell/tzbot | GetTimeshiftsSpec.hs | SPDX - FileCopyrightText : 2022 >
--
SPDX - License - Identifier : MPL-2.0
module Test.TzBot.GetTimeshiftsSpec
( test_getTimeshiftsSpec
, test_checkForTimeshifts
) where
import Universum
import Data.Time (UTCTime)
import Data.Time.TZInfo
import Data.Time.TZInfo qualified as TZI
import Data.Time.TZTime (toUTC)
import Data.Time.TZTime.QQ (tz)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))
import Text.Interpolation.Nyan
import TzBot.Parser (parseTimeRefs)
import TzBot.TZ (TimeShift(..), checkForTimeshifts, checkForTimeshifts')
import TzBot.TimeReference (TimeReferenceToUTCResult(..), timeReferenceToUTC)
import TzBot.Util
springHavana2022utc, autumnHavana2022utc, springHavana2023utc :: UTCTime
springHavana2022utc = toUTC [tz|2022-03-13 05:00:00 [UTC]|]
autumnHavana2022utc = toUTC [tz|2022-11-06 05:00:00 [UTC]|]
--
springHavana2023utc = toUTC [tz|2023-03-12 05:00:00 [UTC]|]
springHavana2022, autumnHavana2022, springHavana2023 :: TimeShift
springHavana2022 = TimeShift springHavana2022utc cst cdt (TZI.fromLabel America__Havana)
autumnHavana2022 = TimeShift autumnHavana2022utc cdt cst (TZI.fromLabel America__Havana)
springHavana2023 = TimeShift springHavana2023utc cst cdt (TZI.fromLabel America__Havana)
cst, cdt :: Offset
cst = Offset ((-5)*60)
cdt = Offset ((-4)*60)
test_getTimeshiftsSpec :: TestTree
test_getTimeshiftsSpec = testGroup "GetTimeshifts"
[ testCase "havana1" $ do
let t1 = toUTC [tz|2022-03-12 23:59:00 [America/Havana]|]
let t2 = toUTC [tz|2023-03-12 01:01:00 [America/Havana]|]
let ts = checkForTimeshifts' (TZI.fromLabel America__Havana) t1 t2
ts @?=
[springHavana2022, autumnHavana2022, springHavana2023]
, testCase "havana2" $ do
let t1 = toUTC [tz|2022-03-13 01:00:00 [America/Havana]|]
let t2 = toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]
let ts = checkForTimeshifts' (TZI.fromLabel America__Havana) t1 t2
ts @?=
[autumnHavana2022, springHavana2023]
, testCase "utc" $ do
let t1 = toUTC [tz|1900-01-01 01:00:00 [UTC]|]
let t2 = toUTC [tz|2024-03-12 01:00:00 [UTC]|]
let ts = checkForTimeshifts' (TZI.fromLabel Etc__UTC) t1 t2
ts @?= []
, testCase "incorrect arguments" $ do
let t1 = toUTC [tz|1900-01-01 01:00:00 [UTC]|]
let t2 = toUTC [tz|2024-03-12 01:00:00 [UTC]|]
let ts = checkForTimeshifts' (TZI.fromLabel Etc__UTC) t2 t1
ts @?= []
]
test_checkForTimeshifts :: TestTree
test_checkForTimeshifts =
testGroup "checkForTimeshifts"
[ testCase "When the date is not specified, check for offset changes up to 3 days after/before the inferred date" do
there 's an offset change 2 days and 23 hours before the inferred date / time .
--
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "23:00" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
there 's an offset change 3 days and 1 hour before , so we do n't return it .
check
(toUTC [tz|2023-03-15 00:00:00 [America/Havana]|]) "01:00" America__Havana
Europe__Lisbon
[]
there 's an offset change 2 days and 23 hours after the inferred date / time .
--
check
(toUTC [tz|2023-03-09 00:00:00 [America/Havana]|]) "00:00" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
there 's an offset change 3 days and 1 hour after , so we do n't return it .
check
(toUTC [tz|2023-03-08 00:00:00 [America/Havana]|]) "23:00" America__Havana
Europe__Lisbon
[]
, testCase "When the sender specifies a day of week, check for offset changes during the week before the inferred date" do
We will infer " 23:00 on Saturday " means 23:00 on 18 March .
There 's an offset change 6 days and 23 hours before the inferred date / time .
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "23:00 on Saturday" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
We will infer " 01:00 on Sunday " means 01:00 on 19 March .
There 's an offset change 7 days and 1 hour before the inferred date / time , so we do n't return it .
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "01:00 on Sunday" America__Havana
Europe__Lisbon
[]
We will infer " 23:00 on Saturday " means 01:00 on 11 March .
There 's an offset change 1 hour after the inferred date / time ,
-- but we only check for offset changes in the past, so we don't return anything.
check
(toUTC [tz|2023-03-11 00:00:00 [America/Havana]|]) "23:00 on Saturday" America__Havana
Europe__Lisbon
[]
]
where
check :: UTCTime -> Text -> TZLabel -> TZLabel -> [TimeShift] -> Assertion
check now input senderTimeZone receiverTimeZone expectedTimeShifts = do
case parseTimeRefs input of
[timeRef] ->
case timeReferenceToUTC senderTimeZone now timeRef of
TRTUSuccess timeRefSuccess ->
checkForTimeshifts timeRef timeRefSuccess receiverTimeZone @?= expectedTimeShifts
other ->
assertFailure
[int|s|
Expected 'timeReferenceToUTC' to success, but it failed:
#s{other}
|]
timeRefs ->
assertFailure
[int|s|
Expected 'parseTimeRefs' to return exactly 1 result, but it returned:
#s{timeRefs}
|]
| null | https://raw.githubusercontent.com/serokell/tzbot/ef9c80a941474703ff8ab5eabb782e09c63928a9/test/Test/TzBot/GetTimeshiftsSpec.hs | haskell |
but we only check for offset changes in the past, so we don't return anything. | SPDX - FileCopyrightText : 2022 >
SPDX - License - Identifier : MPL-2.0
module Test.TzBot.GetTimeshiftsSpec
( test_getTimeshiftsSpec
, test_checkForTimeshifts
) where
import Universum
import Data.Time (UTCTime)
import Data.Time.TZInfo
import Data.Time.TZInfo qualified as TZI
import Data.Time.TZTime (toUTC)
import Data.Time.TZTime.QQ (tz)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))
import Text.Interpolation.Nyan
import TzBot.Parser (parseTimeRefs)
import TzBot.TZ (TimeShift(..), checkForTimeshifts, checkForTimeshifts')
import TzBot.TimeReference (TimeReferenceToUTCResult(..), timeReferenceToUTC)
import TzBot.Util
springHavana2022utc, autumnHavana2022utc, springHavana2023utc :: UTCTime
springHavana2022utc = toUTC [tz|2022-03-13 05:00:00 [UTC]|]
autumnHavana2022utc = toUTC [tz|2022-11-06 05:00:00 [UTC]|]
springHavana2023utc = toUTC [tz|2023-03-12 05:00:00 [UTC]|]
springHavana2022, autumnHavana2022, springHavana2023 :: TimeShift
springHavana2022 = TimeShift springHavana2022utc cst cdt (TZI.fromLabel America__Havana)
autumnHavana2022 = TimeShift autumnHavana2022utc cdt cst (TZI.fromLabel America__Havana)
springHavana2023 = TimeShift springHavana2023utc cst cdt (TZI.fromLabel America__Havana)
cst, cdt :: Offset
cst = Offset ((-5)*60)
cdt = Offset ((-4)*60)
test_getTimeshiftsSpec :: TestTree
test_getTimeshiftsSpec = testGroup "GetTimeshifts"
[ testCase "havana1" $ do
let t1 = toUTC [tz|2022-03-12 23:59:00 [America/Havana]|]
let t2 = toUTC [tz|2023-03-12 01:01:00 [America/Havana]|]
let ts = checkForTimeshifts' (TZI.fromLabel America__Havana) t1 t2
ts @?=
[springHavana2022, autumnHavana2022, springHavana2023]
, testCase "havana2" $ do
let t1 = toUTC [tz|2022-03-13 01:00:00 [America/Havana]|]
let t2 = toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]
let ts = checkForTimeshifts' (TZI.fromLabel America__Havana) t1 t2
ts @?=
[autumnHavana2022, springHavana2023]
, testCase "utc" $ do
let t1 = toUTC [tz|1900-01-01 01:00:00 [UTC]|]
let t2 = toUTC [tz|2024-03-12 01:00:00 [UTC]|]
let ts = checkForTimeshifts' (TZI.fromLabel Etc__UTC) t1 t2
ts @?= []
, testCase "incorrect arguments" $ do
let t1 = toUTC [tz|1900-01-01 01:00:00 [UTC]|]
let t2 = toUTC [tz|2024-03-12 01:00:00 [UTC]|]
let ts = checkForTimeshifts' (TZI.fromLabel Etc__UTC) t2 t1
ts @?= []
]
test_checkForTimeshifts :: TestTree
test_checkForTimeshifts =
testGroup "checkForTimeshifts"
[ testCase "When the date is not specified, check for offset changes up to 3 days after/before the inferred date" do
there 's an offset change 2 days and 23 hours before the inferred date / time .
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "23:00" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
there 's an offset change 3 days and 1 hour before , so we do n't return it .
check
(toUTC [tz|2023-03-15 00:00:00 [America/Havana]|]) "01:00" America__Havana
Europe__Lisbon
[]
there 's an offset change 2 days and 23 hours after the inferred date / time .
check
(toUTC [tz|2023-03-09 00:00:00 [America/Havana]|]) "00:00" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
there 's an offset change 3 days and 1 hour after , so we do n't return it .
check
(toUTC [tz|2023-03-08 00:00:00 [America/Havana]|]) "23:00" America__Havana
Europe__Lisbon
[]
, testCase "When the sender specifies a day of week, check for offset changes during the week before the inferred date" do
We will infer " 23:00 on Saturday " means 23:00 on 18 March .
There 's an offset change 6 days and 23 hours before the inferred date / time .
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "23:00 on Saturday" America__Havana
Europe__Lisbon
[ TimeShift (toUTC [tz|2023-03-12 01:00:00 [America/Havana]|]) cst cdt (TZI.fromLabel America__Havana) ]
We will infer " 01:00 on Sunday " means 01:00 on 19 March .
There 's an offset change 7 days and 1 hour before the inferred date / time , so we do n't return it .
check
(toUTC [tz|2023-03-14 00:00:00 [America/Havana]|]) "01:00 on Sunday" America__Havana
Europe__Lisbon
[]
We will infer " 23:00 on Saturday " means 01:00 on 11 March .
There 's an offset change 1 hour after the inferred date / time ,
check
(toUTC [tz|2023-03-11 00:00:00 [America/Havana]|]) "23:00 on Saturday" America__Havana
Europe__Lisbon
[]
]
where
check :: UTCTime -> Text -> TZLabel -> TZLabel -> [TimeShift] -> Assertion
check now input senderTimeZone receiverTimeZone expectedTimeShifts = do
case parseTimeRefs input of
[timeRef] ->
case timeReferenceToUTC senderTimeZone now timeRef of
TRTUSuccess timeRefSuccess ->
checkForTimeshifts timeRef timeRefSuccess receiverTimeZone @?= expectedTimeShifts
other ->
assertFailure
[int|s|
Expected 'timeReferenceToUTC' to success, but it failed:
#s{other}
|]
timeRefs ->
assertFailure
[int|s|
Expected 'parseTimeRefs' to return exactly 1 result, but it returned:
#s{timeRefs}
|]
|
485be3261b7e43f578b057261f2e0b39bd5b944be7baf1d56c5b99d287de8b36 | jimpil/clambda | project.clj | (defproject clambda "0.1.6-SNAPSHOT"
:description "Utilities for working with Java Streams/Lambdas from Clojure."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies []
:profiles {:dev {:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/data.csv "1.0.0"]
[org.clojure/data.json "1.0.0"]]}}
;; exact match of the test dictionary
:jar-exclusions [#"ddict\.txt"]
:release-tasks [["vcs" "assert-committed"]
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag" "--no-sign"]
["deploy"]
["change" "version" "leiningen.release/bump-version"]
["vcs" "commit"]
;["vcs" "push"]
]
:deploy-repositories [["releases" :clojars]] ;; lein release :patch
:signing {:gpg-key ""})
| null | https://raw.githubusercontent.com/jimpil/clambda/176831945e12e0736cee00b53d2b9a6a1b8c6964/project.clj | clojure | exact match of the test dictionary
["vcs" "push"]
lein release :patch | (defproject clambda "0.1.6-SNAPSHOT"
:description "Utilities for working with Java Streams/Lambdas from Clojure."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies []
:profiles {:dev {:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/data.csv "1.0.0"]
[org.clojure/data.json "1.0.0"]]}}
:jar-exclusions [#"ddict\.txt"]
:release-tasks [["vcs" "assert-committed"]
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag" "--no-sign"]
["deploy"]
["change" "version" "leiningen.release/bump-version"]
["vcs" "commit"]
]
:signing {:gpg-key ""})
|
8f554762b0e0c01caf904f526514322f9b8932b1897adaf2f4c8507a84014cd8 | gpetiot/Frama-C-StaDy | env.ml | open Cil_types
type t = Cil_types.varinfo list * Cil_types.stmt list * Cil_types.stmt list
let empty = ([], [], [])
let merge (v1, s1, c1) (v2, s2, c2) =
( List.rev_append (List.rev v1) v2
, List.rev_append (List.rev s1) s2
, List.rev_append (List.rev c1) c2 )
let make v s c = (v, s, c)
let loc = Cil_datatype.Location.unknown
let mk_if e (v1, s1, c1) (v2, s2, c2) =
let b1 = Cil.mkBlock (List.rev_append (List.rev s1) c1)
and b2 = Cil.mkBlock (List.rev_append (List.rev s2) c2) in
Cil.mkStmt (If (e, {b1 with blocals= v1}, {b2 with blocals= v2}, loc))
let mk_block (v, s, c) =
let b = Cil.mkBlock (List.rev_append (List.rev s) c) in
Cil.mkStmt (Block {b with blocals= v})
let mk_loop e (v, s, c) =
let break_stmt = Cil.mkStmt (Break loc) in
let b1 = Cil.mkBlock [] and b2 = Cil.mkBlock [break_stmt] in
let i = Cil.mkStmt (If (e, b1, b2, loc)) in
let b = Cil.mkBlock (List.rev_append (List.rev s) c) in
let b = {b with blocals= v} in
Cil.mkStmt (Loop ([], {b with bstmts= i :: b.bstmts}, loc, None, None))
let locals (v, _s, _c) = v
let stmts (_v, s, _c) = s
let cleans (_v, _s, c) = c
| null | https://raw.githubusercontent.com/gpetiot/Frama-C-StaDy/48d8677c0c145d730d7f94e37b7b3e3a80fd1a27/env.ml | ocaml | open Cil_types
type t = Cil_types.varinfo list * Cil_types.stmt list * Cil_types.stmt list
let empty = ([], [], [])
let merge (v1, s1, c1) (v2, s2, c2) =
( List.rev_append (List.rev v1) v2
, List.rev_append (List.rev s1) s2
, List.rev_append (List.rev c1) c2 )
let make v s c = (v, s, c)
let loc = Cil_datatype.Location.unknown
let mk_if e (v1, s1, c1) (v2, s2, c2) =
let b1 = Cil.mkBlock (List.rev_append (List.rev s1) c1)
and b2 = Cil.mkBlock (List.rev_append (List.rev s2) c2) in
Cil.mkStmt (If (e, {b1 with blocals= v1}, {b2 with blocals= v2}, loc))
let mk_block (v, s, c) =
let b = Cil.mkBlock (List.rev_append (List.rev s) c) in
Cil.mkStmt (Block {b with blocals= v})
let mk_loop e (v, s, c) =
let break_stmt = Cil.mkStmt (Break loc) in
let b1 = Cil.mkBlock [] and b2 = Cil.mkBlock [break_stmt] in
let i = Cil.mkStmt (If (e, b1, b2, loc)) in
let b = Cil.mkBlock (List.rev_append (List.rev s) c) in
let b = {b with blocals= v} in
Cil.mkStmt (Loop ([], {b with bstmts= i :: b.bstmts}, loc, None, None))
let locals (v, _s, _c) = v
let stmts (_v, s, _c) = s
let cleans (_v, _s, c) = c
|
|
69d0291c41b9ad4f086c9800271f14cc517a52828642423ce34001d3c6aefb48 | Elzair/nazghul | lever.scm | ;; A lever is a basic binary mechanism.
(define (lever-state on?)
(if on?
(state-mk 's_R_lever_up #f pclass-none 0)
(state-mk 's_R_lever_down #f pclass-none 0)))
(define lever-ifc
(ifc bim-ifc
(method 'handle bim-toggle)
(method 'state lever-state)))
(mk-obj-type 't_lever "lever" '() layer-mechanism lever-ifc)
(define (mk-lever dest-tag)
(bind (kern-mk-obj t_lever 1)
(bim-mk #f dest-tag nil)))
(define (mk-lever-on dest-tag)
(bind (kern-mk-obj t_lever 1)
(bim-mk #t dest-tag nil)))
(define (mk-lever-with-id dest-tag id)
(bind (kern-mk-obj t_lever 1)
(bim-mk #f dest-tag id)))
;;----------------------------------------------------------------------------
;; Disguised lever
;;----------------------------------------------------------------------------
(define (disg-lvr-state on? klvr)
(let ((bim (kobj-gob-data klvr)))
(state-mk (bim-members bim) #f pclass-none 0)))
(define disg-lvr-ifc
(ifc bim-ifc
(method 'handle bim-toggle)
(method 'state disg-lvr-state)))
(mk-obj-type 't_disg_lvr nil '() layer-mechanism disg-lvr-ifc)
(define (mk-disg-lvr dest-tag sprite-tag)
(bind (kern-mk-obj t_disg_lvr 1)
(bim-mk #f dest-tag sprite-tag)))
;;----------------------------------------------------------------------------
;; Searchable Description of hidden mechanisms
;;----------------------------------------------------------------------------
(mk-obj-type 't_hidden_mech ;; tag
"hidden mechanism" ;; name
s_blank ;; sprite
layer-tfeat ;; stacking layer
nil ;; interface
)
(define (mk-hidden-mech)
(mk-hidden 't_hidden_mech 1))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/template/lib/lever.scm | scheme | A lever is a basic binary mechanism.
----------------------------------------------------------------------------
Disguised lever
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Searchable Description of hidden mechanisms
----------------------------------------------------------------------------
tag
name
sprite
stacking layer
interface |
(define (lever-state on?)
(if on?
(state-mk 's_R_lever_up #f pclass-none 0)
(state-mk 's_R_lever_down #f pclass-none 0)))
(define lever-ifc
(ifc bim-ifc
(method 'handle bim-toggle)
(method 'state lever-state)))
(mk-obj-type 't_lever "lever" '() layer-mechanism lever-ifc)
(define (mk-lever dest-tag)
(bind (kern-mk-obj t_lever 1)
(bim-mk #f dest-tag nil)))
(define (mk-lever-on dest-tag)
(bind (kern-mk-obj t_lever 1)
(bim-mk #t dest-tag nil)))
(define (mk-lever-with-id dest-tag id)
(bind (kern-mk-obj t_lever 1)
(bim-mk #f dest-tag id)))
(define (disg-lvr-state on? klvr)
(let ((bim (kobj-gob-data klvr)))
(state-mk (bim-members bim) #f pclass-none 0)))
(define disg-lvr-ifc
(ifc bim-ifc
(method 'handle bim-toggle)
(method 'state disg-lvr-state)))
(mk-obj-type 't_disg_lvr nil '() layer-mechanism disg-lvr-ifc)
(define (mk-disg-lvr dest-tag sprite-tag)
(bind (kern-mk-obj t_disg_lvr 1)
(bim-mk #f dest-tag sprite-tag)))
)
(define (mk-hidden-mech)
(mk-hidden 't_hidden_mech 1))
|
14a1c32676af025f8eb1a013f8e3d9757d4eccd0d6c8eb1171d6230b7706b366 | uxbox/uxbox-backend | locks.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
Copyright ( c ) 2016 < >
(ns uxbox.locks
"Advirsory locks for specific handling concurrent modifications
on particular objects in the database."
(:require [suricatta.core :as sc])
(:import clojure.lang.Murmur3))
(defn- uuid->long
[v]
(Murmur3/hashUnencodedChars (str v)))
(defn acquire!
[conn v]
(let [id (uuid->long v)]
(sc/execute conn ["select pg_advisory_xact_lock(?);" id])
nil))
| null | https://raw.githubusercontent.com/uxbox/uxbox-backend/036c42db8424be3ac34c38be80577ee279141681/src/uxbox/locks.clj | clojure | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2016 < >
(ns uxbox.locks
"Advirsory locks for specific handling concurrent modifications
on particular objects in the database."
(:require [suricatta.core :as sc])
(:import clojure.lang.Murmur3))
(defn- uuid->long
[v]
(Murmur3/hashUnencodedChars (str v)))
(defn acquire!
[conn v]
(let [id (uuid->long v)]
(sc/execute conn ["select pg_advisory_xact_lock(?);" id])
nil))
|
|
976ac5ec804bbe96cc873f535f60f378c07eeddf9373106a90b17968cedf860c | MassD/99 | graph.ml | type 'a edge_clause = ('a * 'a) list
type 'a graph_term = {nodes: 'a list; edges : ('a *'a) list}
type 'a human_friendly = string
let edge_clause_to_graph_term l =
let rec rm_dup acc = function
| [] -> acc
| (x,y)::tl ->
if List.mem x acc && List.mem y acc then rm_dup (acc) tl
else if List.mem y acc then rm_dup (x::acc) tl
else if List.mem x acc then rm_dup (y::acc) tl
else rm_dup (x::y::acc) tl
in
{nodes = rm_dup [] l |> List.sort compare; edges = l}
let ec = ['h', 'g'; 'k', 'f'; 'f', 'b'; 'f', 'c'; 'c', 'b']
module type NodeEdgeType =
sig
type t
type et
val compare: t -> t -> int
end
module type Adj_graph_type = sig
type nt
type t
val create_adjacency : ( nt * nt list ) list - > t
end
type nt
type t
val create_adjacency : (nt * nt list) list -> t
end*)
module Make_adj (Ne:NodeEdgeType) = struct
include Map.Make(Ne)
type nt = Ne.t
type gt = Ne.et t
let create_adjacency l = List.fold_left (fun g (x,xl) -> add x xl g) (empty) l
end
| null | https://raw.githubusercontent.com/MassD/99/1d3019eb55b0d621ed1df4132315673dd812b1e1/80-89%2B94-graphs/graph.ml | ocaml | type 'a edge_clause = ('a * 'a) list
type 'a graph_term = {nodes: 'a list; edges : ('a *'a) list}
type 'a human_friendly = string
let edge_clause_to_graph_term l =
let rec rm_dup acc = function
| [] -> acc
| (x,y)::tl ->
if List.mem x acc && List.mem y acc then rm_dup (acc) tl
else if List.mem y acc then rm_dup (x::acc) tl
else if List.mem x acc then rm_dup (y::acc) tl
else rm_dup (x::y::acc) tl
in
{nodes = rm_dup [] l |> List.sort compare; edges = l}
let ec = ['h', 'g'; 'k', 'f'; 'f', 'b'; 'f', 'c'; 'c', 'b']
module type NodeEdgeType =
sig
type t
type et
val compare: t -> t -> int
end
module type Adj_graph_type = sig
type nt
type t
val create_adjacency : ( nt * nt list ) list - > t
end
type nt
type t
val create_adjacency : (nt * nt list) list -> t
end*)
module Make_adj (Ne:NodeEdgeType) = struct
include Map.Make(Ne)
type nt = Ne.t
type gt = Ne.et t
let create_adjacency l = List.fold_left (fun g (x,xl) -> add x xl g) (empty) l
end
|
|
92a1dae58f481a41628cdfe01c0714dd77ca13e7ba01b39dbf4adc414b9c0324 | singleheart/programming-in-haskell | ex5.hs | (&&) :: Bool -> Bool -> Bool
a && b =
if a == True
then if b == True
then True
else False
else False
| null | https://raw.githubusercontent.com/singleheart/programming-in-haskell/80c7efc0425babea3cd982e47e121f19bec0aba9/ch04/ex5.hs | haskell | (&&) :: Bool -> Bool -> Bool
a && b =
if a == True
then if b == True
then True
else False
else False
|
|
f9813fe3146dc4854be6f6db8464df38d86b1c6f417e2139aa1c98325147cb73 | tezos/tezos-mirror | node_context.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 TriliTech < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
(** This module describes the execution context of the node. *)
open Protocol
open Alpha_context
type lcc = {commitment : Sc_rollup.Commitment.Hash.t; level : Raw_level.t}
(** Abstract type for store to force access through this module. *)
type 'a store constraint 'a = [< `Read | `Write > `Read]
type 'a t = {
cctxt : Protocol_client_context.full;
(** Client context used by the rollup node. *)
dal_cctxt : Dal_node_client.cctxt option;
* DAL client context to query the dal node , if the rollup node supports
the DAL .
the DAL. *)
* Node data dir .
l1_ctxt : Layer1.t;
* Layer 1 context to fetch blocks and monitor heads , etc .
rollup_address : Sc_rollup.t; (** Smart rollup tracked by the rollup node. *)
mode : Configuration.mode;
(** Mode of the node, see {!Configuration.mode}. *)
operators : Configuration.operators;
(** Addresses of the rollup node operators by purposes. *)
genesis_info : Sc_rollup.Commitment.genesis_info;
(** Origination information of the smart rollup. *)
injector_retention_period : int;
(** Number of blocks the injector will keep information about included
operations. *)
block_finality_time : int;
* Deterministic block finality time for the layer 1 protocol .
kind : Sc_rollup.Kind.t; (** Kind of the smart rollup. *)
fee_parameters : Configuration.fee_parameters;
* Fee parameters to use when injecting operations in layer 1 .
protocol_constants : Constants.t;
* Protocol constants retrieved from the Tezos node .
loser_mode : Loser_mode.t;
(** If different from [Loser_mode.no_failures], the rollup node
issues wrong commitments (for tests). *)
store : 'a store; (** The store for the persistent storage. *)
context : 'a Context.index;
(** The persistent context for the rollup node. *)
lcc : ('a, lcc) Reference.t; (** Last cemented commitment and its level. *)
lpc : ('a, Sc_rollup.Commitment.t option) Reference.t;
(** The last published commitment, i.e. commitment that the operator is
staked on. *)
}
(** Read/write node context {!t}. *)
type rw = [`Read | `Write] t
(** Read only node context {!t}. *)
type ro = [`Read] t
(** [get_operator cctxt purpose] returns the public key hash for the operator
who has purpose [purpose], if any.
*)
val get_operator :
_ t ->
Configuration.purpose ->
Tezos_crypto.Signature.Public_key_hash.t option
(** [is_operator cctxt pkh] returns [true] if the public key hash [pkh] is an
operator for the node (for any purpose). *)
val is_operator : _ t -> Tezos_crypto.Signature.Public_key_hash.t -> bool
(** [is_accuser node_ctxt] returns [true] if the rollup node runs in accuser
mode. *)
val is_accuser : _ t -> bool
(** [get_fee_parameter cctxt purpose] returns the fee parameter to inject an
operation for a given [purpose]. If no specific fee parameters were
configured for this purpose, returns the default fee parameter for this
purpose.
*)
val get_fee_parameter : _ t -> Configuration.purpose -> Injection.fee_parameter
* [ init cctxt ~data_dir mode configuration ] initializes the rollup
representation . The rollup origination level and kind are fetched via an RPC
call to the layer1 node that [ cctxt ] uses for RPC requests .
representation. The rollup origination level and kind are fetched via an RPC
call to the layer1 node that [cctxt] uses for RPC requests.
*)
val init :
Protocol_client_context.full ->
data_dir:string ->
'a Store_sigs.mode ->
Configuration.t ->
'a t tzresult Lwt.t
(** Closes the store, context and Layer 1 monitor. *)
val close : _ t -> unit tzresult Lwt.t
(** [checkout_context node_ctxt block_hash] returns the context at block
[block_hash]. *)
val checkout_context : 'a t -> Block_hash.t -> 'a Context.t tzresult Lwt.t
* [ metadata node_ctxt ] creates a { Sc_rollup . Metadata.t } using the information
stored in [ node_ctxt ] .
stored in [node_ctxt]. *)
val metadata : _ t -> Sc_rollup.Metadata.t
* Returns [ true ] if the rollup node supports the DAL and if DAL is enabled for
the current protocol .
the current protocol. *)
val dal_supported : _ t -> bool
(** [readonly node_ctxt] returns a read only version of the node context
[node_ctxt]. *)
val readonly : _ t -> ro
(** Monad for values with delayed write effects in the node context. *)
type 'a delayed_write = ('a, rw) Delayed_write_monad.t
* { 2 Abstraction over store }
* { 3 Layer 2 blocks }
(** [is_processed store hash] returns [true] if the block with [hash] has
already been processed by the daemon. *)
val is_processed : _ t -> Block_hash.t -> bool tzresult Lwt.t
(** [get_l2_block t hash] returns the Layer 2 block known by the rollup node for
Layer 1 block [hash]. *)
val get_l2_block : _ t -> Block_hash.t -> Sc_rollup_block.t tzresult Lwt.t
(** Same as {!get_l2_block} but returns [None] when the Layer 2 block is not
available. *)
val find_l2_block :
_ t -> Block_hash.t -> Sc_rollup_block.t option tzresult Lwt.t
(** Same as {!get_l2_block} but retrieves the Layer 2 block by its level. *)
val get_l2_block_by_level : _ t -> int32 -> Sc_rollup_block.t tzresult Lwt.t
(** Same as {!get_l2_block_by_level} but returns [None] when the Layer 2 block
is not available. *)
val find_l2_block_by_level :
_ t -> int32 -> Sc_rollup_block.t option tzresult Lwt.t
* [ get_full_l2_block node_ctxt hash ] returns the full L2 block for L1 block
hash [ hash ] . The result contains the L2 block and its content ( inbox ,
messages , commitment ) .
hash [hash]. The result contains the L2 block and its content (inbox,
messages, commitment). *)
val get_full_l2_block :
_ t -> Block_hash.t -> Sc_rollup_block.full tzresult Lwt.t
(** [save_level t head] registers the correspondences [head.level |->
head.hash] in the store. *)
val save_level : rw -> Layer1.head -> unit tzresult Lwt.t
(** [save_l2_head t l2_block] remembers that the [l2_block.head] is
processed. The system should not have to come back to it. *)
val save_l2_head : rw -> Sc_rollup_block.t -> unit tzresult Lwt.t
(** [last_processed_head_opt store] returns the last processed head if it
exists. *)
val last_processed_head_opt : _ t -> Sc_rollup_block.t option tzresult Lwt.t
(** [mark_finalized_head store head] remembers that the [head] is finalized. By
construction, every block whose level is smaller than [head]'s is also
finalized. *)
val mark_finalized_head : rw -> Block_hash.t -> unit tzresult Lwt.t
(** [last_finalized_head_opt store] returns the last finalized head if it exists. *)
val get_finalized_head_opt : _ t -> Sc_rollup_block.t option tzresult Lwt.t
(** [hash_of_level node_ctxt level] returns the current block hash for a given
[level]. *)
val hash_of_level : _ t -> int32 -> Block_hash.t tzresult Lwt.t
(** [hash_of_level_opt] is like {!hash_of_level} but returns [None] if the
[level] is not known. *)
val hash_of_level_opt : _ t -> int32 -> Block_hash.t option tzresult Lwt.t
* [ level_of_hash node_ctxt hash ] returns the level for Tezos block hash [ hash ]
if it is known by the Tezos Layer 1 node .
if it is known by the Tezos Layer 1 node. *)
val level_of_hash : _ t -> Block_hash.t -> int32 tzresult Lwt.t
* [ block_with_tick store ~max_level tick ] returns [ Some b ] where [ b ] is the
last layer 2 block which contains the [ tick ] before [ max_level ] . If no such
block exists ( the tick happened after [ max_level ] , or we are too late ) , the
function returns [ None ] .
last layer 2 block which contains the [tick] before [max_level]. If no such
block exists (the tick happened after [max_level], or we are too late), the
function returns [None]. *)
val block_with_tick :
_ t ->
max_level:Raw_level.t ->
Sc_rollup.Tick.t ->
Sc_rollup_block.t option tzresult Lwt.t
* { 3 Commitments }
(** [get_commitment t hash] returns the commitment with [hash] stored by the
rollup node. *)
val get_commitment :
_ t -> Sc_rollup.Commitment.Hash.t -> Sc_rollup.Commitment.t tzresult Lwt.t
(** Same as {!get_commitment} but returns [None] if this commitment hash is not
known by the rollup node. *)
val find_commitment :
_ t ->
Sc_rollup.Commitment.Hash.t ->
Sc_rollup.Commitment.t option tzresult Lwt.t
(** [commitment_exists t hash] returns [true] if the commitment with [hash] is
known (i.e. stored) by the rollup node. *)
val commitment_exists :
_ t -> Sc_rollup.Commitment.Hash.t -> bool tzresult Lwt.t
(** [save_commitment t commitment] saves a commitment in the store an returns is
hash. *)
val save_commitment :
rw -> Sc_rollup.Commitment.t -> Sc_rollup.Commitment.Hash.t tzresult Lwt.t
* [ commitment_published_at_level t hash ] returns the levels at which the
commitment was first published and the one at which it was included by in a
Layer 1 block . It returns [ None ] if the commitment is not known by the
rollup node or if it was never published by the rollup node ( and included on
L1 ) .
commitment was first published and the one at which it was included by in a
Layer 1 block. It returns [None] if the commitment is not known by the
rollup node or if it was never published by the rollup node (and included on
L1). *)
val commitment_published_at_level :
_ t ->
Sc_rollup.Commitment.Hash.t ->
Store.Commitments_published_at_level.element option tzresult Lwt.t
(** [save_commitment_published_at_level t hash levels] saves the
publication/inclusion information for a commitment with [hash]. *)
val set_commitment_published_at_level :
rw ->
Sc_rollup.Commitment.Hash.t ->
Store.Commitments_published_at_level.element ->
unit tzresult Lwt.t
type commitment_source = Anyone | Us
* [ commitment_was_published t hash ] returns [ true ] if the commitment is known
as being already published on L1 . The [ source ] indicates if we want to know
the publication status for commitments we published ourselves [ ` Us ] or that
[ ` Anyone ] published .
as being already published on L1. The [source] indicates if we want to know
the publication status for commitments we published ourselves [`Us] or that
[`Anyone] published. *)
val commitment_was_published :
_ t ->
source:commitment_source ->
Sc_rollup.Commitment.Hash.t ->
bool tzresult Lwt.t
* { 3 Inboxes }
type messages_info = {
predecessor : Block_hash.t;
predecessor_timestamp : Timestamp.t;
messages : Sc_rollup.Inbox_message.t list;
}
(** [get_inbox t inbox_hash] retrieves the inbox whose hash is [inbox_hash] from
the rollup node's storage. *)
val get_inbox :
_ t -> Sc_rollup.Inbox.Hash.t -> Sc_rollup.Inbox.t tzresult Lwt.t
* Same as { ! } but returns [ None ] if this inbox is not known .
val find_inbox :
_ t -> Sc_rollup.Inbox.Hash.t -> Sc_rollup.Inbox.t option tzresult Lwt.t
(** [save_inbox t inbox] remembers the [inbox] in the storage. It is associated
to its hash which is returned. *)
val save_inbox :
rw -> Sc_rollup.Inbox.t -> Sc_rollup.Inbox.Hash.t tzresult Lwt.t
* [ inbox_of_head node_ctxt block ] returns the latest inbox at the given
[ block ] . This function always returns [ inbox ] for all levels at and
after the rollup genesis . NOTE : It requires the L2 block for [ block.hash ] to
have been saved .
[block]. This function always returns [inbox] for all levels at and
after the rollup genesis. NOTE: It requires the L2 block for [block.hash] to
have been saved. *)
val inbox_of_head : _ t -> Layer1.head -> Sc_rollup.Inbox.t tzresult Lwt.t
* Same as { ! } but uses the Layer 1 block hash for this inbox instead .
val get_inbox_by_block_hash :
_ t -> Block_hash.t -> Sc_rollup.Inbox.t tzresult Lwt.t
(** [genesis_inbox t] is the genesis inbox for the rollup [t.sc_rollup_address]. *)
val genesis_inbox : _ t -> Sc_rollup.Inbox.t tzresult Lwt.t
* [ get_messages t witness_hash ] retrieves the messages for the merkelized
payloads hash [ witness_hash ] stored by the rollup node .
payloads hash [witness_hash] stored by the rollup node. *)
val get_messages :
_ t ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info tzresult Lwt.t
* Same as { ! } but returns [ None ] if the payloads hash is not known .
val find_messages :
_ t ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info option tzresult Lwt.t
(** [get_num_messages t witness_hash] retrieves (without reading all the messages
from disk) the number of messages for the inbox witness [witness_hash]
stored by the rollup node. *)
val get_num_messages :
_ t -> Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t -> int tzresult Lwt.t
(** [save_messages t payloads_hash messages] associates the list of [messages]
to the [payloads_hash]. The payload hash must be computed by calling,
e.g. {!Sc_rollup.Inbox.add_all_messages}. *)
val save_messages :
rw ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info ->
unit tzresult Lwt.t
(** {3 DAL} *)
* [ get_slot_header t ~published_in_block_hash slot_index ] returns the slot
header for the [ slot_index ] that was published in the provided block hash on
Layer 1 .
header for the [slot_index] that was published in the provided block hash on
Layer 1. *)
val get_slot_header :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot_index.t ->
Dal.Slot.Header.t tzresult Lwt.t
* [ get_all_slot_headers t ~published_in_block_hash ] returns the slot headers
for all the slots that were published in the provided block hash on Layer
1 .
for all the slots that were published in the provided block hash on Layer
1. *)
val get_all_slot_headers :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot.Header.t list tzresult Lwt.t
* [ get_slot_indexes t ~published_in_block_hash ] returns the slot indexes whose
headers were published in the provided block hash on Layer 1 .
headers were published in the provided block hash on Layer 1. *)
val get_slot_indexes :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot_index.t list tzresult Lwt.t
* [ save_slot_header t ~published_in_block_hash header ] saves the [ header ] as
being published for its index in the provided block hash on Layer 1 .
being published for its index in the provided block hash on Layer 1. *)
val save_slot_header :
rw ->
published_in_block_hash:Block_hash.t ->
Dal.Slot.Header.t ->
unit tzresult Lwt.t
* [ processed_slot t ~confirmed_in_block_hash index ] returns [ None ] if the slot
pages was never processed nor downloaded , [ Some ` Unconfirmed ] if the slot
was not confirmed and [ Some ` Confirmed ] if the slot is confirmed and the
associated pages are available .
pages was never processed nor downloaded, [Some `Unconfirmed] if the slot
was not confirmed and [Some `Confirmed] if the slot is confirmed and the
associated pages are available. *)
val processed_slot :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
Dal.Slot_index.t ->
[`Unconfirmed | `Confirmed] option tzresult Lwt.t
(** [list_slot_pages t ~confirmed_in_block_hash] lists all slots and their pages
that were confirmed and stored by the rollup node for
[confirmed_in_block_hash]. *)
val list_slot_pages :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
((Dal.Slot_index.t * int) * bytes) list tzresult Lwt.t
(** [find_slot_page t ~confirmed_in_block_hash slot_index page_index] retrieves
a pages (with index [page_index]) for a slot [slot_index] that was confirmed
in the provided block hash. It returns [None] if the slot was not processed
or if the page index is out of bounds. *)
val find_slot_page :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
slot_index:Dal.Slot_index.t ->
page_index:int ->
bytes option tzresult Lwt.t
(** [save_unconfirmed_slot node_ctxt hash slot_index] saves in [node_ctxt.store]
that [slot_index] is unconfirmed in the block with hash in [node_ctxt.store].
*)
val save_unconfirmed_slot :
rw -> Block_hash.t -> Dal.Slot_index.t -> unit tzresult Lwt.t
(** [save_confirmed_slot node_ctxt hash slot_index] saves in [node_ctxt.store]
that [slot_index] is confirmed in the block with hashin [node_ctxt.store].
The contents of the slot are set to [pages] in [node_ctxt.store]. *)
val save_confirmed_slot :
rw -> Block_hash.t -> Dal.Slot_index.t -> bytes list -> unit tzresult Lwt.t
(* TODO: /-/issues/4636
Missing docstrings. *)
val find_confirmed_slots_history :
_ t -> Block_hash.t -> Dal.Slots_history.t option tzresult Lwt.t
val save_confirmed_slots_history :
rw -> Block_hash.t -> Dal.Slots_history.t -> unit tzresult Lwt.t
val find_confirmed_slots_histories :
_ t -> Block_hash.t -> Dal.Slots_history.History_cache.t option tzresult Lwt.t
val save_confirmed_slots_histories :
rw -> Block_hash.t -> Dal.Slots_history.History_cache.t -> unit tzresult Lwt.t
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/1b26ce0f9c2a9c508a65c45641a0a146d9b52fc7/src/proto_016_PtMumbai/lib_sc_rollup_node/node_context.mli | 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 module describes the execution context of the node.
* Abstract type for store to force access through this module.
* Client context used by the rollup node.
* Smart rollup tracked by the rollup node.
* Mode of the node, see {!Configuration.mode}.
* Addresses of the rollup node operators by purposes.
* Origination information of the smart rollup.
* Number of blocks the injector will keep information about included
operations.
* Kind of the smart rollup.
* If different from [Loser_mode.no_failures], the rollup node
issues wrong commitments (for tests).
* The store for the persistent storage.
* The persistent context for the rollup node.
* Last cemented commitment and its level.
* The last published commitment, i.e. commitment that the operator is
staked on.
* Read/write node context {!t}.
* Read only node context {!t}.
* [get_operator cctxt purpose] returns the public key hash for the operator
who has purpose [purpose], if any.
* [is_operator cctxt pkh] returns [true] if the public key hash [pkh] is an
operator for the node (for any purpose).
* [is_accuser node_ctxt] returns [true] if the rollup node runs in accuser
mode.
* [get_fee_parameter cctxt purpose] returns the fee parameter to inject an
operation for a given [purpose]. If no specific fee parameters were
configured for this purpose, returns the default fee parameter for this
purpose.
* Closes the store, context and Layer 1 monitor.
* [checkout_context node_ctxt block_hash] returns the context at block
[block_hash].
* [readonly node_ctxt] returns a read only version of the node context
[node_ctxt].
* Monad for values with delayed write effects in the node context.
* [is_processed store hash] returns [true] if the block with [hash] has
already been processed by the daemon.
* [get_l2_block t hash] returns the Layer 2 block known by the rollup node for
Layer 1 block [hash].
* Same as {!get_l2_block} but returns [None] when the Layer 2 block is not
available.
* Same as {!get_l2_block} but retrieves the Layer 2 block by its level.
* Same as {!get_l2_block_by_level} but returns [None] when the Layer 2 block
is not available.
* [save_level t head] registers the correspondences [head.level |->
head.hash] in the store.
* [save_l2_head t l2_block] remembers that the [l2_block.head] is
processed. The system should not have to come back to it.
* [last_processed_head_opt store] returns the last processed head if it
exists.
* [mark_finalized_head store head] remembers that the [head] is finalized. By
construction, every block whose level is smaller than [head]'s is also
finalized.
* [last_finalized_head_opt store] returns the last finalized head if it exists.
* [hash_of_level node_ctxt level] returns the current block hash for a given
[level].
* [hash_of_level_opt] is like {!hash_of_level} but returns [None] if the
[level] is not known.
* [get_commitment t hash] returns the commitment with [hash] stored by the
rollup node.
* Same as {!get_commitment} but returns [None] if this commitment hash is not
known by the rollup node.
* [commitment_exists t hash] returns [true] if the commitment with [hash] is
known (i.e. stored) by the rollup node.
* [save_commitment t commitment] saves a commitment in the store an returns is
hash.
* [save_commitment_published_at_level t hash levels] saves the
publication/inclusion information for a commitment with [hash].
* [get_inbox t inbox_hash] retrieves the inbox whose hash is [inbox_hash] from
the rollup node's storage.
* [save_inbox t inbox] remembers the [inbox] in the storage. It is associated
to its hash which is returned.
* [genesis_inbox t] is the genesis inbox for the rollup [t.sc_rollup_address].
* [get_num_messages t witness_hash] retrieves (without reading all the messages
from disk) the number of messages for the inbox witness [witness_hash]
stored by the rollup node.
* [save_messages t payloads_hash messages] associates the list of [messages]
to the [payloads_hash]. The payload hash must be computed by calling,
e.g. {!Sc_rollup.Inbox.add_all_messages}.
* {3 DAL}
* [list_slot_pages t ~confirmed_in_block_hash] lists all slots and their pages
that were confirmed and stored by the rollup node for
[confirmed_in_block_hash].
* [find_slot_page t ~confirmed_in_block_hash slot_index page_index] retrieves
a pages (with index [page_index]) for a slot [slot_index] that was confirmed
in the provided block hash. It returns [None] if the slot was not processed
or if the page index is out of bounds.
* [save_unconfirmed_slot node_ctxt hash slot_index] saves in [node_ctxt.store]
that [slot_index] is unconfirmed in the block with hash in [node_ctxt.store].
* [save_confirmed_slot node_ctxt hash slot_index] saves in [node_ctxt.store]
that [slot_index] is confirmed in the block with hashin [node_ctxt.store].
The contents of the slot are set to [pages] in [node_ctxt.store].
TODO: /-/issues/4636
Missing docstrings. | Copyright ( c ) 2022 TriliTech < >
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 Protocol
open Alpha_context
type lcc = {commitment : Sc_rollup.Commitment.Hash.t; level : Raw_level.t}
type 'a store constraint 'a = [< `Read | `Write > `Read]
type 'a t = {
cctxt : Protocol_client_context.full;
dal_cctxt : Dal_node_client.cctxt option;
* DAL client context to query the dal node , if the rollup node supports
the DAL .
the DAL. *)
* Node data dir .
l1_ctxt : Layer1.t;
* Layer 1 context to fetch blocks and monitor heads , etc .
mode : Configuration.mode;
operators : Configuration.operators;
genesis_info : Sc_rollup.Commitment.genesis_info;
injector_retention_period : int;
block_finality_time : int;
* Deterministic block finality time for the layer 1 protocol .
fee_parameters : Configuration.fee_parameters;
* Fee parameters to use when injecting operations in layer 1 .
protocol_constants : Constants.t;
* Protocol constants retrieved from the Tezos node .
loser_mode : Loser_mode.t;
context : 'a Context.index;
lpc : ('a, Sc_rollup.Commitment.t option) Reference.t;
}
type rw = [`Read | `Write] t
type ro = [`Read] t
val get_operator :
_ t ->
Configuration.purpose ->
Tezos_crypto.Signature.Public_key_hash.t option
val is_operator : _ t -> Tezos_crypto.Signature.Public_key_hash.t -> bool
val is_accuser : _ t -> bool
val get_fee_parameter : _ t -> Configuration.purpose -> Injection.fee_parameter
* [ init cctxt ~data_dir mode configuration ] initializes the rollup
representation . The rollup origination level and kind are fetched via an RPC
call to the layer1 node that [ cctxt ] uses for RPC requests .
representation. The rollup origination level and kind are fetched via an RPC
call to the layer1 node that [cctxt] uses for RPC requests.
*)
val init :
Protocol_client_context.full ->
data_dir:string ->
'a Store_sigs.mode ->
Configuration.t ->
'a t tzresult Lwt.t
val close : _ t -> unit tzresult Lwt.t
val checkout_context : 'a t -> Block_hash.t -> 'a Context.t tzresult Lwt.t
* [ metadata node_ctxt ] creates a { Sc_rollup . Metadata.t } using the information
stored in [ node_ctxt ] .
stored in [node_ctxt]. *)
val metadata : _ t -> Sc_rollup.Metadata.t
* Returns [ true ] if the rollup node supports the DAL and if DAL is enabled for
the current protocol .
the current protocol. *)
val dal_supported : _ t -> bool
val readonly : _ t -> ro
type 'a delayed_write = ('a, rw) Delayed_write_monad.t
* { 2 Abstraction over store }
* { 3 Layer 2 blocks }
val is_processed : _ t -> Block_hash.t -> bool tzresult Lwt.t
val get_l2_block : _ t -> Block_hash.t -> Sc_rollup_block.t tzresult Lwt.t
val find_l2_block :
_ t -> Block_hash.t -> Sc_rollup_block.t option tzresult Lwt.t
val get_l2_block_by_level : _ t -> int32 -> Sc_rollup_block.t tzresult Lwt.t
val find_l2_block_by_level :
_ t -> int32 -> Sc_rollup_block.t option tzresult Lwt.t
* [ get_full_l2_block node_ctxt hash ] returns the full L2 block for L1 block
hash [ hash ] . The result contains the L2 block and its content ( inbox ,
messages , commitment ) .
hash [hash]. The result contains the L2 block and its content (inbox,
messages, commitment). *)
val get_full_l2_block :
_ t -> Block_hash.t -> Sc_rollup_block.full tzresult Lwt.t
val save_level : rw -> Layer1.head -> unit tzresult Lwt.t
val save_l2_head : rw -> Sc_rollup_block.t -> unit tzresult Lwt.t
val last_processed_head_opt : _ t -> Sc_rollup_block.t option tzresult Lwt.t
val mark_finalized_head : rw -> Block_hash.t -> unit tzresult Lwt.t
val get_finalized_head_opt : _ t -> Sc_rollup_block.t option tzresult Lwt.t
val hash_of_level : _ t -> int32 -> Block_hash.t tzresult Lwt.t
val hash_of_level_opt : _ t -> int32 -> Block_hash.t option tzresult Lwt.t
* [ level_of_hash node_ctxt hash ] returns the level for Tezos block hash [ hash ]
if it is known by the Tezos Layer 1 node .
if it is known by the Tezos Layer 1 node. *)
val level_of_hash : _ t -> Block_hash.t -> int32 tzresult Lwt.t
* [ block_with_tick store ~max_level tick ] returns [ Some b ] where [ b ] is the
last layer 2 block which contains the [ tick ] before [ max_level ] . If no such
block exists ( the tick happened after [ max_level ] , or we are too late ) , the
function returns [ None ] .
last layer 2 block which contains the [tick] before [max_level]. If no such
block exists (the tick happened after [max_level], or we are too late), the
function returns [None]. *)
val block_with_tick :
_ t ->
max_level:Raw_level.t ->
Sc_rollup.Tick.t ->
Sc_rollup_block.t option tzresult Lwt.t
* { 3 Commitments }
val get_commitment :
_ t -> Sc_rollup.Commitment.Hash.t -> Sc_rollup.Commitment.t tzresult Lwt.t
val find_commitment :
_ t ->
Sc_rollup.Commitment.Hash.t ->
Sc_rollup.Commitment.t option tzresult Lwt.t
val commitment_exists :
_ t -> Sc_rollup.Commitment.Hash.t -> bool tzresult Lwt.t
val save_commitment :
rw -> Sc_rollup.Commitment.t -> Sc_rollup.Commitment.Hash.t tzresult Lwt.t
* [ commitment_published_at_level t hash ] returns the levels at which the
commitment was first published and the one at which it was included by in a
Layer 1 block . It returns [ None ] if the commitment is not known by the
rollup node or if it was never published by the rollup node ( and included on
L1 ) .
commitment was first published and the one at which it was included by in a
Layer 1 block. It returns [None] if the commitment is not known by the
rollup node or if it was never published by the rollup node (and included on
L1). *)
val commitment_published_at_level :
_ t ->
Sc_rollup.Commitment.Hash.t ->
Store.Commitments_published_at_level.element option tzresult Lwt.t
val set_commitment_published_at_level :
rw ->
Sc_rollup.Commitment.Hash.t ->
Store.Commitments_published_at_level.element ->
unit tzresult Lwt.t
type commitment_source = Anyone | Us
* [ commitment_was_published t hash ] returns [ true ] if the commitment is known
as being already published on L1 . The [ source ] indicates if we want to know
the publication status for commitments we published ourselves [ ` Us ] or that
[ ` Anyone ] published .
as being already published on L1. The [source] indicates if we want to know
the publication status for commitments we published ourselves [`Us] or that
[`Anyone] published. *)
val commitment_was_published :
_ t ->
source:commitment_source ->
Sc_rollup.Commitment.Hash.t ->
bool tzresult Lwt.t
* { 3 Inboxes }
type messages_info = {
predecessor : Block_hash.t;
predecessor_timestamp : Timestamp.t;
messages : Sc_rollup.Inbox_message.t list;
}
val get_inbox :
_ t -> Sc_rollup.Inbox.Hash.t -> Sc_rollup.Inbox.t tzresult Lwt.t
* Same as { ! } but returns [ None ] if this inbox is not known .
val find_inbox :
_ t -> Sc_rollup.Inbox.Hash.t -> Sc_rollup.Inbox.t option tzresult Lwt.t
val save_inbox :
rw -> Sc_rollup.Inbox.t -> Sc_rollup.Inbox.Hash.t tzresult Lwt.t
* [ inbox_of_head node_ctxt block ] returns the latest inbox at the given
[ block ] . This function always returns [ inbox ] for all levels at and
after the rollup genesis . NOTE : It requires the L2 block for [ block.hash ] to
have been saved .
[block]. This function always returns [inbox] for all levels at and
after the rollup genesis. NOTE: It requires the L2 block for [block.hash] to
have been saved. *)
val inbox_of_head : _ t -> Layer1.head -> Sc_rollup.Inbox.t tzresult Lwt.t
* Same as { ! } but uses the Layer 1 block hash for this inbox instead .
val get_inbox_by_block_hash :
_ t -> Block_hash.t -> Sc_rollup.Inbox.t tzresult Lwt.t
val genesis_inbox : _ t -> Sc_rollup.Inbox.t tzresult Lwt.t
* [ get_messages t witness_hash ] retrieves the messages for the merkelized
payloads hash [ witness_hash ] stored by the rollup node .
payloads hash [witness_hash] stored by the rollup node. *)
val get_messages :
_ t ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info tzresult Lwt.t
* Same as { ! } but returns [ None ] if the payloads hash is not known .
val find_messages :
_ t ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info option tzresult Lwt.t
val get_num_messages :
_ t -> Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t -> int tzresult Lwt.t
val save_messages :
rw ->
Sc_rollup.Inbox_merkelized_payload_hashes.Hash.t ->
messages_info ->
unit tzresult Lwt.t
* [ get_slot_header t ~published_in_block_hash slot_index ] returns the slot
header for the [ slot_index ] that was published in the provided block hash on
Layer 1 .
header for the [slot_index] that was published in the provided block hash on
Layer 1. *)
val get_slot_header :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot_index.t ->
Dal.Slot.Header.t tzresult Lwt.t
* [ get_all_slot_headers t ~published_in_block_hash ] returns the slot headers
for all the slots that were published in the provided block hash on Layer
1 .
for all the slots that were published in the provided block hash on Layer
1. *)
val get_all_slot_headers :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot.Header.t list tzresult Lwt.t
* [ get_slot_indexes t ~published_in_block_hash ] returns the slot indexes whose
headers were published in the provided block hash on Layer 1 .
headers were published in the provided block hash on Layer 1. *)
val get_slot_indexes :
_ t ->
published_in_block_hash:Block_hash.t ->
Dal.Slot_index.t list tzresult Lwt.t
* [ save_slot_header t ~published_in_block_hash header ] saves the [ header ] as
being published for its index in the provided block hash on Layer 1 .
being published for its index in the provided block hash on Layer 1. *)
val save_slot_header :
rw ->
published_in_block_hash:Block_hash.t ->
Dal.Slot.Header.t ->
unit tzresult Lwt.t
* [ processed_slot t ~confirmed_in_block_hash index ] returns [ None ] if the slot
pages was never processed nor downloaded , [ Some ` Unconfirmed ] if the slot
was not confirmed and [ Some ` Confirmed ] if the slot is confirmed and the
associated pages are available .
pages was never processed nor downloaded, [Some `Unconfirmed] if the slot
was not confirmed and [Some `Confirmed] if the slot is confirmed and the
associated pages are available. *)
val processed_slot :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
Dal.Slot_index.t ->
[`Unconfirmed | `Confirmed] option tzresult Lwt.t
val list_slot_pages :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
((Dal.Slot_index.t * int) * bytes) list tzresult Lwt.t
val find_slot_page :
_ t ->
confirmed_in_block_hash:Block_hash.t ->
slot_index:Dal.Slot_index.t ->
page_index:int ->
bytes option tzresult Lwt.t
val save_unconfirmed_slot :
rw -> Block_hash.t -> Dal.Slot_index.t -> unit tzresult Lwt.t
val save_confirmed_slot :
rw -> Block_hash.t -> Dal.Slot_index.t -> bytes list -> unit tzresult Lwt.t
val find_confirmed_slots_history :
_ t -> Block_hash.t -> Dal.Slots_history.t option tzresult Lwt.t
val save_confirmed_slots_history :
rw -> Block_hash.t -> Dal.Slots_history.t -> unit tzresult Lwt.t
val find_confirmed_slots_histories :
_ t -> Block_hash.t -> Dal.Slots_history.History_cache.t option tzresult Lwt.t
val save_confirmed_slots_histories :
rw -> Block_hash.t -> Dal.Slots_history.History_cache.t -> unit tzresult Lwt.t
|
9bfd51f517426d30e4c6ad94a0c9e2210caca94dc6ddc03c78467a248f7a6f90 | takikawa/racket-ppa | info.rkt | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("scheme-lib" ("base" #:version "6.5.0.2") "net-lib" "sandbox-lib" ("scribble-lib" #:version "1.34") "racket-index"))) (define build-deps (quote ("rackunit-doc" "compatibility" "errortrace-doc" "typed-racket-doc" "at-exp-lib" "rackunit-lib" "web-server-doc" "gui" "draw" "pict" "parser-tools-doc" "slideshow-doc" "r5rs-doc" "r6rs-doc" "xrepl" "readline" "syntax-color" "scribble-doc" "future-visualizer" "distributed-places" "serialize-cstruct-lib" "cext-lib" "data-doc" "net-doc" "planet-doc" "mzscheme-doc" "compiler-lib" "drracket" "math-doc" "math-lib"))) (define pkg-desc "Base Racket documentation") (define pkg-authors (quote (eli jay matthias mflatt robby ryanc samth))) (define version "1.1") (define license (quote (Apache-2.0 OR MIT)))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/d336bb10e3e0ec3a20020e9ade9e77d2f6f80b6d/share/pkgs/racket-doc/info.rkt | racket | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("scheme-lib" ("base" #:version "6.5.0.2") "net-lib" "sandbox-lib" ("scribble-lib" #:version "1.34") "racket-index"))) (define build-deps (quote ("rackunit-doc" "compatibility" "errortrace-doc" "typed-racket-doc" "at-exp-lib" "rackunit-lib" "web-server-doc" "gui" "draw" "pict" "parser-tools-doc" "slideshow-doc" "r5rs-doc" "r6rs-doc" "xrepl" "readline" "syntax-color" "scribble-doc" "future-visualizer" "distributed-places" "serialize-cstruct-lib" "cext-lib" "data-doc" "net-doc" "planet-doc" "mzscheme-doc" "compiler-lib" "drracket" "math-doc" "math-lib"))) (define pkg-desc "Base Racket documentation") (define pkg-authors (quote (eli jay matthias mflatt robby ryanc samth))) (define version "1.1") (define license (quote (Apache-2.0 OR MIT)))))
|
|
5c261e4c948271a1b9a6129617a19cf03735319dbe2a7a3162555d884b20784a | borodust/claw-legacy | struct.lisp | (cl:in-package :claw.cffi.c)
(declaim (special *anonymous-field-number*))
(uiop:define-package :%claw.anonymous
(:use))
(defun next-anonymous-field-number ()
(prog1 *anonymous-field-number*
(incf *anonymous-field-number*)))
;;;
;;; RECORD
;;;
(defun field-c-name->lisp (field)
(let ((name (claw.spec:foreign-entity-name field)))
(if (emptyp name)
(let ((lispified (format-symbol :%claw.anonymous "~A"
(next-anonymous-field-number))))
(setf (getf (symbol-plist lispified) :cffi-c-ref-anonymous-field-p) t)
lispified)
(c-name->lisp name :field))))
(defun %generate-c-field (field name kind type count)
(if (and (eq kind :array) (numberp count))
`(,name ,(entity-typespec->cffi type) :count ,count)
`(,name ,(entity-type->cffi field))))
(defun generate-c-field (record-kind field)
(let* ((name (field-c-name->lisp field))
(type (claw.spec:foreign-entity-type field))
(entity (claw.spec:find-foreign-entity type *spec*)))
(export-symbol name)
(append
(destructuring-bind (kind &optional actual-type count)
(ensure-list (if (and entity
(typep entity 'claw.spec:foreign-alias)
(not *recognize-arrays-p*))
(ensure-list (claw.spec:find-basic-type type *spec*))
type))
(%generate-c-field field name kind actual-type count))
(when (eq record-kind :struct)
`(:offset ,(/ (claw.spec:foreign-record-field-bit-offset field) 8))))))
(defun generate-c-fields (kind entity)
(flet ((%generate-c-field (field)
(generate-c-field kind field)))
(let ((*anonymous-field-number* 0))
(mapcar #'%generate-c-field (claw.spec:foreign-record-fields entity)))))
(defun generate-record-binding (kind entity name fields)
(let* ((id (entity-type->cffi entity))
(name (or name
(if (emptyp (claw.spec:foreign-entity-name entity))
(second id)
(c-name->lisp (claw.spec:foreign-entity-name entity) :type))))
(byte-size (/ (claw.spec:foreign-entity-bit-size entity) 8)))
(export-symbol name)
`((,kind (,name :size ,byte-size) ,@fields))))
(defun %generate-forward-declaration (kind name)
`(,kind ,(c-name->lisp name :type)))
;;;
;;; STRUCT
;;;
(defmethod generate-binding ((entity claw.spec:foreign-struct) &key name)
(generate-record-binding 'cffi:defcstruct entity name
(generate-c-fields :struct entity)))
(defmethod generate-forward-declaration ((entity claw.spec:foreign-struct) &key name)
(generate-record-binding 'cffi:defcstruct entity name nil))
(defmethod generate-forward-declaration-from-typespec ((kind (eql :struct))
&optional name &rest opts)
(declare (ignore opts))
(%generate-forward-declaration 'cffi:defcstruct name))
;;;
;;; UNION
;;;
(defmethod generate-binding ((entity claw.spec:foreign-union) &key name)
(generate-record-binding 'cffi:defcunion entity name
(generate-c-fields :union entity)))
(defmethod generate-forward-declaration ((entity claw.spec:foreign-union) &key name)
(generate-record-binding 'cffi:defcunion entity name nil))
(defmethod generate-forward-declaration-from-typespec ((kind (eql :union))
&optional name &rest opts)
(declare (ignore opts))
(%generate-forward-declaration 'cffi:defcunion name))
| null | https://raw.githubusercontent.com/borodust/claw-legacy/3cd4a96fca95eb9e8d5d069426694669f81b2250/src/cffi/c/generator/struct.lisp | lisp |
RECORD
STRUCT
UNION
| (cl:in-package :claw.cffi.c)
(declaim (special *anonymous-field-number*))
(uiop:define-package :%claw.anonymous
(:use))
(defun next-anonymous-field-number ()
(prog1 *anonymous-field-number*
(incf *anonymous-field-number*)))
(defun field-c-name->lisp (field)
(let ((name (claw.spec:foreign-entity-name field)))
(if (emptyp name)
(let ((lispified (format-symbol :%claw.anonymous "~A"
(next-anonymous-field-number))))
(setf (getf (symbol-plist lispified) :cffi-c-ref-anonymous-field-p) t)
lispified)
(c-name->lisp name :field))))
(defun %generate-c-field (field name kind type count)
(if (and (eq kind :array) (numberp count))
`(,name ,(entity-typespec->cffi type) :count ,count)
`(,name ,(entity-type->cffi field))))
(defun generate-c-field (record-kind field)
(let* ((name (field-c-name->lisp field))
(type (claw.spec:foreign-entity-type field))
(entity (claw.spec:find-foreign-entity type *spec*)))
(export-symbol name)
(append
(destructuring-bind (kind &optional actual-type count)
(ensure-list (if (and entity
(typep entity 'claw.spec:foreign-alias)
(not *recognize-arrays-p*))
(ensure-list (claw.spec:find-basic-type type *spec*))
type))
(%generate-c-field field name kind actual-type count))
(when (eq record-kind :struct)
`(:offset ,(/ (claw.spec:foreign-record-field-bit-offset field) 8))))))
(defun generate-c-fields (kind entity)
(flet ((%generate-c-field (field)
(generate-c-field kind field)))
(let ((*anonymous-field-number* 0))
(mapcar #'%generate-c-field (claw.spec:foreign-record-fields entity)))))
(defun generate-record-binding (kind entity name fields)
(let* ((id (entity-type->cffi entity))
(name (or name
(if (emptyp (claw.spec:foreign-entity-name entity))
(second id)
(c-name->lisp (claw.spec:foreign-entity-name entity) :type))))
(byte-size (/ (claw.spec:foreign-entity-bit-size entity) 8)))
(export-symbol name)
`((,kind (,name :size ,byte-size) ,@fields))))
(defun %generate-forward-declaration (kind name)
`(,kind ,(c-name->lisp name :type)))
(defmethod generate-binding ((entity claw.spec:foreign-struct) &key name)
(generate-record-binding 'cffi:defcstruct entity name
(generate-c-fields :struct entity)))
(defmethod generate-forward-declaration ((entity claw.spec:foreign-struct) &key name)
(generate-record-binding 'cffi:defcstruct entity name nil))
(defmethod generate-forward-declaration-from-typespec ((kind (eql :struct))
&optional name &rest opts)
(declare (ignore opts))
(%generate-forward-declaration 'cffi:defcstruct name))
(defmethod generate-binding ((entity claw.spec:foreign-union) &key name)
(generate-record-binding 'cffi:defcunion entity name
(generate-c-fields :union entity)))
(defmethod generate-forward-declaration ((entity claw.spec:foreign-union) &key name)
(generate-record-binding 'cffi:defcunion entity name nil))
(defmethod generate-forward-declaration-from-typespec ((kind (eql :union))
&optional name &rest opts)
(declare (ignore opts))
(%generate-forward-declaration 'cffi:defcunion name))
|
99d79a9f47d5d7283538b71f46bb1fd22bdb74ad09608cbc3678e0aa9e0d16cd | shayan-najd/NativeMetaprogramming | RecompilationChecking.hs | module Options.RecompilationChecking where
import Types
recompilationCheckingOptions :: [Flag]
recompilationCheckingOptions =
[ flag { flagName = "-fforce-recomp"
, flagDescription =
"Turn off recompilation checking. This is implied by any " ++
"``-ddump-X`` option when compiling a single file " ++
"(i.e. when using :ghc-flag:`-c`)."
, flagType = DynamicFlag
, flagReverse = "-fno-force-recomp"
}
]
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/utils/mkUserGuidePart/Options/RecompilationChecking.hs | haskell | module Options.RecompilationChecking where
import Types
recompilationCheckingOptions :: [Flag]
recompilationCheckingOptions =
[ flag { flagName = "-fforce-recomp"
, flagDescription =
"Turn off recompilation checking. This is implied by any " ++
"``-ddump-X`` option when compiling a single file " ++
"(i.e. when using :ghc-flag:`-c`)."
, flagType = DynamicFlag
, flagReverse = "-fno-force-recomp"
}
]
|
|
ade8edc8f9da8ca47442be09982c39a41f47c1bcbff544ec28ed2218da7d741f | blancas/tinypost | main.clj | Copyright ( c ) 2013 . All rights reserved .
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns blancas.tinypost.main
(:gen-class)
(:use [blancas.tinypost scan interpret]))
(defn -main
"\nRuns a PostScript program.
Usage: ps <file>
file A PostScript source file."
[& args]
(try
(if-let [file (first args)]
(let [env (make-env)]
(reduce postscript env (scanner file)))
(println (:doc (meta (var -main)))))
(catch Throwable t
(.println *err* (.getMessage t)))))
(defn run
"Runs the passed PostScript text. Returns the operand stack."
[ps]
(try
(:os (reduce postscript (make-env) (text-scanner ps)))
(catch Throwable t
(.println *err* (.getMessage t)))))
(defn runf
"Runs the passed PostScript file. Returns the operand stack."
[file] (run (slurp file)))
| null | https://raw.githubusercontent.com/blancas/tinypost/1afc54017e68a488a428cae0c417130b1721610d/src/main/clojure/blancas/tinypost/main.clj | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) 2013 . All rights reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns blancas.tinypost.main
(:gen-class)
(:use [blancas.tinypost scan interpret]))
(defn -main
"\nRuns a PostScript program.
Usage: ps <file>
file A PostScript source file."
[& args]
(try
(if-let [file (first args)]
(let [env (make-env)]
(reduce postscript env (scanner file)))
(println (:doc (meta (var -main)))))
(catch Throwable t
(.println *err* (.getMessage t)))))
(defn run
"Runs the passed PostScript text. Returns the operand stack."
[ps]
(try
(:os (reduce postscript (make-env) (text-scanner ps)))
(catch Throwable t
(.println *err* (.getMessage t)))))
(defn runf
"Runs the passed PostScript file. Returns the operand stack."
[file] (run (slurp file)))
|
5bad6b461d68406ec2f5a94149df0ad7aea2bd4e02c0fa6ac3f87822edd0050a | philoskim/debux | core.clj | (ns examples.core
(:require [debux.core :as d])
(:gen-class))
(defn -main []
(println "\nRunning debux examples...\n")
;(d/set-debug-mode! false)
;(d/set-ns-whitelist! ["example.dbg*"])
;(d/set-ns-blacklist! ["example.dbgn"])
You should require dynamically the namespaces that you want to laod
;; if you want to use set-ns-blacklist! or set-ns-whitelist!.
(require 'examples.common)
(require 'examples.dbg)
(require 'examples.dbgn)
(require 'examples.options)
(require 'examples.etc)
;(require 'examples.demo)
;(require 'examples.lab)
)
| null | https://raw.githubusercontent.com/philoskim/debux/24c0641499c21ad86eb43f6b7ca7b7164df8ea37/examples/src/clj/examples/core.clj | clojure | (d/set-debug-mode! false)
(d/set-ns-whitelist! ["example.dbg*"])
(d/set-ns-blacklist! ["example.dbgn"])
if you want to use set-ns-blacklist! or set-ns-whitelist!.
(require 'examples.demo)
(require 'examples.lab) | (ns examples.core
(:require [debux.core :as d])
(:gen-class))
(defn -main []
(println "\nRunning debux examples...\n")
You should require dynamically the namespaces that you want to laod
(require 'examples.common)
(require 'examples.dbg)
(require 'examples.dbgn)
(require 'examples.options)
(require 'examples.etc)
)
|
c553d85509de5fa5afb37de5ff762ef270be6689e9a3facae3de0f9db8efad78 | homebaseio/datalog-console | tree_table.cljs | (ns datalog-console.components.tree-table
{:no-doc true}
(:require [reagent.core :as r]
[clojure.set]))
(declare tree-table)
(defn table-row []
(let [open? (r/atom false)]
(fn [{:keys [level row expandable-row? expand-row render-col full-width? _conn] :as props}]
[:<>
[:tr {:class "odd:bg-gray-100"}
(doall (for [[i col] (map-indexed vector row)]
^{:key (str {:level level :col col})}
[:<>
(if (= 0 i)
[:td {:title (str col)
:style {:padding-left (str (+ 0.25 level) "rem")
:max-width "16rem"}
:class "pr-1 box-content truncate align-top"}
(if (expandable-row? row)
[:button {:class "pr-1 focus:outline-none"
:on-click #(reset! open? (not @open?))}
(if @open? "▼" "▶")]
[:span {:class "pr-1 invisible"} "▶"])
(render-col col)]
[:td {:title (str col)
:class (if full-width? "pl-3 w-full align-top" "pl-3 w-full align-top")} ;truncate
(render-col col)])]))]
(when @open?
[:tr
[:td {:col-span (count row) :class "p-0 relative align-top"
:style {:min-width :max-content}}
[tree-table
(merge props {:level (inc level)
:caption nil
:rows (expand-row row)})]
[:button {:title (str "Collapse " (pr-str row))
:on-click #(reset! open? false)
:style {:margin-left (str (+ 0.4 level) "rem")}
border - gray-300 border - l hover : translate - x-1 hover : border - l-6 ; top-0 left-2.5 absolute h - full border - gray-300 border - l transform hover : border - l-6 hover:-translate - x-1 focus : outline - none
(defn tree-table
"Renders `rows` of data in a table `[[col1 col2] [col1 col2]]`.
If the row is `(expandable-row? row)` then it will render a caret
to toggle the `(expand-row row)` function and step down a level in the
tree. `expand-row` should return a new sequence of rows."
[{:keys [level caption head-row rows render-col _expandable-row? _expand-row _full-width? _conn]
:as props}]
(let [level (or level 0)
render-col (or render-col str)
props (merge props {:level level :render-col render-col})]
[:table {:class "table-auto w-full relative"}
(when caption
[:caption {:class "sr-only"}
caption])
[:thead {:class (if (= 0 level) "" "sr-only")}
[:tr {:class "pl-1 font-bold text-left"}
^{:key (str "first th " (first head-row))}
[:th {:class "pl-1"} (first head-row)]
(for [col (rest head-row)]
^{:key (str "th-" level "-" (pr-str col))}
[:th {:class "pl-3"} col])]]
[:tbody
(for [[i row] (map-indexed vector rows)]
^{:key (str "tr-" level "-" i)}
[table-row (merge props {:row row})])]])) | null | https://raw.githubusercontent.com/homebaseio/datalog-console/a041f920ffb6434a14f81efe79197d56819d6363/src/main/datalog_console/components/tree_table.cljs | clojure | truncate
top-0 left-2.5 absolute h - full border - gray-300 border - l transform hover : border - l-6 hover:-translate - x-1 focus : outline - none | (ns datalog-console.components.tree-table
{:no-doc true}
(:require [reagent.core :as r]
[clojure.set]))
(declare tree-table)
(defn table-row []
(let [open? (r/atom false)]
(fn [{:keys [level row expandable-row? expand-row render-col full-width? _conn] :as props}]
[:<>
[:tr {:class "odd:bg-gray-100"}
(doall (for [[i col] (map-indexed vector row)]
^{:key (str {:level level :col col})}
[:<>
(if (= 0 i)
[:td {:title (str col)
:style {:padding-left (str (+ 0.25 level) "rem")
:max-width "16rem"}
:class "pr-1 box-content truncate align-top"}
(if (expandable-row? row)
[:button {:class "pr-1 focus:outline-none"
:on-click #(reset! open? (not @open?))}
(if @open? "▼" "▶")]
[:span {:class "pr-1 invisible"} "▶"])
(render-col col)]
[:td {:title (str col)
(render-col col)])]))]
(when @open?
[:tr
[:td {:col-span (count row) :class "p-0 relative align-top"
:style {:min-width :max-content}}
[tree-table
(merge props {:level (inc level)
:caption nil
:rows (expand-row row)})]
[:button {:title (str "Collapse " (pr-str row))
:on-click #(reset! open? false)
:style {:margin-left (str (+ 0.4 level) "rem")}
(defn tree-table
"Renders `rows` of data in a table `[[col1 col2] [col1 col2]]`.
If the row is `(expandable-row? row)` then it will render a caret
to toggle the `(expand-row row)` function and step down a level in the
tree. `expand-row` should return a new sequence of rows."
[{:keys [level caption head-row rows render-col _expandable-row? _expand-row _full-width? _conn]
:as props}]
(let [level (or level 0)
render-col (or render-col str)
props (merge props {:level level :render-col render-col})]
[:table {:class "table-auto w-full relative"}
(when caption
[:caption {:class "sr-only"}
caption])
[:thead {:class (if (= 0 level) "" "sr-only")}
[:tr {:class "pl-1 font-bold text-left"}
^{:key (str "first th " (first head-row))}
[:th {:class "pl-1"} (first head-row)]
(for [col (rest head-row)]
^{:key (str "th-" level "-" (pr-str col))}
[:th {:class "pl-3"} col])]]
[:tbody
(for [[i row] (map-indexed vector rows)]
^{:key (str "tr-" level "-" i)}
[table-row (merge props {:row row})])]])) |
1355076d4724136e4456c807b5cffb0e51c25f2d73554ac0216a1369a0860d00 | taruen/apertiumpp | add-travis-yml.rkt | #lang racket
Add .travis.yml file to an Apertium linguistic data package if it 's missing
By default , will only ` make ' the package . It wo n't run ` make test '
; or `make check` or anything else.
(require rash)
(require "turkic-repos.rkt")
(define MONOLINGUAL-TRAVIS-YML
#<<end
dist: xenial
before_install:
- wget -nightly.sh -O - | sudo bash
- sudo apt-get install hfst apertium lttoolbox apertium-dev lttoolbox-dev libhfst-dev cg3 python3-libhfst
- rm tests/morphophonology/test.py
- wget -tat/master/tests/morphophonology/test.py -O tests/morphophonology/test.py
script:
- ./autogen.sh
- make
# - make check
notifications:
irc:
channels:
- "chat.freenode.net#apertium"
on_failure: change
on_success: never
email:
recipients:
-
on_failure: always
on_success: always
end
)
;(for ([l MONOLINGUAL])
( define ( string - append " apertium - all/ " l " .travis.yml " ) )
( when ( not ( file - exists ? ) )
( display - to - file MONOLINGUAL - TRAVIS - YML ) ) )
; git pull
; etc | null | https://raw.githubusercontent.com/taruen/apertiumpp/73eeacc19015170e54c77824e015224f6456cf3e/apertiumpp/cookbook/add-travis-yml.rkt | racket | or `make check` or anything else.
(for ([l MONOLINGUAL])
git pull
etc | #lang racket
Add .travis.yml file to an Apertium linguistic data package if it 's missing
By default , will only ` make ' the package . It wo n't run ` make test '
(require rash)
(require "turkic-repos.rkt")
(define MONOLINGUAL-TRAVIS-YML
#<<end
dist: xenial
before_install:
- wget -nightly.sh -O - | sudo bash
- sudo apt-get install hfst apertium lttoolbox apertium-dev lttoolbox-dev libhfst-dev cg3 python3-libhfst
- rm tests/morphophonology/test.py
- wget -tat/master/tests/morphophonology/test.py -O tests/morphophonology/test.py
script:
- ./autogen.sh
- make
# - make check
notifications:
irc:
channels:
- "chat.freenode.net#apertium"
on_failure: change
on_success: never
email:
recipients:
-
on_failure: always
on_success: always
end
)
( define ( string - append " apertium - all/ " l " .travis.yml " ) )
( when ( not ( file - exists ? ) )
( display - to - file MONOLINGUAL - TRAVIS - YML ) ) ) |
221206ec0ee732258943ab125d776d7766571b4d8372d9cbabba2c416399f5dd | racket/htdp | abstraction.rkt | #lang racket
(provide (all-from-out 2htdp/abstraction))
(require 2htdp/abstraction)
| null | https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-lib/teachpack/2htdp/abstraction.rkt | racket | #lang racket
(provide (all-from-out 2htdp/abstraction))
(require 2htdp/abstraction)
|
|
cc876e4cd308d60531f67088d89ed82ce9b809848fa753639b12827d607ef7fe | mlemerre/l-lang | cpsbase.ml | include Cpsbasepack.Cpsdef;;
module Print = Cpsbasepack.Cpsprint;;
module Change = Cpsbasepack.Cpschange;;
module Build = Cpsbasepack.Cpsbuild;;
module Check = Cpsbasepack.Cpscheck;;
module Traverse = Cpsbasepack.Cpstraverse;;
module type VAR = sig
type var
type occur_maker
type occur
module Var: sig
type number_of_occurrences =
| No_occurrence
| One_occurrence of occur
| Several_occurrences
val number_of_occurrences: var -> number_of_occurrences
val fold_on_occurrences: var -> 'a -> ('a -> occur -> 'a) -> 'a
val binding_site: var -> enclosing
val to_string : var -> string
module Map : Map.S with type key = var
module Set : Set.S with type elt = var
end
module Occur: sig
type maker = occur_maker
val maker: var -> maker
val rec_maker: var -> maker
val binding_variable : occur -> var
val to_string : occur -> string
module Map : Map.S with type key = occur
module Set : Set.S with type elt = occur
end
end
| null | https://raw.githubusercontent.com/mlemerre/l-lang/88201e861c6cc30bb3b9510d7f55c681eded4085/src/cps/cpsbase.ml | ocaml | include Cpsbasepack.Cpsdef;;
module Print = Cpsbasepack.Cpsprint;;
module Change = Cpsbasepack.Cpschange;;
module Build = Cpsbasepack.Cpsbuild;;
module Check = Cpsbasepack.Cpscheck;;
module Traverse = Cpsbasepack.Cpstraverse;;
module type VAR = sig
type var
type occur_maker
type occur
module Var: sig
type number_of_occurrences =
| No_occurrence
| One_occurrence of occur
| Several_occurrences
val number_of_occurrences: var -> number_of_occurrences
val fold_on_occurrences: var -> 'a -> ('a -> occur -> 'a) -> 'a
val binding_site: var -> enclosing
val to_string : var -> string
module Map : Map.S with type key = var
module Set : Set.S with type elt = var
end
module Occur: sig
type maker = occur_maker
val maker: var -> maker
val rec_maker: var -> maker
val binding_variable : occur -> var
val to_string : occur -> string
module Map : Map.S with type key = occur
module Set : Set.S with type elt = occur
end
end
|
|
e982723ecc90e7852d0190a5849c13b0e7b46219d09f2b9337a1be42beb9783b | mark-watson/lisp_practical_semantic_web | packages.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
$ Header : /usr / local / cvsrep / drakma / packages.lisp , v 1.22 2008/01/14 01:57:01 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :drakma
(:use :cl :puri :flexi-streams :chunga)
;; the variable defined in the ASDF system definition
(:import-from :drakma-asd :*drakma-version-string*)
(:shadow :syntax-error :parameter-error)
(:export :*allow-dotless-cookie-domains-p*
:*body-format-function*
:*remove-duplicate-cookies-p*
:*drakma-default-external-format*
:*header-stream*
:*ignore-unparseable-cookie-dates-p*
:*text-content-types*
:cookie
:cookie-error
:cookie-error-cookie
:cookie-date-parse-error
:cookie-domain
:cookie-expires
:cookie-http-only-p
:cookie-jar
:cookie-jar-cookies
:cookie-name
:cookie-path
:cookie-securep
:cookie-value
:cookie=
:delete-old-cookies
:drakma-condition
:drakma-error
:drakma-warning
:get-content-type
:header-value
:http-request
:parameter-error
:parameter-present-p
:parameter-value
:parse-cookie-date
:read-tokens-and-parameters
:split-tokens
:syntax-error))
| null | https://raw.githubusercontent.com/mark-watson/lisp_practical_semantic_web/2d9d5bb06b574ab0bff15664fe747a5b99e1fb1b/utils/drakma-1.2.3/packages.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; 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.
the variable defined in the ASDF system definition | $ Header : /usr / local / cvsrep / drakma / packages.lisp , v 1.22 2008/01/14 01:57:01 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-user)
(defpackage :drakma
(:use :cl :puri :flexi-streams :chunga)
(:import-from :drakma-asd :*drakma-version-string*)
(:shadow :syntax-error :parameter-error)
(:export :*allow-dotless-cookie-domains-p*
:*body-format-function*
:*remove-duplicate-cookies-p*
:*drakma-default-external-format*
:*header-stream*
:*ignore-unparseable-cookie-dates-p*
:*text-content-types*
:cookie
:cookie-error
:cookie-error-cookie
:cookie-date-parse-error
:cookie-domain
:cookie-expires
:cookie-http-only-p
:cookie-jar
:cookie-jar-cookies
:cookie-name
:cookie-path
:cookie-securep
:cookie-value
:cookie=
:delete-old-cookies
:drakma-condition
:drakma-error
:drakma-warning
:get-content-type
:header-value
:http-request
:parameter-error
:parameter-present-p
:parameter-value
:parse-cookie-date
:read-tokens-and-parameters
:split-tokens
:syntax-error))
|
548c4e801331f3fe1ebbe2ed7b223b3e6a6ed5377b8933d33c164a6a8a3e4c21 | haskell-works/avro | JSONSpec.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Avro.JSONSpec where
import Control.Monad (forM_)
import Control.Monad.Identity (Identity (..))
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Data.Avro.Deriving
import Data.Avro.EitherN
import Data.Avro.JSON
import Avro.Data.Endpoint
import Avro.Data.Enums
import Avro.Data.Reused
import Avro.Data.Unions
import HaskellWorks.Hspec.Hedgehog
import Hedgehog
import Hedgehog.Gen as Gen
import Hedgehog.Range as Range
import Paths_avro
import Test.Hspec
import System.Directory (doesFileExist, getCurrentDirectory)
import System.Environment (setEnv)
HLINT ignore " Redundant do "
deriveAvro "test/data/unions-no-namespace.avsc"
spec :: Spec
spec = describe "Avro.JSONSpec: JSON serialization/parsing" $ do
it "should pass" $ require $ withTests 1 $ property success
-- it "should do roundtrip (enums)" $ require $ property $ do
msg < - forAll
tripping msg ( Aeson.encode . ) parseJSON
-- it "should do roundtrip (reused)" $ require $ property $ do
-- msg <- forAll reusedWrapperGen
tripping msg ( Aeson.encode . ) parseJSON
-- it "should do roundtrip (small)" $ require $ property $ do
-- msg <- forAll endpointGen
tripping msg ( Aeson.encode . ) parseJSON
-- enumsExampleJSON <- runIO $ getFileName "test/data/enums-object.json" >>= LBS.readFile
-- it "should parse (enums)" $ do
let expected = EnumWrapper 37 " blarg " EnumReasonInstead
parseJSON enumsExampleJSON ` shouldBe ` pure expected
-- let unionsExampleA = Unions
-- { unionsScalars = Left "blarg"
-- , unionsNullable = Nothing
, unionsRecords = Left $ Foo { fooStuff = " stuff " }
-- , unionsSameFields = Left $ Foo { fooStuff = "foo stuff" }
-- , unionsArrayAndMap = Left ["foo"]
, unionsOne = Identity 42
, = E3_1 37
-- , unionsFour = E4_2 "foo"
-- , unionsFive = E5_4 $ Foo { fooStuff = "foo stuff" }
-- , unionsSix = E6_2 "foo"
, = E7_6 6.28
, = E8_3 37
-- , unionsNine = E9_1 37
, unionsTen = E10_9 $ BS.pack [ 70 , 79 , 79 , 66 , 65 , 82 ]
-- }
= Unions
{ unionsScalars = Right 37
, unionsNullable = Just 42
, unionsRecords = Right $ Bar { barStuff = " stuff "
, barThings = Foo " things "
-- }
-- , unionsSameFields = Right $ NotFoo { notFooStuff = "not foo stuff" }
, unionsArrayAndMap = Right $ Map.fromList [ ( " a " , 5 ) ]
, unionsOne = Identity 42
, E3_3 37
-- , unionsFour = E4_4 $ Foo { fooStuff = "foo stuff" }
-- , unionsFive = E5_5 $ NotFoo { notFooStuff = "not foo stuff" }
, unionsSix = E6_6 6.28
, = E7_7 False
, = E8_8 2.718
, unionsNine = E9_9 $ BS.pack [ 70 , 79 , 79 , 66 , 65 , 82 ]
, unionsTen = E10_10 $ Bar { barStuff = " bar stuff " ,
-- barThings = Foo { fooStuff = "things" }
-- }
-- }
-- it "should roundtrip (unions)" $ do
-- forM_ [unionsExampleA, unionsExampleB] $ \ msg ->
parseJSON ( Aeson.encode ( toJSON msg ) ) ` shouldBe ` pure msg
-- unionsJsonA <- runIO $ getFileName "test/data/unions-object-a.json" >>= LBS.readFile
-- unionsJsonB <- runIO $ getFileName "test/data/unions-object-b.json" >>= LBS.readFile
-- it "should parse (unions)" $ do
parseJSON unionsJsonA ` shouldBe ` pure unionsExampleA
parseJSON unionsJsonB ` shouldBe ` pure unionsExampleB
-- let unionsNoNamespaceA = UnionsNoNamespace (Left TypeA)
unionsNoNamespaceB = UnionsNoNamespace ( Right TypeB )
-- it "should roundtrip (unions-no-namespace)" $ do
parseJSON ( Aeson.encode ( toJSON unionsNoNamespaceA ) ) ` shouldBe `
-- pure unionsNoNamespaceA
parseJSON ( Aeson.encode ( toJSON unionsNoNamespaceB ) ) ` shouldBe `
-- pure unionsNoNamespaceB
-- let noNamespace = "test/data/unions-no-namespace-object.json"
-- objectA = "{ \"unionField\" : { \"TypeA\" : {} } }"
-- objectB = "{ \"unionField\" : { \"TypeB\" : {} } }"
-- it "should parse (unions-no-namespace)" $ do
parseJSON objectA ` shouldBe ` pure unionsNoNamespaceA
parseJSON objectB ` shouldBe ` pure unionsNoNamespaceB
getFileName :: FilePath -> IO FilePath
getFileName p = do
path <- getDataFileName p
isOk <- doesFileExist path
pure $ if isOk then path else p
| null | https://raw.githubusercontent.com/haskell-works/avro/aeea12b07a1c6fcc3708d1afe7209c5497665296/test/Avro/JSONSpec.hs | haskell | # LANGUAGE OverloadedStrings #
it "should do roundtrip (enums)" $ require $ property $ do
it "should do roundtrip (reused)" $ require $ property $ do
msg <- forAll reusedWrapperGen
it "should do roundtrip (small)" $ require $ property $ do
msg <- forAll endpointGen
enumsExampleJSON <- runIO $ getFileName "test/data/enums-object.json" >>= LBS.readFile
it "should parse (enums)" $ do
let unionsExampleA = Unions
{ unionsScalars = Left "blarg"
, unionsNullable = Nothing
, unionsSameFields = Left $ Foo { fooStuff = "foo stuff" }
, unionsArrayAndMap = Left ["foo"]
, unionsFour = E4_2 "foo"
, unionsFive = E5_4 $ Foo { fooStuff = "foo stuff" }
, unionsSix = E6_2 "foo"
, unionsNine = E9_1 37
}
}
, unionsSameFields = Right $ NotFoo { notFooStuff = "not foo stuff" }
, unionsFour = E4_4 $ Foo { fooStuff = "foo stuff" }
, unionsFive = E5_5 $ NotFoo { notFooStuff = "not foo stuff" }
barThings = Foo { fooStuff = "things" }
}
}
it "should roundtrip (unions)" $ do
forM_ [unionsExampleA, unionsExampleB] $ \ msg ->
unionsJsonA <- runIO $ getFileName "test/data/unions-object-a.json" >>= LBS.readFile
unionsJsonB <- runIO $ getFileName "test/data/unions-object-b.json" >>= LBS.readFile
it "should parse (unions)" $ do
let unionsNoNamespaceA = UnionsNoNamespace (Left TypeA)
it "should roundtrip (unions-no-namespace)" $ do
pure unionsNoNamespaceA
pure unionsNoNamespaceB
let noNamespace = "test/data/unions-no-namespace-object.json"
objectA = "{ \"unionField\" : { \"TypeA\" : {} } }"
objectB = "{ \"unionField\" : { \"TypeB\" : {} } }"
it "should parse (unions-no-namespace)" $ do | # LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Avro.JSONSpec where
import Control.Monad (forM_)
import Control.Monad.Identity (Identity (..))
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Data.Avro.Deriving
import Data.Avro.EitherN
import Data.Avro.JSON
import Avro.Data.Endpoint
import Avro.Data.Enums
import Avro.Data.Reused
import Avro.Data.Unions
import HaskellWorks.Hspec.Hedgehog
import Hedgehog
import Hedgehog.Gen as Gen
import Hedgehog.Range as Range
import Paths_avro
import Test.Hspec
import System.Directory (doesFileExist, getCurrentDirectory)
import System.Environment (setEnv)
HLINT ignore " Redundant do "
deriveAvro "test/data/unions-no-namespace.avsc"
spec :: Spec
spec = describe "Avro.JSONSpec: JSON serialization/parsing" $ do
it "should pass" $ require $ withTests 1 $ property success
msg < - forAll
tripping msg ( Aeson.encode . ) parseJSON
tripping msg ( Aeson.encode . ) parseJSON
tripping msg ( Aeson.encode . ) parseJSON
let expected = EnumWrapper 37 " blarg " EnumReasonInstead
parseJSON enumsExampleJSON ` shouldBe ` pure expected
, unionsRecords = Left $ Foo { fooStuff = " stuff " }
, unionsOne = Identity 42
, = E3_1 37
, = E7_6 6.28
, = E8_3 37
, unionsTen = E10_9 $ BS.pack [ 70 , 79 , 79 , 66 , 65 , 82 ]
= Unions
{ unionsScalars = Right 37
, unionsNullable = Just 42
, unionsRecords = Right $ Bar { barStuff = " stuff "
, barThings = Foo " things "
, unionsArrayAndMap = Right $ Map.fromList [ ( " a " , 5 ) ]
, unionsOne = Identity 42
, E3_3 37
, unionsSix = E6_6 6.28
, = E7_7 False
, = E8_8 2.718
, unionsNine = E9_9 $ BS.pack [ 70 , 79 , 79 , 66 , 65 , 82 ]
, unionsTen = E10_10 $ Bar { barStuff = " bar stuff " ,
parseJSON ( Aeson.encode ( toJSON msg ) ) ` shouldBe ` pure msg
parseJSON unionsJsonA ` shouldBe ` pure unionsExampleA
parseJSON unionsJsonB ` shouldBe ` pure unionsExampleB
unionsNoNamespaceB = UnionsNoNamespace ( Right TypeB )
parseJSON ( Aeson.encode ( toJSON unionsNoNamespaceA ) ) ` shouldBe `
parseJSON ( Aeson.encode ( toJSON unionsNoNamespaceB ) ) ` shouldBe `
parseJSON objectA ` shouldBe ` pure unionsNoNamespaceA
parseJSON objectB ` shouldBe ` pure unionsNoNamespaceB
getFileName :: FilePath -> IO FilePath
getFileName p = do
path <- getDataFileName p
isOk <- doesFileExist path
pure $ if isOk then path else p
|
1e0736cea2a831275aa563b0e13dcf2cb0e926541104ac55786343c47c5ca3b2 | fosskers/kanji | Base.hs | {-# LANGUAGE OverloadedStrings #-}
module Pages.Base where
import Lucid
import Lucid.Base (makeAttribute)
import Pages.Bootstrap
---
-- | The basic template for all pages.
base :: Html () -> Html ()
base content = do
doctype_
html_ $ do
head_ $ do
meta_ [charset_ "utf-8"]
title_ "NanQ - Analyse Japanese Text"
link_ [ href_ "/assets/bootstrap.min.css"
, rel_ "stylesheet"
, media_ "all"
, type_ "text/css" ]
body_ [style_ "padding-top: 20px;"] $
containerFluid_ $ do
row_ $
col6_ [class_ "col-md-offset-3"] $
div_ [class_ "header clearfix"] $ do
nav_ $ ul_ [class_ "nav nav-pills pull-right"] $
li_ [role_ "presentation"] $
a_ [href_ "/about", class_ "btn btn-default"] "About"
h3_ [ class_ "text-muted"
, style_ "margin-top: 0;margin-bottom: 0;line-height: 40px;"
] $ do
a_ [href_ "/"] $ img_ [src_ "/assets/logo-small.png"]
"・NanQ - Analyse Japanese Text・漢字分析"
hr_ []
content
row_ $
col6_ [class_ "col-md-offset-3"] $ do
hr_ []
center_ ghButton
center_ $ a_ [href_ "/"] $ img_ [src_ "/assets/logo.png"]
ghButton :: Html ()
ghButton = iframe_
[ src_ "-btn.html?user=fosskers&type=follow&count=true&size=large"
, makeAttribute "frameborder" "0"
, makeAttribute "scrolling" "0"
, width_ "180px"
, height_ "30px"] ""
-- | The Home Page, accessible through the `/` endpoint.
home :: Html ()
home = row_ $ do
col4_ [class_ "col-md-offset-1"] explanation
col6_ form
form :: Html ()
form = form_ [action_ "/analyse", method_ "POST"] $
div_ [class_ "input"] $ do
label_ [for_ "japText"] "Japanese Text・日本語入力"
textarea_ [ id_ "japText"
, class_ "form-control"
, name_ "japText"
, rows_ "15"
, placeholder_ "Paste your text here."
] ""
center_ [style_ "padding-top:15px;"] $
button_ [ class_ "btn btn-primary btn-lg", type_ "submit" ] "Analyse・分析"
explanation :: Html ()
explanation = div_ [class_ "jumbotron"] $ do
p_ . toHtml $ unwords [ "Are you a learner or native speaker of Japanese?"
, "You can use this website to analyse Japanese text"
, "for its Kanji difficulty."
]
p_ $ mconcat [ "日本語のネイティブも学生も、日本語の文章の漢字難易度を"
, "分析するためにこのサイトを無料に利用できます。" ]
| null | https://raw.githubusercontent.com/fosskers/kanji/93dd7d16d1a3690db36ca0ffbeb21e05083c42ea/nanq-site/Pages/Base.hs | haskell | # LANGUAGE OverloadedStrings #
-
| The basic template for all pages.
| The Home Page, accessible through the `/` endpoint. |
module Pages.Base where
import Lucid
import Lucid.Base (makeAttribute)
import Pages.Bootstrap
base :: Html () -> Html ()
base content = do
doctype_
html_ $ do
head_ $ do
meta_ [charset_ "utf-8"]
title_ "NanQ - Analyse Japanese Text"
link_ [ href_ "/assets/bootstrap.min.css"
, rel_ "stylesheet"
, media_ "all"
, type_ "text/css" ]
body_ [style_ "padding-top: 20px;"] $
containerFluid_ $ do
row_ $
col6_ [class_ "col-md-offset-3"] $
div_ [class_ "header clearfix"] $ do
nav_ $ ul_ [class_ "nav nav-pills pull-right"] $
li_ [role_ "presentation"] $
a_ [href_ "/about", class_ "btn btn-default"] "About"
h3_ [ class_ "text-muted"
, style_ "margin-top: 0;margin-bottom: 0;line-height: 40px;"
] $ do
a_ [href_ "/"] $ img_ [src_ "/assets/logo-small.png"]
"・NanQ - Analyse Japanese Text・漢字分析"
hr_ []
content
row_ $
col6_ [class_ "col-md-offset-3"] $ do
hr_ []
center_ ghButton
center_ $ a_ [href_ "/"] $ img_ [src_ "/assets/logo.png"]
ghButton :: Html ()
ghButton = iframe_
[ src_ "-btn.html?user=fosskers&type=follow&count=true&size=large"
, makeAttribute "frameborder" "0"
, makeAttribute "scrolling" "0"
, width_ "180px"
, height_ "30px"] ""
home :: Html ()
home = row_ $ do
col4_ [class_ "col-md-offset-1"] explanation
col6_ form
form :: Html ()
form = form_ [action_ "/analyse", method_ "POST"] $
div_ [class_ "input"] $ do
label_ [for_ "japText"] "Japanese Text・日本語入力"
textarea_ [ id_ "japText"
, class_ "form-control"
, name_ "japText"
, rows_ "15"
, placeholder_ "Paste your text here."
] ""
center_ [style_ "padding-top:15px;"] $
button_ [ class_ "btn btn-primary btn-lg", type_ "submit" ] "Analyse・分析"
explanation :: Html ()
explanation = div_ [class_ "jumbotron"] $ do
p_ . toHtml $ unwords [ "Are you a learner or native speaker of Japanese?"
, "You can use this website to analyse Japanese text"
, "for its Kanji difficulty."
]
p_ $ mconcat [ "日本語のネイティブも学生も、日本語の文章の漢字難易度を"
, "分析するためにこのサイトを無料に利用できます。" ]
|
50b2a12e3977fae75889208c732ffe50223423c955c6aa296204b03b02442286 | DanielG/ghc-mod | MonadSpec.hs | module MonadSpec where
import Test.Hspec
import TestUtils
import Control.Monad.Error.Class
import Control.Concurrent
import Control.Exception
spec :: Spec
spec = do
describe "When using GhcModT in a do block" $
it "a pattern match failure causes a call to `fail` on ErrorT in the monad stack" $ do
(a, _h)
<- runGmOutDef $ runGhcModT defaultOptions $
do
Just _ <- return Nothing
return "hello"
`catchError` (const $ fail "oh noes")
a `shouldBe` (Left $ GMEString "oh noes")
describe "runGhcModT" $
it "throws an exception when run in multiple threads" $ do
mv_ex :: MVar (Either SomeException ())
<- newEmptyMVar
mv_startup_barrier :: MVar ()
<- newEmptyMVar
_t1 <- forkOS $ do
wait ( inside ) for t2 to receive the exception
_ <- runD $ liftIO $ do
putMVar mv_startup_barrier ()
readMVar mv_ex
return ()
_t2 <- forkOS $ do
wait for t1 to be in GhcModT
res <- try $ runD $ return ()
res' <- evaluate res
putMVar mv_ex res'
ex <- takeMVar mv_ex
isLeft ex `shouldBe` True
isLeft :: Either a b -> Bool
isLeft (Right _) = False
isLeft (Left _) = True
| null | https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/test/MonadSpec.hs | haskell | module MonadSpec where
import Test.Hspec
import TestUtils
import Control.Monad.Error.Class
import Control.Concurrent
import Control.Exception
spec :: Spec
spec = do
describe "When using GhcModT in a do block" $
it "a pattern match failure causes a call to `fail` on ErrorT in the monad stack" $ do
(a, _h)
<- runGmOutDef $ runGhcModT defaultOptions $
do
Just _ <- return Nothing
return "hello"
`catchError` (const $ fail "oh noes")
a `shouldBe` (Left $ GMEString "oh noes")
describe "runGhcModT" $
it "throws an exception when run in multiple threads" $ do
mv_ex :: MVar (Either SomeException ())
<- newEmptyMVar
mv_startup_barrier :: MVar ()
<- newEmptyMVar
_t1 <- forkOS $ do
wait ( inside ) for t2 to receive the exception
_ <- runD $ liftIO $ do
putMVar mv_startup_barrier ()
readMVar mv_ex
return ()
_t2 <- forkOS $ do
wait for t1 to be in GhcModT
res <- try $ runD $ return ()
res' <- evaluate res
putMVar mv_ex res'
ex <- takeMVar mv_ex
isLeft ex `shouldBe` True
isLeft :: Either a b -> Bool
isLeft (Right _) = False
isLeft (Left _) = True
|
|
c1ce850ed05b629b5dabbadc5632423d03fc1e3b1e95d1d0a574182ff050e555 | parapluu/Concuerror | ets_new.erl | %%%----------------------------------------------------------------------
Copyright ( c ) 2012 , < > ,
< >
and < > .
%%% All rights reserved.
%%%
This file is distributed under the Simplified BSD License .
%%% Details can be found in the LICENSE file.
%%%----------------------------------------------------------------------
Authors : < >
%%% Description : Test the `ets:new' instrumentation
%%%----------------------------------------------------------------------
-module(ets_new).
-export([scenarios/0]).
-export([test/0]).
scenarios() ->
[{test, inf, dpor}].
test() ->
spawn(fun child/0),
ets:new(table, [named_table, public]),
ets:delete(table).
%% There should be an exception if this happens
%% between `new' and `delete'
child() ->
case ets:info(table) of
undefined -> ok;
_ -> 1 = 2
end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/basic_tests/src/ets_new.erl | erlang | ----------------------------------------------------------------------
All rights reserved.
Details can be found in the LICENSE file.
----------------------------------------------------------------------
Description : Test the `ets:new' instrumentation
----------------------------------------------------------------------
There should be an exception if this happens
between `new' and `delete' | Copyright ( c ) 2012 , < > ,
< >
and < > .
This file is distributed under the Simplified BSD License .
Authors : < >
-module(ets_new).
-export([scenarios/0]).
-export([test/0]).
scenarios() ->
[{test, inf, dpor}].
test() ->
spawn(fun child/0),
ets:new(table, [named_table, public]),
ets:delete(table).
child() ->
case ets:info(table) of
undefined -> ok;
_ -> 1 = 2
end.
|
e5c48ba7e55e052c6419cc3d04b63745e4fed817fad757df23b823c3b427dc46 | bmeurer/ocaml-rbtrees | rbset.ml | -
* Copyright ( c ) 2007 , < >
*
* Permission is hereby granted , free of charge , to any person obtaining a
* copy of this software and associated documentation files ( the " Software " ) ,
* to deal in the Software without restriction , including without limitation
* the rights to use , copy , modify , merge , publish , distribute , sublicense ,
* and/or sell copies of the Software , and to permit persons to whom the
* Software is furnished to do so , subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software .
*
* THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
* OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
* LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
* FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE .
* Copyright (c) 2007, Benedikt Meurer <>
*
* 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.
*)
This is my implementation of Red - Black Trees for OCaml . It is based upon
* " Red - Black Trees in a Functional Setting " , in " Functional
* Pearls " .
* Red - Black Trees are exposed via a map and a set API , which is designed to
* be compatible with the Map and Set modules in the OCaml standard library
* ( which are implemented using AVL trees ) . You can use the Rbmap and * modules as drop - in replacement for the Map and Set modules .
* "Red-Black Trees in a Functional Setting", Chris Okasaki in "Functional
* Pearls".
* Red-Black Trees are exposed via a map and a set API, which is designed to
* be compatible with the Map and Set modules in the OCaml standard library
* (which are implemented using AVL trees). You can use the Rbmap and Rbset
* modules as drop-in replacement for the Map and Set modules.
*)
module type OrderedType =
sig
type t
val compare: t -> t -> int
end
module type S =
sig
type elt
type t
val empty: t
val is_empty: t -> bool
val mem: elt -> t -> bool
val add: elt -> t -> t
val singleton: elt -> t
val remove: elt -> t -> t
val union: t -> t -> t
val inter: t -> t -> t
val diff: t -> t -> t
val compare: t -> t -> int
val equal: t -> t -> bool
val subset: t -> t -> bool
val iter: (elt -> unit) -> t -> unit
val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val for_all: (elt -> bool) -> t -> bool
val exists: (elt -> bool) -> t -> bool
val filter: (elt -> bool) -> t -> t
val partition: (elt -> bool) -> t -> t * t
val cardinal: t -> int
val elements: t -> elt list
val min_elt: t -> elt
val max_elt: t -> elt
val choose: t -> elt
val split: elt -> t -> t * bool * t
end
module Make(Ord: OrderedType) =
struct
type elt = Ord.t
type t =
| Black of t * elt * t
| Red of t * elt * t
| Empty
type enum =
| End
| More of elt * t * enum
let rec enum s e =
match s with
| Empty -> e
| Black(l, x, r) | Red(l, x, r) -> enum l (More(x, r, e))
let blackify = function
| Red(l, x, r) -> Black(l, x, r), false
| s -> s, true
let empty = Empty
let is_empty = function
| Empty -> true
| _ -> false
let rec mem x = function
| Empty ->
false
| Red(l, y, r)
| Black(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then mem x l
else if c > 0 then mem x r
else true
let balance_left l x r =
match l, x, r with
| Red(Red(a, x, b), y, c), z, d
| Red(a, x, Red(b, y, c)), z, d ->
Red(Black(a, x, b), y, Black(c, z, d))
| l, x, r ->
Black(l, x, r)
let balance_right l x r =
match l, x, r with
| a, x, Red(Red(b, y, c), z, d)
| a, x, Red(b, y, Red(c, z, d)) ->
Red(Black(a, x, b), y, Black(c, z, d))
| l, x, r ->
Black(l, x, r)
let add x s =
let rec add_aux = function
| Empty ->
Red(Empty, x, Empty)
| Red(l, y, r) as s ->
let c = Ord.compare x y in
if c < 0 then
Red(add_aux l, y, r)
else if c > 0 then
Red(l, y, add_aux r)
else
s
| Black(l, y, r) as s ->
let c = Ord.compare x y in
if c < 0 then
balance_left (add_aux l) y r
else if c > 0 then
balance_right l y (add_aux r)
else
s
in fst (blackify (add_aux s))
let singleton x =
Black(Empty, x, Empty)
let unbalanced_left = function
| Red(Black(a, x, b), y, c) -> balance_left (Red(a, x, b)) y c, false
| Black(Black(a, x, b), y, c) -> balance_left (Red(a, x, b)) y c, true
| Black(Red(a, x, Black(b, y, c)), z, d) -> Black(a, x, balance_left (Red(b, y, c)) z d), false
| _ -> assert false
let unbalanced_right = function
| Red(a, x, Black(b, y, c)) -> balance_right a x (Red(b, y, c)), false
| Black(a, x, Black(b, y, c)) -> balance_right a x (Red(b, y, c)), true
| Black(a, x, Red(Black(b, y, c), z, d)) -> Black(balance_right a x (Red(b, y, c)), z, d), false
| _ -> assert false
let rec remove_min = function
| Empty
| Black(Empty, _, Black(_)) ->
assert false
| Black(Empty, x, Empty) ->
Empty, x, true
| Black(Empty, x, Red(l, y, r)) ->
Black(l, y, r), x, false
| Red(Empty, x, r) ->
r, x, false
| Black(l, x, r) ->
let l, y, d = remove_min l in
let s = Black(l, x, r) in
if d then
let s, d = unbalanced_right s in s, y, d
else
s, y, false
| Red(l, x, r) ->
let l, y, d = remove_min l in
let s = Red(l, x, r) in
if d then
let s, d = unbalanced_right s in s, y, d
else
s, y, false
let remove x s =
let rec remove_aux = function
| Empty ->
Empty, false
| Black(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then
let l, d = remove_aux l in
let s = Black(l, y, r) in
if d then unbalanced_right s else s, false
else if c > 0 then
let r, d = remove_aux r in
let s = Black(l, y, r) in
if d then unbalanced_left s else s, false
else
begin match r with
| Empty ->
blackify l
| _ ->
let r, y, d = remove_min r in
let s = Black(l, y, r) in
if d then unbalanced_left s else s, false
end
| Red(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then
let l, d = remove_aux l in
let s = Red(l, y, r) in
if d then unbalanced_right s else s, false
else if c > 0 then
let r, d = remove_aux r in
let s = Red(l, y, r) in
if d then unbalanced_left s else s, false
else
begin match r with
| Empty ->
l, false
| _ ->
let r, y, d = remove_min r in
let s = Red(l, y, r) in
if d then unbalanced_left s else s, false
end
in fst (remove_aux s)
let union s1 s2 =
let rec union_aux e1 e2 accu =
match e1, e2 with
| End, End ->
accu
| End, More(x, r, e)
| More(x, r, e), End ->
union_aux End (enum r e) (add x accu)
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then union_aux (enum r1 e1) e2' (add x1 accu)
else if c > 0 then union_aux e1' (enum r2 e2) (add x2 accu)
else union_aux (enum r1 e1) (enum r2 e2) (add x1 accu)
in union_aux (enum s1 End) (enum s2 End) Empty
let inter s1 s2 =
let rec inter_aux e1 e2 accu =
match e1, e2 with
| End, _
| _, End ->
accu
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then inter_aux (enum r1 e1) e2' accu
else if c > 0 then inter_aux e1' (enum r2 e2) accu
else inter_aux (enum r1 e1) (enum r2 e2) (add x1 accu)
in inter_aux (enum s1 End) (enum s2 End) Empty
let diff s1 s2 =
let rec diff_aux e1 e2 accu =
match e1, e2 with
| End, _ ->
accu
| More(x, r, e), End ->
diff_aux (enum r e) End (add x accu)
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then diff_aux (enum r1 e1) e2' (add x1 accu)
else if c > 0 then diff_aux e1' (enum r2 e2) accu
else diff_aux (enum r1 e1) (enum r2 e2) accu
in diff_aux (enum s1 End) (enum s2 End) Empty
let compare s1 s2 =
let rec compare_aux e1 e2 =
match e1, e2 with
| End, End ->
0
| End, _ ->
-1
| _, End ->
1
| More(x1, r1, e1), More(x2, r2, e2) ->
let c = Ord.compare x1 x2 in
if c <> 0 then c else compare_aux (enum r1 e1) (enum r2 e2)
in compare_aux (enum s1 End) (enum s2 End)
let equal s1 s2 =
compare s1 s2 = 0
let rec subset s1 s2 =
match s1, s2 with
| Empty, _ ->
true
| _, Empty ->
false
| (Black(l1, x1, r1) | Red(l1, x1, r1)), ((Black(l2, x2, r2) | Red(l2, x2, r2)) as s2) ->
let c = Ord.compare x1 x2 in
if c = 0 then
subset l1 l2 && subset r1 r2
else if c < 0 then
subset (Black(l1, x1, Empty)) l2 && subset r1 s2
else
subset (Black(Empty, x1, r1)) r2 && subset l1 s2
let rec iter f = function
| Empty -> ()
| Black(l, x, r) | Red(l, x, r) -> iter f l; f x; iter f r
let rec fold f s accu =
match s with
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> fold f r (f x (fold f l accu))
let rec for_all p = function
| Empty -> true
| Black(l, x, r) | Red(l, x, r) -> p x && (for_all p l && for_all p r)
let rec exists p = function
| Empty -> false
| Black(l, x, r) | Red(l, x, r) -> p x || (exists p l || exists p r)
let filter p s =
let rec filter_aux accu = function
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> filter_aux (filter_aux (if p x then add x accu else accu) l) r
in filter_aux Empty s
let partition p s =
let rec partition_aux (t, f as accu) = function
| Empty ->
accu
| Black(l, x, r) | Red(l, x, r) ->
partition_aux (partition_aux (if p x then (add x t, f) else (t, add x f)) l) r
in partition_aux (Empty, Empty) s
let rec cardinal = function
| Empty -> 0
| Black(l, x, r) | Red(l, x, r) -> 1 + cardinal l + cardinal r
let rec elements_aux accu = function
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> elements_aux (x :: elements_aux accu r) l
let elements s =
elements_aux [] s
let rec min_elt = function
| Empty -> raise Not_found
| Black(Empty, x, _) | Red(Empty, x, _) -> x
| Black(l, _, _) | Red(l, _, _) -> min_elt l
let rec max_elt = function
| Empty -> raise Not_found
| Black(_, x, Empty) | Red(_, x, Empty) -> x
| Black(_, _, r) | Red(_, _, r) -> max_elt r
let choose = function
| Empty -> raise Not_found
| Black(_, x, _) | Red(_, x, _) -> x
let split x s =
let rec split_aux y (l, b, r) =
let c = Ord.compare x y in
if c < 0 then l, b, add x r
else if c > 0 then add x l, b, r
else l, true, r
in fold split_aux s (Empty, false, Empty)
end
| null | https://raw.githubusercontent.com/bmeurer/ocaml-rbtrees/06c879da5b009025e65b9cbe9a36405bcf301f35/src/rbset.ml | ocaml | -
* Copyright ( c ) 2007 , < >
*
* Permission is hereby granted , free of charge , to any person obtaining a
* copy of this software and associated documentation files ( the " Software " ) ,
* to deal in the Software without restriction , including without limitation
* the rights to use , copy , modify , merge , publish , distribute , sublicense ,
* and/or sell copies of the Software , and to permit persons to whom the
* Software is furnished to do so , subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software .
*
* THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
* OR IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
* LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
* FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE .
* Copyright (c) 2007, Benedikt Meurer <>
*
* 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.
*)
This is my implementation of Red - Black Trees for OCaml . It is based upon
* " Red - Black Trees in a Functional Setting " , in " Functional
* Pearls " .
* Red - Black Trees are exposed via a map and a set API , which is designed to
* be compatible with the Map and Set modules in the OCaml standard library
* ( which are implemented using AVL trees ) . You can use the Rbmap and * modules as drop - in replacement for the Map and Set modules .
* "Red-Black Trees in a Functional Setting", Chris Okasaki in "Functional
* Pearls".
* Red-Black Trees are exposed via a map and a set API, which is designed to
* be compatible with the Map and Set modules in the OCaml standard library
* (which are implemented using AVL trees). You can use the Rbmap and Rbset
* modules as drop-in replacement for the Map and Set modules.
*)
module type OrderedType =
sig
type t
val compare: t -> t -> int
end
module type S =
sig
type elt
type t
val empty: t
val is_empty: t -> bool
val mem: elt -> t -> bool
val add: elt -> t -> t
val singleton: elt -> t
val remove: elt -> t -> t
val union: t -> t -> t
val inter: t -> t -> t
val diff: t -> t -> t
val compare: t -> t -> int
val equal: t -> t -> bool
val subset: t -> t -> bool
val iter: (elt -> unit) -> t -> unit
val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
val for_all: (elt -> bool) -> t -> bool
val exists: (elt -> bool) -> t -> bool
val filter: (elt -> bool) -> t -> t
val partition: (elt -> bool) -> t -> t * t
val cardinal: t -> int
val elements: t -> elt list
val min_elt: t -> elt
val max_elt: t -> elt
val choose: t -> elt
val split: elt -> t -> t * bool * t
end
module Make(Ord: OrderedType) =
struct
type elt = Ord.t
type t =
| Black of t * elt * t
| Red of t * elt * t
| Empty
type enum =
| End
| More of elt * t * enum
let rec enum s e =
match s with
| Empty -> e
| Black(l, x, r) | Red(l, x, r) -> enum l (More(x, r, e))
let blackify = function
| Red(l, x, r) -> Black(l, x, r), false
| s -> s, true
let empty = Empty
let is_empty = function
| Empty -> true
| _ -> false
let rec mem x = function
| Empty ->
false
| Red(l, y, r)
| Black(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then mem x l
else if c > 0 then mem x r
else true
let balance_left l x r =
match l, x, r with
| Red(Red(a, x, b), y, c), z, d
| Red(a, x, Red(b, y, c)), z, d ->
Red(Black(a, x, b), y, Black(c, z, d))
| l, x, r ->
Black(l, x, r)
let balance_right l x r =
match l, x, r with
| a, x, Red(Red(b, y, c), z, d)
| a, x, Red(b, y, Red(c, z, d)) ->
Red(Black(a, x, b), y, Black(c, z, d))
| l, x, r ->
Black(l, x, r)
let add x s =
let rec add_aux = function
| Empty ->
Red(Empty, x, Empty)
| Red(l, y, r) as s ->
let c = Ord.compare x y in
if c < 0 then
Red(add_aux l, y, r)
else if c > 0 then
Red(l, y, add_aux r)
else
s
| Black(l, y, r) as s ->
let c = Ord.compare x y in
if c < 0 then
balance_left (add_aux l) y r
else if c > 0 then
balance_right l y (add_aux r)
else
s
in fst (blackify (add_aux s))
let singleton x =
Black(Empty, x, Empty)
let unbalanced_left = function
| Red(Black(a, x, b), y, c) -> balance_left (Red(a, x, b)) y c, false
| Black(Black(a, x, b), y, c) -> balance_left (Red(a, x, b)) y c, true
| Black(Red(a, x, Black(b, y, c)), z, d) -> Black(a, x, balance_left (Red(b, y, c)) z d), false
| _ -> assert false
let unbalanced_right = function
| Red(a, x, Black(b, y, c)) -> balance_right a x (Red(b, y, c)), false
| Black(a, x, Black(b, y, c)) -> balance_right a x (Red(b, y, c)), true
| Black(a, x, Red(Black(b, y, c), z, d)) -> Black(balance_right a x (Red(b, y, c)), z, d), false
| _ -> assert false
let rec remove_min = function
| Empty
| Black(Empty, _, Black(_)) ->
assert false
| Black(Empty, x, Empty) ->
Empty, x, true
| Black(Empty, x, Red(l, y, r)) ->
Black(l, y, r), x, false
| Red(Empty, x, r) ->
r, x, false
| Black(l, x, r) ->
let l, y, d = remove_min l in
let s = Black(l, x, r) in
if d then
let s, d = unbalanced_right s in s, y, d
else
s, y, false
| Red(l, x, r) ->
let l, y, d = remove_min l in
let s = Red(l, x, r) in
if d then
let s, d = unbalanced_right s in s, y, d
else
s, y, false
let remove x s =
let rec remove_aux = function
| Empty ->
Empty, false
| Black(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then
let l, d = remove_aux l in
let s = Black(l, y, r) in
if d then unbalanced_right s else s, false
else if c > 0 then
let r, d = remove_aux r in
let s = Black(l, y, r) in
if d then unbalanced_left s else s, false
else
begin match r with
| Empty ->
blackify l
| _ ->
let r, y, d = remove_min r in
let s = Black(l, y, r) in
if d then unbalanced_left s else s, false
end
| Red(l, y, r) ->
let c = Ord.compare x y in
if c < 0 then
let l, d = remove_aux l in
let s = Red(l, y, r) in
if d then unbalanced_right s else s, false
else if c > 0 then
let r, d = remove_aux r in
let s = Red(l, y, r) in
if d then unbalanced_left s else s, false
else
begin match r with
| Empty ->
l, false
| _ ->
let r, y, d = remove_min r in
let s = Red(l, y, r) in
if d then unbalanced_left s else s, false
end
in fst (remove_aux s)
let union s1 s2 =
let rec union_aux e1 e2 accu =
match e1, e2 with
| End, End ->
accu
| End, More(x, r, e)
| More(x, r, e), End ->
union_aux End (enum r e) (add x accu)
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then union_aux (enum r1 e1) e2' (add x1 accu)
else if c > 0 then union_aux e1' (enum r2 e2) (add x2 accu)
else union_aux (enum r1 e1) (enum r2 e2) (add x1 accu)
in union_aux (enum s1 End) (enum s2 End) Empty
let inter s1 s2 =
let rec inter_aux e1 e2 accu =
match e1, e2 with
| End, _
| _, End ->
accu
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then inter_aux (enum r1 e1) e2' accu
else if c > 0 then inter_aux e1' (enum r2 e2) accu
else inter_aux (enum r1 e1) (enum r2 e2) (add x1 accu)
in inter_aux (enum s1 End) (enum s2 End) Empty
let diff s1 s2 =
let rec diff_aux e1 e2 accu =
match e1, e2 with
| End, _ ->
accu
| More(x, r, e), End ->
diff_aux (enum r e) End (add x accu)
| (More(x1, r1, e1) as e1'), (More(x2, r2, e2) as e2') ->
let c = Ord.compare x1 x2 in
if c < 0 then diff_aux (enum r1 e1) e2' (add x1 accu)
else if c > 0 then diff_aux e1' (enum r2 e2) accu
else diff_aux (enum r1 e1) (enum r2 e2) accu
in diff_aux (enum s1 End) (enum s2 End) Empty
let compare s1 s2 =
let rec compare_aux e1 e2 =
match e1, e2 with
| End, End ->
0
| End, _ ->
-1
| _, End ->
1
| More(x1, r1, e1), More(x2, r2, e2) ->
let c = Ord.compare x1 x2 in
if c <> 0 then c else compare_aux (enum r1 e1) (enum r2 e2)
in compare_aux (enum s1 End) (enum s2 End)
let equal s1 s2 =
compare s1 s2 = 0
let rec subset s1 s2 =
match s1, s2 with
| Empty, _ ->
true
| _, Empty ->
false
| (Black(l1, x1, r1) | Red(l1, x1, r1)), ((Black(l2, x2, r2) | Red(l2, x2, r2)) as s2) ->
let c = Ord.compare x1 x2 in
if c = 0 then
subset l1 l2 && subset r1 r2
else if c < 0 then
subset (Black(l1, x1, Empty)) l2 && subset r1 s2
else
subset (Black(Empty, x1, r1)) r2 && subset l1 s2
let rec iter f = function
| Empty -> ()
| Black(l, x, r) | Red(l, x, r) -> iter f l; f x; iter f r
let rec fold f s accu =
match s with
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> fold f r (f x (fold f l accu))
let rec for_all p = function
| Empty -> true
| Black(l, x, r) | Red(l, x, r) -> p x && (for_all p l && for_all p r)
let rec exists p = function
| Empty -> false
| Black(l, x, r) | Red(l, x, r) -> p x || (exists p l || exists p r)
let filter p s =
let rec filter_aux accu = function
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> filter_aux (filter_aux (if p x then add x accu else accu) l) r
in filter_aux Empty s
let partition p s =
let rec partition_aux (t, f as accu) = function
| Empty ->
accu
| Black(l, x, r) | Red(l, x, r) ->
partition_aux (partition_aux (if p x then (add x t, f) else (t, add x f)) l) r
in partition_aux (Empty, Empty) s
let rec cardinal = function
| Empty -> 0
| Black(l, x, r) | Red(l, x, r) -> 1 + cardinal l + cardinal r
let rec elements_aux accu = function
| Empty -> accu
| Black(l, x, r) | Red(l, x, r) -> elements_aux (x :: elements_aux accu r) l
let elements s =
elements_aux [] s
let rec min_elt = function
| Empty -> raise Not_found
| Black(Empty, x, _) | Red(Empty, x, _) -> x
| Black(l, _, _) | Red(l, _, _) -> min_elt l
let rec max_elt = function
| Empty -> raise Not_found
| Black(_, x, Empty) | Red(_, x, Empty) -> x
| Black(_, _, r) | Red(_, _, r) -> max_elt r
let choose = function
| Empty -> raise Not_found
| Black(_, x, _) | Red(_, x, _) -> x
let split x s =
let rec split_aux y (l, b, r) =
let c = Ord.compare x y in
if c < 0 then l, b, add x r
else if c > 0 then add x l, b, r
else l, true, r
in fold split_aux s (Empty, false, Empty)
end
|
|
f8c438a01b65820c1ae1c5dda02cefde907e07af3134123e47422e385d53c02b | losfair/Violet | Gpr.hs | module Violet.Backend.Gpr where
import Clash.Prelude
import Violet.Types.Gpr
import qualified Violet.Types.Fifo as FifoT
gpr :: HiddenClockResetEnable dom
=> Signal dom ((FifoT.FifoItem, FifoT.FifoItem), WritePort, WritePort)
-> Signal dom ((RegValue, RegValue), (RegValue, RegValue))
gpr inputs = bundle (bundle (read1, read2), bundle (read3, read4))
where
(inPorts, wp1, wp2) = unbundle inputs
(port1, port2) = unbundle inPorts
(i1, i2) = unbundle $ fmap fifoItemToRegIndices port1
(i3, i4) = unbundle $ fmap fifoItemToRegIndices port2
readA1 = asyncRamPow2 i1 (fmap transformWp wp1)
readA2 = asyncRamPow2 i2 (fmap transformWp wp1)
readA3 = asyncRamPow2 i3 (fmap transformWp wp1)
readA4 = asyncRamPow2 i4 (fmap transformWp wp1)
readB1 = asyncRamPow2 i1 (fmap transformWp wp2)
readB2 = asyncRamPow2 i2 (fmap transformWp wp2)
readB3 = asyncRamPow2 i3 (fmap transformWp wp2)
readB4 = asyncRamPow2 i4 (fmap transformWp wp2)
(a1, a2, a3, a4) = unbundle $ (mealy mkAllocation 0) (bundle (wp1, wp2, i1, i2, i3, i4))
read1 = register undefined $ fmap selectReadRes $ bundle (a1, i1, readA1, readB1, wp1, wp2)
read2 = register undefined $ fmap selectReadRes $ bundle (a2, i2, readA2, readB2, wp1, wp2)
read3 = register undefined $ fmap selectReadRes $ bundle (a3, i3, readA3, readB3, wp1, wp2)
read4 = register undefined $ fmap selectReadRes $ bundle (a4, i4, readA4, readB4, wp1, wp2)
fifoItemToRegIndices :: FifoT.FifoItem -> (Unsigned 5, Unsigned 5)
fifoItemToRegIndices item = (rs1, rs2)
where
inst = case item of
FifoT.Item (_, inst, _) -> inst
_ -> undefined
rs1 = unpack $ slice d19 d15 inst
rs2 = unpack $ slice d24 d20 inst
transformWp :: WritePort -> Maybe (Unsigned 5, RegValue)
transformWp (Just (i, v)) = Just (unpack i, v)
transformWp _ = Nothing
mkAllocation :: BitVector 32
-> (WritePort, WritePort, Unsigned 5, Unsigned 5, Unsigned 5, Unsigned 5)
-> (BitVector 32, (Bool, Bool, Bool, Bool))
mkAllocation s (wp1, wp2, i1, i2, i3, i4) = (s', (a1, a2, a3, a4))
where
s_ = case wp1 of
Just (i, _) -> clearBit s (fromIntegral i)
_ -> s
s' = case wp2 of
Just (i, _) -> setBit s_ (fromIntegral i)
_ -> s_
a1 = testBit s (fromIntegral i1)
a2 = testBit s (fromIntegral i2)
a3 = testBit s (fromIntegral i3)
a4 = testBit s (fromIntegral i4)
selectReadRes :: (Bool, Unsigned 5, RegValue, RegValue, WritePort, WritePort) -> RegValue
selectReadRes (_, 0, _, _, _, _) = 0
selectReadRes (_, i, _, _, _, Just (i', v)) | i == unpack i' = v
selectReadRes (_, i, _, _, Just (i', v), _) | i == unpack i' = v
selectReadRes (False, _, a, _, _, _) = a
selectReadRes (True, _, _, b, _, _) = b | null | https://raw.githubusercontent.com/losfair/Violet/dcdd05f8dc08a438a157347f424966da73ccc9b8/src/Violet/Backend/Gpr.hs | haskell | module Violet.Backend.Gpr where
import Clash.Prelude
import Violet.Types.Gpr
import qualified Violet.Types.Fifo as FifoT
gpr :: HiddenClockResetEnable dom
=> Signal dom ((FifoT.FifoItem, FifoT.FifoItem), WritePort, WritePort)
-> Signal dom ((RegValue, RegValue), (RegValue, RegValue))
gpr inputs = bundle (bundle (read1, read2), bundle (read3, read4))
where
(inPorts, wp1, wp2) = unbundle inputs
(port1, port2) = unbundle inPorts
(i1, i2) = unbundle $ fmap fifoItemToRegIndices port1
(i3, i4) = unbundle $ fmap fifoItemToRegIndices port2
readA1 = asyncRamPow2 i1 (fmap transformWp wp1)
readA2 = asyncRamPow2 i2 (fmap transformWp wp1)
readA3 = asyncRamPow2 i3 (fmap transformWp wp1)
readA4 = asyncRamPow2 i4 (fmap transformWp wp1)
readB1 = asyncRamPow2 i1 (fmap transformWp wp2)
readB2 = asyncRamPow2 i2 (fmap transformWp wp2)
readB3 = asyncRamPow2 i3 (fmap transformWp wp2)
readB4 = asyncRamPow2 i4 (fmap transformWp wp2)
(a1, a2, a3, a4) = unbundle $ (mealy mkAllocation 0) (bundle (wp1, wp2, i1, i2, i3, i4))
read1 = register undefined $ fmap selectReadRes $ bundle (a1, i1, readA1, readB1, wp1, wp2)
read2 = register undefined $ fmap selectReadRes $ bundle (a2, i2, readA2, readB2, wp1, wp2)
read3 = register undefined $ fmap selectReadRes $ bundle (a3, i3, readA3, readB3, wp1, wp2)
read4 = register undefined $ fmap selectReadRes $ bundle (a4, i4, readA4, readB4, wp1, wp2)
fifoItemToRegIndices :: FifoT.FifoItem -> (Unsigned 5, Unsigned 5)
fifoItemToRegIndices item = (rs1, rs2)
where
inst = case item of
FifoT.Item (_, inst, _) -> inst
_ -> undefined
rs1 = unpack $ slice d19 d15 inst
rs2 = unpack $ slice d24 d20 inst
transformWp :: WritePort -> Maybe (Unsigned 5, RegValue)
transformWp (Just (i, v)) = Just (unpack i, v)
transformWp _ = Nothing
mkAllocation :: BitVector 32
-> (WritePort, WritePort, Unsigned 5, Unsigned 5, Unsigned 5, Unsigned 5)
-> (BitVector 32, (Bool, Bool, Bool, Bool))
mkAllocation s (wp1, wp2, i1, i2, i3, i4) = (s', (a1, a2, a3, a4))
where
s_ = case wp1 of
Just (i, _) -> clearBit s (fromIntegral i)
_ -> s
s' = case wp2 of
Just (i, _) -> setBit s_ (fromIntegral i)
_ -> s_
a1 = testBit s (fromIntegral i1)
a2 = testBit s (fromIntegral i2)
a3 = testBit s (fromIntegral i3)
a4 = testBit s (fromIntegral i4)
selectReadRes :: (Bool, Unsigned 5, RegValue, RegValue, WritePort, WritePort) -> RegValue
selectReadRes (_, 0, _, _, _, _) = 0
selectReadRes (_, i, _, _, _, Just (i', v)) | i == unpack i' = v
selectReadRes (_, i, _, _, Just (i', v), _) | i == unpack i' = v
selectReadRes (False, _, a, _, _, _) = a
selectReadRes (True, _, _, b, _, _) = b |
|
5436b7df838e92f0938c17016fcc38afd9e475940e1f72c2a41abe8622f3f351 | qkrgud55/ocamlmulti | main.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : main.ml 11156 2011 - 07 - 27 14:17:02Z doligez $
(* The lexer generator. Command-line parsing. *)
open Syntax
open Scanner
open Grammar
open Lexgen
open Output
let main () =
if Array.length Sys.argv <> 2 then begin
prerr_string "Usage: camllex <input file>\n";
exit 2
end;
let source_name = Sys.argv.(1) in
let dest_name =
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
ic := open_in source_name;
oc : = open_out dest_name ;
oc := stdout;
let lexbuf = Lexing.from_channel !ic in
let (Lexdef(header,_) as def) =
try
Grammar.lexer_definition Scanner.main lexbuf
with
Parsing.Parse_error ->
prerr_string "Syntax error around char ";
prerr_int (Lexing.lexeme_start lexbuf);
prerr_endline ".";
exit 2
| Scan_aux.Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (Lexing.lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline ".";
exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa;
close_in !ic;
close_out !oc
let _ = main(); exit 0
* * * *
let main ( ) =
ic : = stdin ;
oc : = stdout ;
let lexbuf = lexing.from_channel ic in
let ( Lexdef(header , _ ) as def ) =
try
grammar.lexer_definition scanner.main lexbuf
with
parsing . Parse_error x - >
prerr_string " Syntax error around char " ;
prerr_int ( ) ;
prerr_endline " . " ;
sys.exit 2
| scan_aux . Lexical_error s - >
prerr_string " Lexical error around char " ;
prerr_int ( ) ;
prerr_string " : " ;
prerr_string s ;
prerr_endline " . " ;
sys.exit 2 in
let ( ( init , states , acts ) as dfa ) = make_dfa def in
output_lexdef header dfa
* * *
let main () =
ic := stdin;
oc := stdout;
let lexbuf = lexing.from_channel ic in
let (Lexdef(header,_) as def) =
try
grammar.lexer_definition scanner.main lexbuf
with
parsing.Parse_error x ->
prerr_string "Syntax error around char ";
prerr_int (lexing.lexeme_start lexbuf);
prerr_endline ".";
sys.exit 2
| scan_aux.Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (lexing.lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline ".";
sys.exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa
****)
* * *
let =
let tok = scanner.main lexbuf in
begin match tok with
> prerr_string " " ; prerr_string s
| prerr_string " Tchar " ; prerr_char c
| Tstring s - > prerr_string " Tstring " ; prerr_string s
| Taction(Location(i1,i2 ) ) - >
prerr_string " Taction " ; prerr_int i1 ; prerr_string " - " ;
prerr_int i2
| Trule - > prerr_string " "
| Tparse - > prerr_string " "
| Tand - > prerr_string " Tand "
| Tequal - > prerr_string " Tequal "
| Tend - > prerr_string " Tend "
| Tor - > prerr_string " Tor "
| Tunderscore - > prerr_string " "
| Teof - > prerr_string " Teof "
| Tlbracket - > prerr_string " Tlbracket "
| Trbracket - > prerr_string " Trbracket "
| Tstar - > prerr_string " Tstar "
| Tmaybe - > prerr_string " "
| Tplus - > prerr_string " Tplus "
| Tlparen - > prerr_string " "
| Trparen - > prerr_string " "
| Tcaret - > prerr_string " Tcaret "
| Tdash - > prerr_string " "
end ;
prerr_newline ( ) ;
tok
* * *
let debug_scanner lexbuf =
let tok = scanner.main lexbuf in
begin match tok with
Tident s -> prerr_string "Tident "; prerr_string s
| Tchar c -> prerr_string "Tchar "; prerr_char c
| Tstring s -> prerr_string "Tstring "; prerr_string s
| Taction(Location(i1,i2)) ->
prerr_string "Taction "; prerr_int i1; prerr_string "-";
prerr_int i2
| Trule -> prerr_string "Trule"
| Tparse -> prerr_string "Tparse"
| Tand -> prerr_string "Tand"
| Tequal -> prerr_string "Tequal"
| Tend -> prerr_string "Tend"
| Tor -> prerr_string "Tor"
| Tunderscore -> prerr_string "Tunderscore"
| Teof -> prerr_string "Teof"
| Tlbracket -> prerr_string "Tlbracket"
| Trbracket -> prerr_string "Trbracket"
| Tstar -> prerr_string "Tstar"
| Tmaybe -> prerr_string "Tmaybe"
| Tplus -> prerr_string "Tplus"
| Tlparen -> prerr_string "Tlparen"
| Trparen -> prerr_string "Trparen"
| Tcaret -> prerr_string "Tcaret"
| Tdash -> prerr_string "Tdash"
end;
prerr_newline();
tok
****)
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/testsuite/tests/tool-lexyacc/main.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
The lexer generator. Command-line parsing. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : main.ml 11156 2011 - 07 - 27 14:17:02Z doligez $
open Syntax
open Scanner
open Grammar
open Lexgen
open Output
let main () =
if Array.length Sys.argv <> 2 then begin
prerr_string "Usage: camllex <input file>\n";
exit 2
end;
let source_name = Sys.argv.(1) in
let dest_name =
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
ic := open_in source_name;
oc : = open_out dest_name ;
oc := stdout;
let lexbuf = Lexing.from_channel !ic in
let (Lexdef(header,_) as def) =
try
Grammar.lexer_definition Scanner.main lexbuf
with
Parsing.Parse_error ->
prerr_string "Syntax error around char ";
prerr_int (Lexing.lexeme_start lexbuf);
prerr_endline ".";
exit 2
| Scan_aux.Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (Lexing.lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline ".";
exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa;
close_in !ic;
close_out !oc
let _ = main(); exit 0
* * * *
let main ( ) =
ic : = stdin ;
oc : = stdout ;
let lexbuf = lexing.from_channel ic in
let ( Lexdef(header , _ ) as def ) =
try
grammar.lexer_definition scanner.main lexbuf
with
parsing . Parse_error x - >
prerr_string " Syntax error around char " ;
prerr_int ( ) ;
prerr_endline " . " ;
sys.exit 2
| scan_aux . Lexical_error s - >
prerr_string " Lexical error around char " ;
prerr_int ( ) ;
prerr_string " : " ;
prerr_string s ;
prerr_endline " . " ;
sys.exit 2 in
let ( ( init , states , acts ) as dfa ) = make_dfa def in
output_lexdef header dfa
* * *
let main () =
ic := stdin;
oc := stdout;
let lexbuf = lexing.from_channel ic in
let (Lexdef(header,_) as def) =
try
grammar.lexer_definition scanner.main lexbuf
with
parsing.Parse_error x ->
prerr_string "Syntax error around char ";
prerr_int (lexing.lexeme_start lexbuf);
prerr_endline ".";
sys.exit 2
| scan_aux.Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (lexing.lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline ".";
sys.exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa
****)
* * *
let =
let tok = scanner.main lexbuf in
begin match tok with
> prerr_string " " ; prerr_string s
| prerr_string " Tchar " ; prerr_char c
| Tstring s - > prerr_string " Tstring " ; prerr_string s
| Taction(Location(i1,i2 ) ) - >
prerr_string " Taction " ; prerr_int i1 ; prerr_string " - " ;
prerr_int i2
| Trule - > prerr_string " "
| Tparse - > prerr_string " "
| Tand - > prerr_string " Tand "
| Tequal - > prerr_string " Tequal "
| Tend - > prerr_string " Tend "
| Tor - > prerr_string " Tor "
| Tunderscore - > prerr_string " "
| Teof - > prerr_string " Teof "
| Tlbracket - > prerr_string " Tlbracket "
| Trbracket - > prerr_string " Trbracket "
| Tstar - > prerr_string " Tstar "
| Tmaybe - > prerr_string " "
| Tplus - > prerr_string " Tplus "
| Tlparen - > prerr_string " "
| Trparen - > prerr_string " "
| Tcaret - > prerr_string " Tcaret "
| Tdash - > prerr_string " "
end ;
prerr_newline ( ) ;
tok
* * *
let debug_scanner lexbuf =
let tok = scanner.main lexbuf in
begin match tok with
Tident s -> prerr_string "Tident "; prerr_string s
| Tchar c -> prerr_string "Tchar "; prerr_char c
| Tstring s -> prerr_string "Tstring "; prerr_string s
| Taction(Location(i1,i2)) ->
prerr_string "Taction "; prerr_int i1; prerr_string "-";
prerr_int i2
| Trule -> prerr_string "Trule"
| Tparse -> prerr_string "Tparse"
| Tand -> prerr_string "Tand"
| Tequal -> prerr_string "Tequal"
| Tend -> prerr_string "Tend"
| Tor -> prerr_string "Tor"
| Tunderscore -> prerr_string "Tunderscore"
| Teof -> prerr_string "Teof"
| Tlbracket -> prerr_string "Tlbracket"
| Trbracket -> prerr_string "Trbracket"
| Tstar -> prerr_string "Tstar"
| Tmaybe -> prerr_string "Tmaybe"
| Tplus -> prerr_string "Tplus"
| Tlparen -> prerr_string "Tlparen"
| Trparen -> prerr_string "Trparen"
| Tcaret -> prerr_string "Tcaret"
| Tdash -> prerr_string "Tdash"
end;
prerr_newline();
tok
****)
|
663e6e62acaded632e9abcd940ae3e429da6837abfa1f932a58e3a95766e7671 | drdo/logic-translation | Parse.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE UnicodeSyntax #
module Parse
( tlP, fomloP
, ParseError (..), parseText, parseString
)
where
import Data.ByteString (ByteString)
import Data.Char
import Data.Functor.Identity
import Data.Text (Text)
import Text.Parsec
import qualified Data.ByteString.UTF8 as BSU8
import qualified Data.Text as Text
import BooleanCombination
import FOMLO
import TL
import Util
--------------------------------------------------------------------------------
choiceTry ∷ Stream s m t ⇒ [ParsecT s u m a] → ParsecT s u m a
choiceTry = choice . map try
parse_ ∷ Stream s Identity t ⇒ Parsec s () a → s → Either ParseError a
parse_ p = parse p ""
--------------------------------------------------------------------------------
manyTill1 ∷ Stream s m t ⇒ ParsecT s u m a → ParsecT s u m end → ParsecT s u m ([a], end)
manyTill1 p end = p >>= \x → go (x :)
where
go k = (try end >>= \e → pure (k [], e))
<|> (p >>= \x → go (k . (x :)))
many2 ∷ Stream s m t ⇒ ParsecT s u m a → ParsecT s u m [a]
many2 p = (:) <$> p <*> many1 p
list2 ∷ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m [a]
list2 p = many2 (spaces *> p)
spaces1 ∷ Stream s m Char ⇒ ParsecT s u m ()
spaces1 = skipMany1 space
parens ∷ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m a
parens p = spaces *> between (char '(' *> spaces) (spaces *> char ')') p
identifierP ∷ Stream s m Char ⇒ ParsecT s u m String
identifierP = many1 (satisfy (\c → isAlphaNum c || elem c ("_-" ∷ [Char])))
predicateNameP ∷ Stream s m Char ⇒ ParsecT s u m String
predicateNameP = identifierP
variableNameP ∷ Stream s m Char ⇒ ParsecT s u m String
variableNameP = identifierP
bcP ∷ (Ord a) ⇒ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m (BC a)
bcP primP = spaces *> choiceTry [ botP
, topP
, negP
, orP
, andP
, implP
, biimplP
, Prim <$> primP]
where
variadicOp names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> many (spaces1 *> bcP primP)
variadic1Op names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> many1 (spaces1 *> bcP primP)
botP = (choiceTry $ string <$> ["⊥", "bot", "Bot", "false", "False"]) *> pure bot
topP = (choiceTry $ string <$> ["⊤", "top", "Top", "true", "True"]) *> pure top
negP = parens $ do
choiceTry $ string <$> ["¬", "not", "Not", "neg", "Neg"]
spaces1
Not <$> bcP primP
orP = variadicOp ["∨", "or", "Or"] disjList
andP = variadicOp ["∧", "and", "And"] conjList
implP = variadic1Op ["→", "->", "implies", "Implies"] impl
biimplP = variadic1Op ["↔", "<->"] biimpl
--------------------
simpleTlP ∷ Stream s m Char ⇒ ParsecT s u m (TL String)
simpleTlP = spaces *> choiceTry [ variableP
, sinceP
, untilP
, nextPastP
, nextP
, eventuallyPastP
, eventuallyP
, foreverPastP
, foreverP
]
where
variableP = Var <$> predicateNameP
binaryOpP names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> (spaces1 *> tlP) <*> (spaces1 *> tlP)
sinceP = binaryOpP ["since", "Since", "s", "S"] S
untilP = binaryOpP ["until", "Until", "u", "U"] U
unaryOp names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> (spaces1 *> tlP)
nextPastP = unaryOp ["●", "prev", "Prev"] nextPast
nextP = unaryOp ["○", "next", "Next"] next
eventuallyPastP = unaryOp ["⧫", "eventually-past", "Eventually-Past"] eventuallyPast
eventuallyP = unaryOp ["◊", "eventually", "Eventually"] eventually
foreverPastP = unaryOp ["■", "forever-past", "Forever-Past"] foreverPast
foreverP = unaryOp ["□", "forever", "Forever"] forever
tlP ∷ Stream s m Char ⇒ ParsecT s u m (TL String)
tlP = bcJoin <$> bcP simpleTlP
--------------------
simpleFomloP ∷ Stream s m Char ⇒ ParsecT s u m (FOMLO String String)
simpleFomloP = spaces *> choiceTry [ equalP
, lessThanP
, lessEqP
, greaterThanP
, greaterEqP
, existentialP
, universalP
, predicateP
]
where
binaryPredP names constructor = parens $ do
choiceTry $ string <$> names
args ← spaces *> list2 variableNameP
pure $ conjList (zipWith constructor args (tail args))
equalP = binaryPredP ["="] Eq
lessThanP = binaryPredP ["<"] Less
lessEqP = binaryPredP ["≤", "<="] (\x y → (Less x y) ∨ (Eq x y))
greaterThanP = binaryPredP [">"] (flip Less)
greaterEqP = binaryPredP ["≥", ">="] (\x y → (Eq x y) ∨ (Less y x))
quantifierP names constructor = parens $ do
choiceTry $ string <$> names
spaces
(vars, body) ← manyTill1 (spaces *> variableNameP) fomloP
pure $ ($ body) . foldl1' (.) . map constructor $ vars
existentialP = quantifierP ["∃", "exists", "Exists"] Exists
universalP = quantifierP ["∀", "forall", "Forall"] Forall
predicateP = parens (Pred <$> (spaces *> predicateNameP) <*> (spaces *> variableNameP))
fomloP ∷ Stream s m Char ⇒ ParsecT s u m (FOMLO String String)
fomloP = bcJoin <$> bcP simpleFomloP
--------------------------------------------------------------------------------
parseText ∷ Parsec String () a → Text → Either ParseError a
parseText p = parse_ p . Text.unpack
parseString ∷ Parsec String () a → String → Either ParseError a
parseString = parse_
| null | https://raw.githubusercontent.com/drdo/logic-translation/3efca7ce74b2e018a6ac4a8dacfc8a2dcfbd467f/library/Parse.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------
------------------
------------------------------------------------------------------------------ | # LANGUAGE FlexibleContexts #
# LANGUAGE UnicodeSyntax #
module Parse
( tlP, fomloP
, ParseError (..), parseText, parseString
)
where
import Data.ByteString (ByteString)
import Data.Char
import Data.Functor.Identity
import Data.Text (Text)
import Text.Parsec
import qualified Data.ByteString.UTF8 as BSU8
import qualified Data.Text as Text
import BooleanCombination
import FOMLO
import TL
import Util
choiceTry ∷ Stream s m t ⇒ [ParsecT s u m a] → ParsecT s u m a
choiceTry = choice . map try
parse_ ∷ Stream s Identity t ⇒ Parsec s () a → s → Either ParseError a
parse_ p = parse p ""
manyTill1 ∷ Stream s m t ⇒ ParsecT s u m a → ParsecT s u m end → ParsecT s u m ([a], end)
manyTill1 p end = p >>= \x → go (x :)
where
go k = (try end >>= \e → pure (k [], e))
<|> (p >>= \x → go (k . (x :)))
many2 ∷ Stream s m t ⇒ ParsecT s u m a → ParsecT s u m [a]
many2 p = (:) <$> p <*> many1 p
list2 ∷ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m [a]
list2 p = many2 (spaces *> p)
spaces1 ∷ Stream s m Char ⇒ ParsecT s u m ()
spaces1 = skipMany1 space
parens ∷ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m a
parens p = spaces *> between (char '(' *> spaces) (spaces *> char ')') p
identifierP ∷ Stream s m Char ⇒ ParsecT s u m String
identifierP = many1 (satisfy (\c → isAlphaNum c || elem c ("_-" ∷ [Char])))
predicateNameP ∷ Stream s m Char ⇒ ParsecT s u m String
predicateNameP = identifierP
variableNameP ∷ Stream s m Char ⇒ ParsecT s u m String
variableNameP = identifierP
bcP ∷ (Ord a) ⇒ Stream s m Char ⇒ ParsecT s u m a → ParsecT s u m (BC a)
bcP primP = spaces *> choiceTry [ botP
, topP
, negP
, orP
, andP
, implP
, biimplP
, Prim <$> primP]
where
variadicOp names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> many (spaces1 *> bcP primP)
variadic1Op names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> many1 (spaces1 *> bcP primP)
botP = (choiceTry $ string <$> ["⊥", "bot", "Bot", "false", "False"]) *> pure bot
topP = (choiceTry $ string <$> ["⊤", "top", "Top", "true", "True"]) *> pure top
negP = parens $ do
choiceTry $ string <$> ["¬", "not", "Not", "neg", "Neg"]
spaces1
Not <$> bcP primP
orP = variadicOp ["∨", "or", "Or"] disjList
andP = variadicOp ["∧", "and", "And"] conjList
implP = variadic1Op ["→", "->", "implies", "Implies"] impl
biimplP = variadic1Op ["↔", "<->"] biimpl
simpleTlP ∷ Stream s m Char ⇒ ParsecT s u m (TL String)
simpleTlP = spaces *> choiceTry [ variableP
, sinceP
, untilP
, nextPastP
, nextP
, eventuallyPastP
, eventuallyP
, foreverPastP
, foreverP
]
where
variableP = Var <$> predicateNameP
binaryOpP names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> (spaces1 *> tlP) <*> (spaces1 *> tlP)
sinceP = binaryOpP ["since", "Since", "s", "S"] S
untilP = binaryOpP ["until", "Until", "u", "U"] U
unaryOp names constructor = parens $ do
choiceTry $ string <$> names
constructor <$> (spaces1 *> tlP)
nextPastP = unaryOp ["●", "prev", "Prev"] nextPast
nextP = unaryOp ["○", "next", "Next"] next
eventuallyPastP = unaryOp ["⧫", "eventually-past", "Eventually-Past"] eventuallyPast
eventuallyP = unaryOp ["◊", "eventually", "Eventually"] eventually
foreverPastP = unaryOp ["■", "forever-past", "Forever-Past"] foreverPast
foreverP = unaryOp ["□", "forever", "Forever"] forever
tlP ∷ Stream s m Char ⇒ ParsecT s u m (TL String)
tlP = bcJoin <$> bcP simpleTlP
simpleFomloP ∷ Stream s m Char ⇒ ParsecT s u m (FOMLO String String)
simpleFomloP = spaces *> choiceTry [ equalP
, lessThanP
, lessEqP
, greaterThanP
, greaterEqP
, existentialP
, universalP
, predicateP
]
where
binaryPredP names constructor = parens $ do
choiceTry $ string <$> names
args ← spaces *> list2 variableNameP
pure $ conjList (zipWith constructor args (tail args))
equalP = binaryPredP ["="] Eq
lessThanP = binaryPredP ["<"] Less
lessEqP = binaryPredP ["≤", "<="] (\x y → (Less x y) ∨ (Eq x y))
greaterThanP = binaryPredP [">"] (flip Less)
greaterEqP = binaryPredP ["≥", ">="] (\x y → (Eq x y) ∨ (Less y x))
quantifierP names constructor = parens $ do
choiceTry $ string <$> names
spaces
(vars, body) ← manyTill1 (spaces *> variableNameP) fomloP
pure $ ($ body) . foldl1' (.) . map constructor $ vars
existentialP = quantifierP ["∃", "exists", "Exists"] Exists
universalP = quantifierP ["∀", "forall", "Forall"] Forall
predicateP = parens (Pred <$> (spaces *> predicateNameP) <*> (spaces *> variableNameP))
fomloP ∷ Stream s m Char ⇒ ParsecT s u m (FOMLO String String)
fomloP = bcJoin <$> bcP simpleFomloP
parseText ∷ Parsec String () a → Text → Either ParseError a
parseText p = parse_ p . Text.unpack
parseString ∷ Parsec String () a → String → Either ParseError a
parseString = parse_
|
d58c13693776a37bfc3aac5825c1b3b35466e742a2bd5ba91dd00a3cba6c2a3e | xsc/kithara | confirmation_defaults.clj | (ns kithara.middlewares.confirmation-defaults
(:require [manifold.deferred :as d]))
(defn- postprocess
[result default-confirmation error-confirmation]
(if (map? result)
(if (keyword? (:status result))
result
(merge default-confirmation result))
default-confirmation))
(defn- confirm-error
[error-confirmation t]
(assoc error-confirmation :error t))
(defn wrap-confirmation-defaults
"Wrap the given function, taking a kithara message map, making sure it
returns a kithara confirmation map to be processed by [[wrap-confirmation]].
- `:default-confirmation` will be used if the result is not a map or does not
contain a valid `:status` key.
- `:error-confirmation` will be used if an exception is encountered (with
the exception being `assoc`ed into the map as `:error`).
This is a middleware activated by default in the kithara base consumer."
[message-handler {:keys [default-confirmation
error-confirmation]
:or {default-confirmation {:status :ack}
error-confirmation {:status :nack}}}]
{:pre [(map? default-confirmation)
(map? error-confirmation)
(-> default-confirmation :status keyword?)
(-> error-confirmation :status keyword?)]}
(fn [message]
(try
(-> (message-handler message)
(d/chain #(postprocess % default-confirmation error-confirmation))
(d/catch #(confirm-error error-confirmation %)))
(catch Throwable t
(confirm-error error-confirmation t)))))
| null | https://raw.githubusercontent.com/xsc/kithara/3394a9e9ef5e6e605637a74e070c7d24bfaf19cc/src/kithara/middlewares/confirmation_defaults.clj | clojure | (ns kithara.middlewares.confirmation-defaults
(:require [manifold.deferred :as d]))
(defn- postprocess
[result default-confirmation error-confirmation]
(if (map? result)
(if (keyword? (:status result))
result
(merge default-confirmation result))
default-confirmation))
(defn- confirm-error
[error-confirmation t]
(assoc error-confirmation :error t))
(defn wrap-confirmation-defaults
"Wrap the given function, taking a kithara message map, making sure it
returns a kithara confirmation map to be processed by [[wrap-confirmation]].
- `:default-confirmation` will be used if the result is not a map or does not
contain a valid `:status` key.
- `:error-confirmation` will be used if an exception is encountered (with
the exception being `assoc`ed into the map as `:error`).
This is a middleware activated by default in the kithara base consumer."
[message-handler {:keys [default-confirmation
error-confirmation]
:or {default-confirmation {:status :ack}
error-confirmation {:status :nack}}}]
{:pre [(map? default-confirmation)
(map? error-confirmation)
(-> default-confirmation :status keyword?)
(-> error-confirmation :status keyword?)]}
(fn [message]
(try
(-> (message-handler message)
(d/chain #(postprocess % default-confirmation error-confirmation))
(d/catch #(confirm-error error-confirmation %)))
(catch Throwable t
(confirm-error error-confirmation t)))))
|
|
27b67b025319fea90f53ad9667202666b5cdd8713964269beaddc6bf6ae8d9be | acl2/acl2 | (JAVA::GRAMMAR-DEC-DIGITP)
(JAVA::GRAMMAR-DEC-DIGITP-SUFF)
(JAVA::BOOLEANP-OF-GRAMMAR-DEC-DIGITP)
(JAVA::GRAMMAR-DEC-DIGITP)
(JAVA::SINGLETON-WHEN-GRAMMAR-DEC-DIGITP
(1606 1602 (:REWRITE DEFAULT-CAR))
(1602 1602 (:REWRITE CAR-WHEN-ALL-EQUALP))
(920 120 (:REWRITE ABNF::TREE-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-TERMINATEDP))
(760 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-LIST-TERMINATEDP))
(455 70 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(400 400 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(400 400 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(355 351 (:REWRITE DEFAULT-CDR))
(350 35 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(322 322 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(290 290 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(200 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(200 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(166 161 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(166 161 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(140 140 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(105 105 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(82 77 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(76 76 (:REWRITE ABNF::TREE-LIST->STRING-WHEN-ATOM))
(70 70 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(70 70 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(70 70 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(66 11 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(60 24 (:REWRITE LEN-WHEN-ATOM))
(24 24 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(22 22 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(22 22 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(11 11 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(4 4 (:LINEAR LEN-WHEN-PREFIXP))
(2 2 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
(2 2 (:LINEAR INDEX-OF-<-LEN))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE JAVA::GRAMMAR-DEC-DIGITP-SUFF))
)
(JAVA::DEC-DIGIT-TREE
(4 4 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(4 4 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(4 4 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(4 4 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE DEFAULT-<-2))
(4 4 (:REWRITE DEFAULT-<-1))
(4 4 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(3 3 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP))
(2 2 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(2 2 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
)
(JAVA::RETURN-TYPE-OF-DEC-DIGIT-TREE
(34 34 (:REWRITE DEFAULT-<-2))
(34 34 (:REWRITE DEFAULT-<-1))
(33 32 (:REWRITE DEFAULT-CAR))
(32 31 (:REWRITE DEFAULT-CDR))
(30 5 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(28 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(28 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(24 24 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(22 22 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(18 2 (:REWRITE JAVA::DEC-DIGIT-FIX-WHEN-DEC-DIGITP))
(17 17 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(15 5 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(12 12 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(12 12 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(10 10 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(10 10 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(8 8 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(5 5 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(5 5 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(5 5 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(2 2 (:TYPE-PRESCRIPTION JAVA::DEC-DIGITP))
(2 2 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-FIX))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
)
(JAVA::TREE->STRING-OF-DEC-DIGIT-TREE
(26 4 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(12 2 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(11 11 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(11 11 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(11 11 (:REWRITE DEFAULT-<-2))
(11 11 (:REWRITE DEFAULT-<-1))
(10 2 (:REWRITE JAVA::DEC-DIGIT-FIX-WHEN-DEC-DIGITP))
(9 9 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(8 8 (:TYPE-PRESCRIPTION ABNF::TREE-KIND$INLINE))
(7 7 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(6 6 (:TYPE-PRESCRIPTION ABNF::TREE-NONLEAF->BRANCHES$INLINE))
(6 6 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(6 2 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(4 4 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(2 2 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(1 1 (:TYPE-PRESCRIPTION JAVA::DEC-DIGITP))
)
(JAVA::DEC-DIGIT-TREE-OF-DEC-DIGIT-FIX-DIGIT
(18 18 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-FIX))
)
(JAVA::DEC-DIGIT-TREE-DEC-DIGIT-EQUIV-CONGRUENCE-ON-DIGIT)
(JAVA::GRAMMAR-DEC-DIGITP-WHEN-DEC-DIGITP)
(JAVA::LEMMA
(11683 188 (:REWRITE ABNF::TREEP-OF-CAR-WHEN-TREE-LISTP))
(6615 5730 (:REWRITE DEFAULT-CAR))
(6503 5858 (:REWRITE DEFAULT-CDR))
(6202 188 (:REWRITE ABNF::TREE-LISTP-OF-CAR-WHEN-TREE-LIST-LISTP))
(5730 5730 (:REWRITE CAR-WHEN-ALL-EQUALP))
(3504 219 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(2847 219 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(2593 116 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-RULENAME-LISTP))
(1858 107 (:REWRITE ABNF::RULENAME-LISTP-OF-CDR-WHEN-RULENAME-LISTP))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(948 948 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(948 948 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(948 948 (:REWRITE CONSP-BY-LEN))
(785 263 (:REWRITE LEN-WHEN-ATOM))
(784 56 (:REWRITE JAVA::DEC-DIGITP-OF-CAR-WHEN-DEC-DIGIT-LISTP))
(606 606 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(606 606 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(606 606 (:LINEAR LEN-WHEN-PREFIXP))
(560 40 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(553 91 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(480 20 (:DEFINITION INTEGER-LISTP))
(460 460 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(460 460 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(450 450 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(438 438 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(438 219 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(438 219 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(438 219 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(438 219 (:REWRITE OMAP::SETP-WHEN-MAPP))
(438 219 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(438 219 (:REWRITE SET::NONEMPTY-MEANS-SET))
(428 428 (:REWRITE ABNF::RULENAME-LISTP-WHEN-SUBSETP-EQUAL))
(400 400 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(386 386 (:REWRITE CONSP-OF-CDR-BY-LEN))
(353 214 (:REWRITE ABNF::RULENAME-LISTP-WHEN-NOT-CONSP))
(336 56 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-NOT-CONSP))
(320 20 (:REWRITE NAT-LIST-FIX-WHEN-NAT-LISTP))
(303 303 (:LINEAR INDEX-OF-<-LEN))
(280 40 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(236 236 (:REWRITE ABNF::RULENAMEP-WHEN-MEMBER-EQUAL-OF-RULENAME-LISTP))
(234 234 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP))
(230 230 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(219 219 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(219 219 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(219 219 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(219 219 (:TYPE-PRESCRIPTION OMAP::MAPP))
(219 219 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(219 219 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(219 219 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(219 219 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(219 219 (:REWRITE JAVA::TRUE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(219 219 (:REWRITE SET::IN-SET))
(203 203 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(203 203 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(203 203 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(132 22 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(119 119 (:REWRITE ABNF::RULENAMEP-WHEN-IN-RULENAME-SETP-BINDS-FREE-X))
(112 112 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(112 112 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(91 91 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(78 78 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(73 39 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(73 39 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(48 4 (:REWRITE ABNF::TREE-LIST-LIST-FIX-UNDER-IFF))
(46 46 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(44 44 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(44 44 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(44 44 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(44 44 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(40 20 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(22 22 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(21 21 (:REWRITE CONSP-OF-CDDR-BY-LEN))
(20 20 (:REWRITE DEFAULT-<-2))
(20 20 (:REWRITE DEFAULT-<-1))
(19 19 (:REWRITE ABNF::RULENAME-OPTION-FIX-WHEN-NONE))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LIST-FIX$INLINE))
(14 14 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(14 7 (:REWRITE ABNF::TREE-LIST-LISTP-OF-CDR-WHEN-TREE-LIST-LISTP))
(4 4 (:REWRITE-QUOTED-CONSTANT TRUE-LIST-LIST-FIX-UNDER-TRUE-LIST-LIST-EQUIV))
(3 3 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::ALTERNATION-FIX-UNDER-ALTERNATION-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
)
(JAVA::DEC-DIGITP-WHEN-GRAMMAR-DEC-DIGITP
(48 3 (:REWRITE JAVA::DEC-DIGITP-OF-CAR-WHEN-DEC-DIGIT-LISTP))
(30 3 (:REWRITE DEFAULT-CAR))
(30 3 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-NOT-CONSP))
(6 6 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(6 6 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::DEC-DIGITP-IS-GRAMMAR-DEC-DIGITP
(2 2 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/java/language/.sys/decimal-digits-validation%40useless-runes.lsp | lisp | (JAVA::GRAMMAR-DEC-DIGITP)
(JAVA::GRAMMAR-DEC-DIGITP-SUFF)
(JAVA::BOOLEANP-OF-GRAMMAR-DEC-DIGITP)
(JAVA::GRAMMAR-DEC-DIGITP)
(JAVA::SINGLETON-WHEN-GRAMMAR-DEC-DIGITP
(1606 1602 (:REWRITE DEFAULT-CAR))
(1602 1602 (:REWRITE CAR-WHEN-ALL-EQUALP))
(920 120 (:REWRITE ABNF::TREE-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-TERMINATEDP))
(760 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-OF-CAR-WHEN-TREE-LIST-LIST-TERMINATEDP))
(455 70 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(400 400 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(400 400 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(355 351 (:REWRITE DEFAULT-CDR))
(350 35 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(322 322 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(290 290 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(200 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(200 200 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(166 161 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(166 161 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(140 140 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(105 105 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(82 77 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(76 76 (:REWRITE ABNF::TREE-LIST->STRING-WHEN-ATOM))
(70 70 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(70 70 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(70 70 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(66 11 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(60 24 (:REWRITE LEN-WHEN-ATOM))
(24 24 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(22 22 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(22 22 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(11 11 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(4 4 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(4 4 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(4 4 (:LINEAR LEN-WHEN-PREFIXP))
(2 2 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
(2 2 (:LINEAR INDEX-OF-<-LEN))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE JAVA::GRAMMAR-DEC-DIGITP-SUFF))
)
(JAVA::DEC-DIGIT-TREE
(4 4 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(4 4 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(4 4 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(4 4 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE DEFAULT-<-2))
(4 4 (:REWRITE DEFAULT-<-1))
(4 4 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(3 3 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP))
(2 2 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(2 2 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(1 1 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
)
(JAVA::RETURN-TYPE-OF-DEC-DIGIT-TREE
(34 34 (:REWRITE DEFAULT-<-2))
(34 34 (:REWRITE DEFAULT-<-1))
(33 32 (:REWRITE DEFAULT-CAR))
(32 31 (:REWRITE DEFAULT-CDR))
(30 5 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(28 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(28 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(24 24 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(22 22 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(22 22 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(19 19 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(18 2 (:REWRITE JAVA::DEC-DIGIT-FIX-WHEN-DEC-DIGITP))
(17 17 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(15 5 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(12 12 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(12 12 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(10 10 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(10 10 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(8 8 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(5 5 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(5 5 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(5 5 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(2 2 (:TYPE-PRESCRIPTION JAVA::DEC-DIGITP))
(2 2 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-FIX))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(2 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
)
(JAVA::TREE->STRING-OF-DEC-DIGIT-TREE
(26 4 (:REWRITE ABNF::TREE-LIST-LIST->STRING-WHEN-ATOM))
(12 2 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP))
(11 11 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-LIST-FIX-UNDER-TREE-LIST-LIST-EQUIV))
(11 11 (:REWRITE-QUOTED-CONSTANT ABNF::TREE-LIST-FIX-UNDER-TREE-LIST-EQUIV))
(11 11 (:REWRITE DEFAULT-<-2))
(11 11 (:REWRITE DEFAULT-<-1))
(10 2 (:REWRITE JAVA::DEC-DIGIT-FIX-WHEN-DEC-DIGITP))
(9 9 (:REWRITE-QUOTED-CONSTANT ABNF::RULENAME-OPTION-FIX-UNDER-RULENAME-OPTION-EQUIV))
(8 8 (:TYPE-PRESCRIPTION ABNF::TREE-KIND$INLINE))
(7 7 (:REWRITE-QUOTED-CONSTANT NAT-LIST-FIX-UNDER-NAT-LIST-EQUIV))
(6 6 (:TYPE-PRESCRIPTION ABNF::TREE-NONLEAF->BRANCHES$INLINE))
(6 6 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(6 2 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP))
(4 4 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(2 2 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(2 2 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(1 1 (:TYPE-PRESCRIPTION JAVA::DEC-DIGITP))
)
(JAVA::DEC-DIGIT-TREE-OF-DEC-DIGIT-FIX-DIGIT
(18 18 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-FIX))
)
(JAVA::DEC-DIGIT-TREE-DEC-DIGIT-EQUIV-CONGRUENCE-ON-DIGIT)
(JAVA::GRAMMAR-DEC-DIGITP-WHEN-DEC-DIGITP)
(JAVA::LEMMA
(11683 188 (:REWRITE ABNF::TREEP-OF-CAR-WHEN-TREE-LISTP))
(6615 5730 (:REWRITE DEFAULT-CAR))
(6503 5858 (:REWRITE DEFAULT-CDR))
(6202 188 (:REWRITE ABNF::TREE-LISTP-OF-CAR-WHEN-TREE-LIST-LISTP))
(5730 5730 (:REWRITE CAR-WHEN-ALL-EQUALP))
(3504 219 (:REWRITE SET::SETS-ARE-TRUE-LISTS-CHEAP))
(2847 219 (:REWRITE TRUE-LISTP-WHEN-ATOM))
(2593 116 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-RULENAME-LISTP))
(1858 107 (:REWRITE ABNF::RULENAME-LISTP-OF-CDR-WHEN-RULENAME-LISTP))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(948 948 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(948 948 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(948 948 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(948 948 (:REWRITE CONSP-BY-LEN))
(785 263 (:REWRITE LEN-WHEN-ATOM))
(784 56 (:REWRITE JAVA::DEC-DIGITP-OF-CAR-WHEN-DEC-DIGIT-LISTP))
(606 606 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(606 606 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(606 606 (:LINEAR LEN-WHEN-PREFIXP))
(560 40 (:REWRITE INTEGERP-OF-CAR-WHEN-INTEGER-LISTP))
(553 91 (:REWRITE NAT-LISTP-WHEN-NOT-CONSP))
(480 20 (:DEFINITION INTEGER-LISTP))
(460 460 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL))
(460 460 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP))
(450 450 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL))
(438 438 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(438 219 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(438 219 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(438 219 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(438 219 (:REWRITE OMAP::SETP-WHEN-MAPP))
(438 219 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(438 219 (:REWRITE SET::NONEMPTY-MEANS-SET))
(428 428 (:REWRITE ABNF::RULENAME-LISTP-WHEN-SUBSETP-EQUAL))
(400 400 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP))
(386 386 (:REWRITE CONSP-OF-CDR-BY-LEN))
(353 214 (:REWRITE ABNF::RULENAME-LISTP-WHEN-NOT-CONSP))
(336 56 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-NOT-CONSP))
(320 20 (:REWRITE NAT-LIST-FIX-WHEN-NAT-LISTP))
(303 303 (:LINEAR INDEX-OF-<-LEN))
(280 40 (:REWRITE INTEGER-LISTP-WHEN-NOT-CONSP))
(236 236 (:REWRITE ABNF::RULENAMEP-WHEN-MEMBER-EQUAL-OF-RULENAME-LISTP))
(234 234 (:REWRITE ABNF::RULENAMEP-OF-CAR-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP))
(230 230 (:REWRITE JAVA::ABNF-TREE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(219 219 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(219 219 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(219 219 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(219 219 (:TYPE-PRESCRIPTION OMAP::MAPP))
(219 219 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(219 219 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(219 219 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(219 219 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(219 219 (:REWRITE JAVA::TRUE-LISTP-WHEN-ABNF-TREE-LIST-WITH-ROOT-P))
(219 219 (:REWRITE SET::IN-SET))
(203 203 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP))
(203 203 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X))
(203 203 (:REWRITE JAVA::ABNF-TREEP-WHEN-ABNF-TREE-WITH-ROOT-P))
(132 22 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-OF-CAR-WHEN-TREE-LIST-MATCH-ELEMENT-P))
(119 119 (:REWRITE ABNF::RULENAMEP-WHEN-IN-RULENAME-SETP-BINDS-FREE-X))
(112 112 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(112 112 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(91 91 (:REWRITE NAT-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(78 78 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL))
(73 39 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP))
(73 39 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM))
(48 4 (:REWRITE ABNF::TREE-LIST-LIST-FIX-UNDER-IFF))
(46 46 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P))
(44 44 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-MATCH-ELEMENT-P))
(44 44 (:REWRITE-QUOTED-CONSTANT NFIX-UNDER-NAT-EQUIV))
(44 44 (:REWRITE-QUOTED-CONSTANT IFIX-UNDER-INT-EQUIV))
(44 44 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL))
(40 20 (:REWRITE INTEGER-LISTP-OF-CDR-WHEN-INTEGER-LISTP))
(22 22 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP))
(21 21 (:REWRITE CONSP-OF-CDDR-BY-LEN))
(20 20 (:REWRITE DEFAULT-<-2))
(20 20 (:REWRITE DEFAULT-<-1))
(19 19 (:REWRITE ABNF::RULENAME-OPTION-FIX-WHEN-NONE))
(16 16 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LIST-FIX$INLINE))
(14 14 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP))
(14 7 (:REWRITE ABNF::TREE-LIST-LISTP-OF-CDR-WHEN-TREE-LIST-LISTP))
(4 4 (:REWRITE-QUOTED-CONSTANT TRUE-LIST-LIST-FIX-UNDER-TRUE-LIST-LIST-EQUIV))
(3 3 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV))
(2 2 (:REWRITE-QUOTED-CONSTANT ABNF::ALTERNATION-FIX-UNDER-ALTERNATION-EQUIV))
(1 1 (:REWRITE-QUOTED-CONSTANT ABNF::ELEMENT-FIX-UNDER-ELEMENT-EQUIV))
)
(JAVA::DEC-DIGITP-WHEN-GRAMMAR-DEC-DIGITP
(48 3 (:REWRITE JAVA::DEC-DIGITP-OF-CAR-WHEN-DEC-DIGIT-LISTP))
(30 3 (:REWRITE DEFAULT-CAR))
(30 3 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-NOT-CONSP))
(6 6 (:TYPE-PRESCRIPTION JAVA::DEC-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
(6 6 (:REWRITE JAVA::DEC-DIGIT-LISTP-WHEN-SUBSETP-EQUAL))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(6 6 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(6 6 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(6 6 (:REWRITE JAVA::ABNF-TREE-WITH-ROOT-P-WHEN-MEMBER-EQUAL-OF-ABNF-TREE-LIST-WITH-ROOT-P))
)
(JAVA::DEC-DIGITP-IS-GRAMMAR-DEC-DIGITP
(2 2 (:REWRITE JAVA::DEC-DIGITP-WHEN-MEMBER-EQUAL-OF-DEC-DIGIT-LISTP))
)
|
||
f6756fd986c7a61285048f4beb13e3e1500c39ac6722fe500280f5b9ae1bf910 | replomancer/Swordfight | project.clj | (defproject swordfight "0.8.0-SNAPSHOT"
:description "Chess engine"
:url ""
:main swordfight.core
:license {:name "BSD-2-clause"
:url "-2-Clause"}
:dependencies [[org.clojure/clojure "1.9.0"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[midje "1.9.0-alpha6"]
[com.taoensso/tufte "1.1.1"]]
:plugins [[lein-midje "3.2"] [lein-cljfmt "0.5.6"]]}})
| null | https://raw.githubusercontent.com/replomancer/Swordfight/4ac956d0c9076792774dd05db3f258a8c713c49c/project.clj | clojure | (defproject swordfight "0.8.0-SNAPSHOT"
:description "Chess engine"
:url ""
:main swordfight.core
:license {:name "BSD-2-clause"
:url "-2-Clause"}
:dependencies [[org.clojure/clojure "1.9.0"]]
:profiles {:dev {:source-paths ["dev"]
:dependencies [[midje "1.9.0-alpha6"]
[com.taoensso/tufte "1.1.1"]]
:plugins [[lein-midje "3.2"] [lein-cljfmt "0.5.6"]]}})
|
|
f2652fdff955dfbc575388122466d29e3a9c481970f587a517cdc3b08e41db5d | darrenldl/stramon | ctx.ml | type 'a t = {
proc_ctxs : (int, Proc_ctx.t) Hashtbl.t;
mutable stats : Stats.t;
mutable user_ctx : 'a;
}
let make (user_ctx : 'a) : 'a t =
{
proc_ctxs = Hashtbl.create 100;
stats = Stats.empty;
user_ctx;
}
let get_user_ctx t = t.user_ctx
let set_user_ctx t x = t.user_ctx <- x
let get_stats t = t.stats
let set_stats t x = t.stats <- x
let get_proc_ctx t ~pid =
match Hashtbl.find_opt t.proc_ctxs pid with
| None ->
let proc_ctx = Proc_ctx.make () in
Hashtbl.replace t.proc_ctxs pid proc_ctx;
proc_ctx
| Some proc_ctx ->
proc_ctx
let remove_proc_ctx t ~pid =
Hashtbl.remove t.proc_ctxs pid
| null | https://raw.githubusercontent.com/darrenldl/stramon/60680249af7367301115158eaee5d8cc3c5ce506/lib/ctx.ml | ocaml | type 'a t = {
proc_ctxs : (int, Proc_ctx.t) Hashtbl.t;
mutable stats : Stats.t;
mutable user_ctx : 'a;
}
let make (user_ctx : 'a) : 'a t =
{
proc_ctxs = Hashtbl.create 100;
stats = Stats.empty;
user_ctx;
}
let get_user_ctx t = t.user_ctx
let set_user_ctx t x = t.user_ctx <- x
let get_stats t = t.stats
let set_stats t x = t.stats <- x
let get_proc_ctx t ~pid =
match Hashtbl.find_opt t.proc_ctxs pid with
| None ->
let proc_ctx = Proc_ctx.make () in
Hashtbl.replace t.proc_ctxs pid proc_ctx;
proc_ctx
| Some proc_ctx ->
proc_ctx
let remove_proc_ctx t ~pid =
Hashtbl.remove t.proc_ctxs pid
|
|
95be6b0945c19005ded334ec2a0a173588d04ced01542e1b9e59cf00cc6da944 | ggreif/omega | CircularFinal.hs | # LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts
, ViewPatterns , TypeOperators #
, ViewPatterns, TypeOperators #-}
import Prelude hiding (max, null, lookup, map)
import qualified Prelude as Prelude (max)
import Data.Map
import qualified Data.List as L
--import Data.Set hiding (singleton)
import qualified Data.Set as S
import Data.Monoid
import Data.Function
see : , : Using Circular Programs for Higher - Order Syntax
-- ICFP 2013
class LC p where
app :: p -> p -> p
lam :: (p -> p) -> p
first order interpretation
data Lam name = Var name
| App (Lam name) (Lam name)
| Lam name (Lam name)
| Lam name `Cho` Lam name
deriving Show
-- join monoid
class Join t where
bot :: t
prime :: t -> t
(|-|) :: t -> t -> t
class Max lc t where
max :: lc t -> t
instance Join name => LC (Lam name) where
app = App
lam f = Lam name body
where body = f (Var name)
name = prime (max body)
-- operator for indeterministic choice
class LC p => Indet p where
(~~) :: p -> p -> p
instance Join Int where
bot = 0
prime = (+1)
(|-|) = Prelude.max
instance Join name => Max Lam name where
max (Var _) = bot
max (f `App` a) = max f |-| max a
max (a `Cho` b) = max a |-| max b
max (Lam name _) = name
t1' :: LC p => p
t1' = lam (\a -> a `app` a)
t1 :: Lam Int
t1 = t1'
t2' :: LC p => p
t2' = lam (\a -> lam (\b -> a `app` b))
t2 :: Lam Int
t2 = t2'
t3' :: Indet p => p
t3' = lam (\a -> lam (\b -> a ~~ b))
t3 : : ( Int , Int )
t3 :: (Lam Int, Lam Int)
t3 = t3'
t3'' :: (Ty Int, Ty Int, [Ty Int])
t3'' = t3'
t3''' :: Ty Int
t3''' = t3'
t0' :: Indet p => p
t0' = lam (\a -> a ~~ a)
t0 :: (Lam Int, Ty Int)
t0 = t0'
t5' :: Indet p => p
t5' = lam (\a -> lam (\b -> b ~~ b) `app` a)
t5 :: (Lam Int, Ty Int)
t5 = t5'
t6' :: LC p => p
t6' = lam (\a -> a)
t6 :: (Ty Int, Ty Int, [Ty Int])
t6 = t6'
# # # # # # # # # # # a very simple initial type universe # # # # # # # # # # #
data Type = Va (S.Set String) | Type `Ar` Type | Int | Cannot Type Type
deriving (Eq, Show)
va, va' :: String -> Type
va = Va . S.singleton
va' = Va . S.fromList . fmap return
can :: Type -> Bool
can Cannot{} = False
can (a `Ar` b) = can a && can b
can Int = True
can Va{} = True
-- NOTE: unify must have a *much* more precise type, that describes all the
-- distinct islands that are known. Then it can be decided whether
-- obligations surface because of island merging. It must be a minimal
-- cover. I.e. smallest set of mutually disjoint islands that covers
-- them all.
infix 1 `unify`
unify :: Type -> Type -> (Type, Aliases `Map` Type)
Va a `unify` Va b | A a == A b = (a `vas` b, empty)
a `unify` b | a == b = (a, empty)
Va a `unify` Va b = (Va (a `S.union` b), empty)
Va a `unify` b = bumm (b, a `pointsTo` b)
a `unify` Va b = Va b `unify` a
Ar a c `unify` Ar b d = if can f && can s
then (f `Ar` s, f' `unifion` s')
else (Ar a c `Cannot` Ar b d, empty)
where (f, f') = a `unify` b
(s, s') = c `unify` d
l `unifion` r | int <- l `intersection` r
= case int of
(null -> True) -> l `union` r
overlap -> error $ "overlapping keys: " ++ show (keysSet overlap)
a `unify` b = (a `Cannot` b, empty)
pointsTo :: S.Set String -> Type -> Aliases `Map` Type
CHECK missing , any mentions of ` s ` in ` t ` ?
-- TODO: Eliminate overlaps by unification
TODO : utilize type system to avoid Va as values in Map
-- CHECK: add assertion that pointsTo does not cause continent growth
-- NOTE: *Any* island growth can lead to fresh unification obligations.
-- So what we really need is an algo, that returns a list of
-- obligations too for circular solving purposes.
joinObl :: Aliases `Map` Type -> Aliases `Map` Type -> (Aliases `Map` Type, [(Type, Type)])
joinObl = error "TODO: cartesian product of keys?"
-- Aliases: non-empty sets of names that are known to unify
newtype Aliases = A (S.Set String) deriving Show
instance Eq Aliases where
A l == A r = not . S.null $ l `S.intersection` r
-- Note: this is not a transitive thing:
-- a == b /\ b == c /=> a == c, as there may not be an overlap
a = { 1,2 } , b = { 2,3 } , c = { 3,4 }
instance Monoid Aliases where
mempty = A S.empty
A l `mappend` A r = A $ l `S.union` r
instance Ord Aliases where
A l `compare` A r | A l == A r = EQ
A l `compare` A r = leader l `compare` leader r
-- Note: this is not a transitive thing, so do not expect
-- the normal indexing into a map to work
-- we have kind of a partial order, as equality messes up things
-- a < b /\ b < c => a < c only when a /= c
leader = S.elemAt 0 -- widest in scope: best
followers = tail . S.toList -- inferiors
-- assumes that the alias continents are maximal
subst :: Type -> (Aliases -> Type) -> Type
Va l `subst` f = f (A l)
Int `subst` _ = Int
Ar a b `subst` f = subst a f `Ar` subst b f
c@Cannot{} `subst` _ = c
-- assumes that the alias continents are maximal
substMap :: Type -> Aliases `Map` Type -> Type
ty `substMap` m = ty `subst` \as@(A ns) -> case as `lookup` m of Just ty -> ty; _ -> Va ns
simplify :: (Type, Aliases `Map` Type) -> Type
simplify = uncurry substMap
aliasSets :: Type -> S.Set Aliases -> S.Set Aliases
Va names `aliasSets` set = unB $ (B . S.singleton . A) names `mappend` B set
(a `Ar` b) `aliasSets` set = a `aliasSets` (b `aliasSets` set)
(a `Cannot` b) `aliasSets` set = a `aliasSets` (b `aliasSets` set)
Int `aliasSets` set = set
b = B . S.singleton . A
-- repMin-like circularity
als :: Type -> AliasSet -> (Type, AliasSet)
Va names `als` B s = (Va full, b names)
where Just (A full) = A names `S.lookupLE` s
(a `Ar` b) `als` s = (a' `Ar` b', as `mappend` bs)
where (a', as) = a `als` s
(b', bs) = b `als` s
Int `als` s = (Int, B S.empty)
alsM :: Aliases `Map` Type -> AliasSet -> (Aliases `Map` Type, AliasSet)
alsM m a@(B s) = (map (fst . flip als a) (mapKeys go m), B (keysSet m))
where go k | Just full <- k `S.lookupLE` s = full
als2 :: (Type, Aliases `Map` Type) -> AliasSet -> ((Type, Aliases `Map` Type), AliasSet)
als2 (t, m) s = ((t', m'), ts `mappend` ms)
where (t', ts) = t `als` s
(m', ms) = m `alsM` s
trace f t = out
where (out, feedback) = f t feedback
wumm = trace als
mumm = trace alsM
bumm :: (Type, Aliases `Map` Type) -> (Type, Aliases `Map` Type)
bumm = trace als2
-- Research Q: do alias sets form sheaves/toposes?
AliasSet : alias - disjoint name sets
CAVEAT : all keys must be mutually disjoint !
--
newtype AliasSet = B (S.Set Aliases) deriving Show
unB (B b) = b
instance Monoid AliasSet where
mempty = B mempty
(S.toList . unB -> ls) `mappend` (B rs) = B $ ls `go` rs
where [] `go` rs = rs
(ls:rest) `go` rs | (sames, diffs) <- (== ls) `S.partition` rs = rest `go` S.union (smash ls sames) diffs
smash a = S.singleton . A . S.unions . L.map (\(A s) -> s) . (a:) . S.toList
l `vas` r = Va $ l `S.union` r
v0 = va "a" `Ar` Int `unify` va "b" `Ar` va "b"
v1 = va "a" `Ar` (Int `Ar` va "a") `unify` (Int `Ar` va "b") `Ar` va "d"
v2 = va "a" `Ar` va "a" `unify` Int `Ar` Int
v3 = va "a" `Ar` (Int `Ar` va "b") `unify` va "a1" `Ar` (Int `Ar` va "b1")
aliases = (`aliasSets` S.empty)
av0 = fst v0 `aliasSets` S.empty
av1 = aliases $ fst v1
av3 = fst v3 `aliasSets` S.empty
av4 = aliases $ va' "abc" `Ar` va' "bcd"
`Ar` va' "ef"
av5 = aliases $ (va' "abc" `Ar` va' "def")
`Ar` va' "be"
av5' = aliases $ va' "be"
`Ar` (va' "abc" `Ar` va' "def")
av51 = aliases $ va' "abc"
av52 = aliases $ va' "def"
b1 = Ar (va "a") (va "c") `unify` va' "abc"
b2 = Ar (va "a") (va "c") `unify` va' "abc"
# # # # # # # # # # # the pairing trick # # # # # # # # # # #
instance (LC r, LC r') => LC (r, r') where
(f, f') `app` (a, a') = (f `app` a, f' `app` a')
lam f = (lam f1, lam f2)
where f1 a = fst $ f (a, undefined) -- provide a bottom
f2 a' = snd $ f (undefined, a') -- provide a bottom
instance (Indet p, Indet p') => Indet (p, p') where
(l, l') ~~ (r, r') = (l ~~ r, l' ~~ r')
# # # # # # # # # # # can we use a similar trick for type inference ? # # # # # # # # # # #
instance Join name => Indet (Lam name) where
(~~) = Cho
instance Join name = > Join ( name , Int ) where
bot = ( bot , 42 )
prime ( p , x ) = ( prime p , x )
( a , x ) |-| ( b , y ) = ( a |-| b , x )
instance Join name => Join (name, Int) where
bot = (bot, 42)
prime (p, x) = (prime p, x)
(a, x) |-| (b, y) = (a |-| b, x)
-}
-- develop a vocabulary for inference
class LC ( name ) = > Inf p name where
-- ofvar :: name -> p -- type of variable named
class LC p => Inf p where
ofvar :: p -> p -- type of variable (must be variable!)
equate :: p -> p -> p
arr :: p -> p -> p
e.g. a LC one level up ( vals - > tys )
instance LC p => LC (Up p) where
Up f `app` Up a = Up $ undefined -- plan: intro an abstraction arrow and apply it on type of arg to obtain type of result
data Ty name = Univ name | Ty name `Equate` Ty name | Ty name `Arr` Ty name | Ty name `TApp` Ty name | Fresh
deriving Show
instance Join name => Max Ty name where
max Fresh = bot
max (Univ _) = bot
max (f `TApp` a) = max f |-| max a
max (a `Equate` b) = max a |-| max b
( name _ ) = name
max (a `Arr` b) = max a |-| max b
instance Join name => LC (Ty name) where
f `app` a = (f `Equate` (a `Arr` Fresh)) `TApp` a
lam f = u `Arr` body
where u = Univ name
body = f u
name = prime (max body)
instance Join name => Indet (Ty name) where
(~~) = Equate
data AllEquates = AE (Ty Int) ((Int, [Ty Int]) -> (Int, [Ty Int]))
# # # # # experiment with collecting equate constraints
instance Indet (Ty Int, Ty Int, [Ty Int]) where
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l == r = (lty ~~ rty, Univ l, ls ++ rs)
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l > r = (lty ~~ rty, Univ l, Univ r : ls)
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l < r = (lty ~~ rty, Univ r, Univ l : rs)
instance LC (Ty Int, Ty Int, [Ty Int]) where
lam f = f (arrow, u, [])
where f1 a = fst (f (a, Univ bot, []))
fst (a, b, c) = a
arrow@(u@Univ{} `Arr` _) = lam f1
# # # # # have a type - level fixpoint , eliminating equated universals .
| null | https://raw.githubusercontent.com/ggreif/omega/016a3b48313ec2c68e8d8ad60147015bc38f2767/mosaic/CircularFinal.hs | haskell | import Data.Set hiding (singleton)
ICFP 2013
join monoid
operator for indeterministic choice
NOTE: unify must have a *much* more precise type, that describes all the
distinct islands that are known. Then it can be decided whether
obligations surface because of island merging. It must be a minimal
cover. I.e. smallest set of mutually disjoint islands that covers
them all.
TODO: Eliminate overlaps by unification
CHECK: add assertion that pointsTo does not cause continent growth
NOTE: *Any* island growth can lead to fresh unification obligations.
So what we really need is an algo, that returns a list of
obligations too for circular solving purposes.
Aliases: non-empty sets of names that are known to unify
Note: this is not a transitive thing:
a == b /\ b == c /=> a == c, as there may not be an overlap
Note: this is not a transitive thing, so do not expect
the normal indexing into a map to work
we have kind of a partial order, as equality messes up things
a < b /\ b < c => a < c only when a /= c
widest in scope: best
inferiors
assumes that the alias continents are maximal
assumes that the alias continents are maximal
repMin-like circularity
Research Q: do alias sets form sheaves/toposes?
provide a bottom
provide a bottom
develop a vocabulary for inference
ofvar :: name -> p -- type of variable named
type of variable (must be variable!)
plan: intro an abstraction arrow and apply it on type of arg to obtain type of result | # LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts
, ViewPatterns , TypeOperators #
, ViewPatterns, TypeOperators #-}
import Prelude hiding (max, null, lookup, map)
import qualified Prelude as Prelude (max)
import Data.Map
import qualified Data.List as L
import qualified Data.Set as S
import Data.Monoid
import Data.Function
see : , : Using Circular Programs for Higher - Order Syntax
class LC p where
app :: p -> p -> p
lam :: (p -> p) -> p
first order interpretation
data Lam name = Var name
| App (Lam name) (Lam name)
| Lam name (Lam name)
| Lam name `Cho` Lam name
deriving Show
class Join t where
bot :: t
prime :: t -> t
(|-|) :: t -> t -> t
class Max lc t where
max :: lc t -> t
instance Join name => LC (Lam name) where
app = App
lam f = Lam name body
where body = f (Var name)
name = prime (max body)
class LC p => Indet p where
(~~) :: p -> p -> p
instance Join Int where
bot = 0
prime = (+1)
(|-|) = Prelude.max
instance Join name => Max Lam name where
max (Var _) = bot
max (f `App` a) = max f |-| max a
max (a `Cho` b) = max a |-| max b
max (Lam name _) = name
t1' :: LC p => p
t1' = lam (\a -> a `app` a)
t1 :: Lam Int
t1 = t1'
t2' :: LC p => p
t2' = lam (\a -> lam (\b -> a `app` b))
t2 :: Lam Int
t2 = t2'
t3' :: Indet p => p
t3' = lam (\a -> lam (\b -> a ~~ b))
t3 : : ( Int , Int )
t3 :: (Lam Int, Lam Int)
t3 = t3'
t3'' :: (Ty Int, Ty Int, [Ty Int])
t3'' = t3'
t3''' :: Ty Int
t3''' = t3'
t0' :: Indet p => p
t0' = lam (\a -> a ~~ a)
t0 :: (Lam Int, Ty Int)
t0 = t0'
t5' :: Indet p => p
t5' = lam (\a -> lam (\b -> b ~~ b) `app` a)
t5 :: (Lam Int, Ty Int)
t5 = t5'
t6' :: LC p => p
t6' = lam (\a -> a)
t6 :: (Ty Int, Ty Int, [Ty Int])
t6 = t6'
# # # # # # # # # # # a very simple initial type universe # # # # # # # # # # #
data Type = Va (S.Set String) | Type `Ar` Type | Int | Cannot Type Type
deriving (Eq, Show)
va, va' :: String -> Type
va = Va . S.singleton
va' = Va . S.fromList . fmap return
can :: Type -> Bool
can Cannot{} = False
can (a `Ar` b) = can a && can b
can Int = True
can Va{} = True
infix 1 `unify`
unify :: Type -> Type -> (Type, Aliases `Map` Type)
Va a `unify` Va b | A a == A b = (a `vas` b, empty)
a `unify` b | a == b = (a, empty)
Va a `unify` Va b = (Va (a `S.union` b), empty)
Va a `unify` b = bumm (b, a `pointsTo` b)
a `unify` Va b = Va b `unify` a
Ar a c `unify` Ar b d = if can f && can s
then (f `Ar` s, f' `unifion` s')
else (Ar a c `Cannot` Ar b d, empty)
where (f, f') = a `unify` b
(s, s') = c `unify` d
l `unifion` r | int <- l `intersection` r
= case int of
(null -> True) -> l `union` r
overlap -> error $ "overlapping keys: " ++ show (keysSet overlap)
a `unify` b = (a `Cannot` b, empty)
pointsTo :: S.Set String -> Type -> Aliases `Map` Type
CHECK missing , any mentions of ` s ` in ` t ` ?
TODO : utilize type system to avoid Va as values in Map
joinObl :: Aliases `Map` Type -> Aliases `Map` Type -> (Aliases `Map` Type, [(Type, Type)])
joinObl = error "TODO: cartesian product of keys?"
newtype Aliases = A (S.Set String) deriving Show
instance Eq Aliases where
A l == A r = not . S.null $ l `S.intersection` r
a = { 1,2 } , b = { 2,3 } , c = { 3,4 }
instance Monoid Aliases where
mempty = A S.empty
A l `mappend` A r = A $ l `S.union` r
instance Ord Aliases where
A l `compare` A r | A l == A r = EQ
A l `compare` A r = leader l `compare` leader r
subst :: Type -> (Aliases -> Type) -> Type
Va l `subst` f = f (A l)
Int `subst` _ = Int
Ar a b `subst` f = subst a f `Ar` subst b f
c@Cannot{} `subst` _ = c
substMap :: Type -> Aliases `Map` Type -> Type
ty `substMap` m = ty `subst` \as@(A ns) -> case as `lookup` m of Just ty -> ty; _ -> Va ns
simplify :: (Type, Aliases `Map` Type) -> Type
simplify = uncurry substMap
aliasSets :: Type -> S.Set Aliases -> S.Set Aliases
Va names `aliasSets` set = unB $ (B . S.singleton . A) names `mappend` B set
(a `Ar` b) `aliasSets` set = a `aliasSets` (b `aliasSets` set)
(a `Cannot` b) `aliasSets` set = a `aliasSets` (b `aliasSets` set)
Int `aliasSets` set = set
b = B . S.singleton . A
als :: Type -> AliasSet -> (Type, AliasSet)
Va names `als` B s = (Va full, b names)
where Just (A full) = A names `S.lookupLE` s
(a `Ar` b) `als` s = (a' `Ar` b', as `mappend` bs)
where (a', as) = a `als` s
(b', bs) = b `als` s
Int `als` s = (Int, B S.empty)
alsM :: Aliases `Map` Type -> AliasSet -> (Aliases `Map` Type, AliasSet)
alsM m a@(B s) = (map (fst . flip als a) (mapKeys go m), B (keysSet m))
where go k | Just full <- k `S.lookupLE` s = full
als2 :: (Type, Aliases `Map` Type) -> AliasSet -> ((Type, Aliases `Map` Type), AliasSet)
als2 (t, m) s = ((t', m'), ts `mappend` ms)
where (t', ts) = t `als` s
(m', ms) = m `alsM` s
trace f t = out
where (out, feedback) = f t feedback
wumm = trace als
mumm = trace alsM
bumm :: (Type, Aliases `Map` Type) -> (Type, Aliases `Map` Type)
bumm = trace als2
AliasSet : alias - disjoint name sets
CAVEAT : all keys must be mutually disjoint !
newtype AliasSet = B (S.Set Aliases) deriving Show
unB (B b) = b
instance Monoid AliasSet where
mempty = B mempty
(S.toList . unB -> ls) `mappend` (B rs) = B $ ls `go` rs
where [] `go` rs = rs
(ls:rest) `go` rs | (sames, diffs) <- (== ls) `S.partition` rs = rest `go` S.union (smash ls sames) diffs
smash a = S.singleton . A . S.unions . L.map (\(A s) -> s) . (a:) . S.toList
l `vas` r = Va $ l `S.union` r
v0 = va "a" `Ar` Int `unify` va "b" `Ar` va "b"
v1 = va "a" `Ar` (Int `Ar` va "a") `unify` (Int `Ar` va "b") `Ar` va "d"
v2 = va "a" `Ar` va "a" `unify` Int `Ar` Int
v3 = va "a" `Ar` (Int `Ar` va "b") `unify` va "a1" `Ar` (Int `Ar` va "b1")
aliases = (`aliasSets` S.empty)
av0 = fst v0 `aliasSets` S.empty
av1 = aliases $ fst v1
av3 = fst v3 `aliasSets` S.empty
av4 = aliases $ va' "abc" `Ar` va' "bcd"
`Ar` va' "ef"
av5 = aliases $ (va' "abc" `Ar` va' "def")
`Ar` va' "be"
av5' = aliases $ va' "be"
`Ar` (va' "abc" `Ar` va' "def")
av51 = aliases $ va' "abc"
av52 = aliases $ va' "def"
b1 = Ar (va "a") (va "c") `unify` va' "abc"
b2 = Ar (va "a") (va "c") `unify` va' "abc"
# # # # # # # # # # # the pairing trick # # # # # # # # # # #
instance (LC r, LC r') => LC (r, r') where
(f, f') `app` (a, a') = (f `app` a, f' `app` a')
lam f = (lam f1, lam f2)
instance (Indet p, Indet p') => Indet (p, p') where
(l, l') ~~ (r, r') = (l ~~ r, l' ~~ r')
# # # # # # # # # # # can we use a similar trick for type inference ? # # # # # # # # # # #
instance Join name => Indet (Lam name) where
(~~) = Cho
instance Join name = > Join ( name , Int ) where
bot = ( bot , 42 )
prime ( p , x ) = ( prime p , x )
( a , x ) |-| ( b , y ) = ( a |-| b , x )
instance Join name => Join (name, Int) where
bot = (bot, 42)
prime (p, x) = (prime p, x)
(a, x) |-| (b, y) = (a |-| b, x)
-}
class LC ( name ) = > Inf p name where
class LC p => Inf p where
equate :: p -> p -> p
arr :: p -> p -> p
e.g. a LC one level up ( vals - > tys )
instance LC p => LC (Up p) where
data Ty name = Univ name | Ty name `Equate` Ty name | Ty name `Arr` Ty name | Ty name `TApp` Ty name | Fresh
deriving Show
instance Join name => Max Ty name where
max Fresh = bot
max (Univ _) = bot
max (f `TApp` a) = max f |-| max a
max (a `Equate` b) = max a |-| max b
( name _ ) = name
max (a `Arr` b) = max a |-| max b
instance Join name => LC (Ty name) where
f `app` a = (f `Equate` (a `Arr` Fresh)) `TApp` a
lam f = u `Arr` body
where u = Univ name
body = f u
name = prime (max body)
instance Join name => Indet (Ty name) where
(~~) = Equate
data AllEquates = AE (Ty Int) ((Int, [Ty Int]) -> (Int, [Ty Int]))
# # # # # experiment with collecting equate constraints
instance Indet (Ty Int, Ty Int, [Ty Int]) where
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l == r = (lty ~~ rty, Univ l, ls ++ rs)
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l > r = (lty ~~ rty, Univ l, Univ r : ls)
(lty, Univ l, ls) ~~ (rty, Univ r, rs) | l < r = (lty ~~ rty, Univ r, Univ l : rs)
instance LC (Ty Int, Ty Int, [Ty Int]) where
lam f = f (arrow, u, [])
where f1 a = fst (f (a, Univ bot, []))
fst (a, b, c) = a
arrow@(u@Univ{} `Arr` _) = lam f1
# # # # # have a type - level fixpoint , eliminating equated universals .
|
07cbc9e0001f30e1634dddf5b277019f9e86c78f03d0cf799726429ac53260b5 | Akii/elescore | Bogestra.hs | # LANGUAGE DataKinds #
module Elescore.Integration.Bogestra
( runBogSource
) where
import ClassyPrelude
import Pipes
import Pipes.Concurrent
import qualified Pipes.Prelude as P
import Database.SimpleEventStore
import Elescore.Integration.Bogestra.Client
import Elescore.Integration.Bogestra.Monitor
import Elescore.Integration.Bogestra.Types
import Elescore.Integration.Common.Monitoring
import Elescore.Integration.Common.Types
import Elescore.Integration.Common.Utils
runBogSource :: MonadIO m => Store -> m (Source 'Bogestra)
runBogSource store = do
(out1, in1) <- liftIO (spawn unbounded)
(out2, in2) <- liftIO (spawn unbounded)
void . liftIO . forkIO $ runEffect $ elevatorP 900 >-> toOutput (out1 <> out2)
dP <- disruptions store
fP <- facilities store
oEvs <- liftIO (readStream store)
(out4, in4) <- liftIO (spawn unbounded)
(out5, in5) <- liftIO (spawn unbounded)
(out6, in6) <- liftIO (spawn unbounded)
liftIO $ do
void . forkIO . runEffect $ fromInput in1 >-> dP >-> toOutput out4
void . forkIO . runEffect $ fromInput in2 >-> fP >-> toOutput out5
runEffect (each oEvs >-> toOutput out6)
return Source
{ disruptionEvents = in4
, facilityEvents = in5
, objectEvents = in6
}
where
elevatorP :: MonadIO m => Int -> Producer [Elevator] m ()
elevatorP delay = forever $ do
res <- liftIO (try scrapeAllPages)
case res of
Left err -> print (err :: SomeException)
Right Nothing -> print ("Scraping Bogestra failed" :: Text)
Right (Just evs) -> yield evs
waitSeconds delay
disruptions :: MonadIO m => Store -> m (Pipe [Elevator] (PersistedEvent (DisruptionEvent 'Bogestra)) IO ())
disruptions store = do
disEvs <- liftIO (readStream store)
return $ P.map (fmap $ liftA2 (,) eId eIsDisrupted)
>-> monitorP bogDisruptionMonitor (replayMkSeed bogDisruptionMonitor . fmap evPayload $ disEvs)
>-> eventStoreP store
>-> P.concat
>-> eachBefore disEvs
facilities :: MonadIO m => Store -> m (Pipe [Elevator] (PersistedEvent (FacilityEvent 'Bogestra)) IO ())
facilities store = do
fEvs <- liftIO (readStream store)
return $ monitorP bogFacilityMonitor (replayMkSeed bogFacilityMonitor . fmap evPayload $ fEvs)
>-> eventStoreP store
>-> P.concat
>-> eachBefore fEvs
| null | https://raw.githubusercontent.com/Akii/elescore/216540f9891f8317179abd8dde215d7cd7deb448/src/Elescore/Integration/Bogestra.hs | haskell | # LANGUAGE DataKinds #
module Elescore.Integration.Bogestra
( runBogSource
) where
import ClassyPrelude
import Pipes
import Pipes.Concurrent
import qualified Pipes.Prelude as P
import Database.SimpleEventStore
import Elescore.Integration.Bogestra.Client
import Elescore.Integration.Bogestra.Monitor
import Elescore.Integration.Bogestra.Types
import Elescore.Integration.Common.Monitoring
import Elescore.Integration.Common.Types
import Elescore.Integration.Common.Utils
runBogSource :: MonadIO m => Store -> m (Source 'Bogestra)
runBogSource store = do
(out1, in1) <- liftIO (spawn unbounded)
(out2, in2) <- liftIO (spawn unbounded)
void . liftIO . forkIO $ runEffect $ elevatorP 900 >-> toOutput (out1 <> out2)
dP <- disruptions store
fP <- facilities store
oEvs <- liftIO (readStream store)
(out4, in4) <- liftIO (spawn unbounded)
(out5, in5) <- liftIO (spawn unbounded)
(out6, in6) <- liftIO (spawn unbounded)
liftIO $ do
void . forkIO . runEffect $ fromInput in1 >-> dP >-> toOutput out4
void . forkIO . runEffect $ fromInput in2 >-> fP >-> toOutput out5
runEffect (each oEvs >-> toOutput out6)
return Source
{ disruptionEvents = in4
, facilityEvents = in5
, objectEvents = in6
}
where
elevatorP :: MonadIO m => Int -> Producer [Elevator] m ()
elevatorP delay = forever $ do
res <- liftIO (try scrapeAllPages)
case res of
Left err -> print (err :: SomeException)
Right Nothing -> print ("Scraping Bogestra failed" :: Text)
Right (Just evs) -> yield evs
waitSeconds delay
disruptions :: MonadIO m => Store -> m (Pipe [Elevator] (PersistedEvent (DisruptionEvent 'Bogestra)) IO ())
disruptions store = do
disEvs <- liftIO (readStream store)
return $ P.map (fmap $ liftA2 (,) eId eIsDisrupted)
>-> monitorP bogDisruptionMonitor (replayMkSeed bogDisruptionMonitor . fmap evPayload $ disEvs)
>-> eventStoreP store
>-> P.concat
>-> eachBefore disEvs
facilities :: MonadIO m => Store -> m (Pipe [Elevator] (PersistedEvent (FacilityEvent 'Bogestra)) IO ())
facilities store = do
fEvs <- liftIO (readStream store)
return $ monitorP bogFacilityMonitor (replayMkSeed bogFacilityMonitor . fmap evPayload $ fEvs)
>-> eventStoreP store
>-> P.concat
>-> eachBefore fEvs
|
|
a63cab6b315bbd3bbe92571ec87350fd773e23c4e35745a261dc007598771838 | mtravers/goddinpotty | templating_test.clj | (ns goddinpotty.templating-test
(:require [goddinpotty.templating :refer :all]
[goddinpotty.database :as db]
[org.parkerici.multitool.core :as u]
[clojure.test :refer :all]))
;;; → utils
(defn structure-contains?
[elt struct]
(u/walk-find #(= % elt) struct))
(deftest formatted-page-title-test
(let [id 23
page
'{:include? true,
:title "__On Purpose__",
:refs #{},
:edit-time #inst "2021-05-31T03:47:57.271-00:00"
:page? true,
:id id ,
:depth 4,
:heading -1}
hiccup (block-page-hiccup id {id page} "output") ]
(is (structure-contains? [:h1 [:i "On Purpose"]] hiccup))))
| null | https://raw.githubusercontent.com/mtravers/goddinpotty/b0b7f4fe5781a56b226d151d11a25130224bf093/test/goddinpotty/templating_test.clj | clojure | → utils | (ns goddinpotty.templating-test
(:require [goddinpotty.templating :refer :all]
[goddinpotty.database :as db]
[org.parkerici.multitool.core :as u]
[clojure.test :refer :all]))
(defn structure-contains?
[elt struct]
(u/walk-find #(= % elt) struct))
(deftest formatted-page-title-test
(let [id 23
page
'{:include? true,
:title "__On Purpose__",
:refs #{},
:edit-time #inst "2021-05-31T03:47:57.271-00:00"
:page? true,
:id id ,
:depth 4,
:heading -1}
hiccup (block-page-hiccup id {id page} "output") ]
(is (structure-contains? [:h1 [:i "On Purpose"]] hiccup))))
|
f272ebbfed8dbc584b6b559cfa7fe13715483d471b93f180e984dfd2df6f4789 | dariusf/ppx_polyprint | main.ml |
open Config
let rec fact n =
if n = 0 then 1 else n * fact (n - 1)
[@@tracerec Recursive]
let rec roll n =
match n with
| 0 -> ()
| 3 -> ignore @@ fact 5; roll 2
| n -> roll (n - 1)
[@@tracerec Recursive]
let rec fib n =
if n <= 1 then 1 else fib (n - 1) + fib (n - 2)
[@@tracerec Minimal]
let () =
roll 5;
ignore @@ fib 5
| null | https://raw.githubusercontent.com/dariusf/ppx_polyprint/6cd87e948a27888d251f851424ad8bd5545989ad/examples/configs/src/main.ml | ocaml |
open Config
let rec fact n =
if n = 0 then 1 else n * fact (n - 1)
[@@tracerec Recursive]
let rec roll n =
match n with
| 0 -> ()
| 3 -> ignore @@ fact 5; roll 2
| n -> roll (n - 1)
[@@tracerec Recursive]
let rec fib n =
if n <= 1 then 1 else fib (n - 1) + fib (n - 2)
[@@tracerec Minimal]
let () =
roll 5;
ignore @@ fib 5
|
|
cfabee0661cf76b817abc7b6ee786f397470aba307ec6640f2fa8733f44adf37 | emqx/emqx | emqx_gateway_cm.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc The Gateway Channel Manager
%%
%% For a certain type of protocol, this is a single instance of the manager.
%% It means that no matter how many instances of the stomp gateway are created,
%% they all share a single this Connection-Manager
-module(emqx_gateway_cm).
-behaviour(gen_server).
-include("include/emqx_gateway.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("snabbkaffe/include/snabbkaffe.hrl").
%% APIs
-export([start_link/1]).
-export([
open_session/5,
open_session/6,
kick_session/2,
kick_session/3,
takeover_session/2,
register_channel/4,
unregister_channel/2,
insert_channel_info/4,
lookup_by_clientid/2,
set_chan_info/3,
set_chan_info/4,
get_chan_info/2,
get_chan_info/3,
set_chan_stats/3,
set_chan_stats/4,
get_chan_stats/2,
get_chan_stats/3,
connection_closed/2
]).
-export([
call/3,
call/4,
cast/3
]).
-export([
with_channel/3,
lookup_channels/2
]).
%% Internal funcs for getting tabname by GatewayId
-export([cmtabs/1, tabname/2]).
%% gen_server callbacks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
%% RPC targets
-export([
do_lookup_by_clientid/2,
do_get_chan_info/3,
do_set_chan_info/4,
do_get_chan_stats/3,
do_set_chan_stats/4,
do_kick_session/4,
do_takeover_session/3,
do_get_chann_conn_mod/3,
do_call/4,
do_call/5,
do_cast/4
]).
-export_type([gateway_name/0]).
-record(state, {
%% Gateway Name
gwname :: gateway_name(),
ClientId Locker for CM
locker :: pid(),
ClientId Registry server
registry :: pid(),
chan_pmon :: emqx_pmon:pmon()
}).
-type option() :: {gwname, gateway_name()}.
-type options() :: list(option()).
-define(T_KICK, 5000).
-define(T_GET_INFO, 5000).
-define(T_TAKEOVER, 15000).
-define(DEFAULT_BATCH_SIZE, 10000).
-elvis([{elvis_style, invalid_dynamic_call, disable}]).
%%--------------------------------------------------------------------
%% APIs
%%--------------------------------------------------------------------
-spec start_link(options()) -> {ok, pid()} | ignore | {error, any()}.
start_link(Options) ->
GwName = proplists:get_value(gwname, Options),
gen_server:start_link({local, procname(GwName)}, ?MODULE, Options, []).
procname(GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_cm'])).
-spec cmtabs(GwName :: gateway_name()) ->
{ChanTab :: atom(), ConnTab :: atom(), ChannInfoTab :: atom()}.
cmtabs(GwName) ->
Record : { ClientId , Pid }
{
tabname(chan, GwName),
Record : { { ClientId , Pid } , ConnMod }
tabname(conn, GwName),
Record : { { ClientId , Pid } , Info , Stats }
tabname(info, GwName)
}.
tabname(chan, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel']));
tabname(conn, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel_conn']));
tabname(info, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel_info'])).
lockername(GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_locker'])).
-spec register_channel(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:conninfo()
) -> ok.
register_channel(GwName, ClientId, ChanPid, #{conn_mod := ConnMod}) when is_pid(ChanPid) ->
Chan = {ClientId, ChanPid},
true = ets:insert(tabname(chan, GwName), Chan),
true = ets:insert(tabname(conn, GwName), {Chan, ConnMod}),
ok = emqx_gateway_cm_registry:register_channel(GwName, Chan),
cast(procname(GwName), {registered, Chan}).
%% @doc Unregister a channel.
-spec unregister_channel(gateway_name(), emqx_types:clientid()) -> ok.
unregister_channel(GwName, ClientId) when is_binary(ClientId) ->
true = do_unregister_channel(GwName, {ClientId, self()}, cmtabs(GwName)),
ok.
%% @doc Insert/Update the channel info and stats
-spec insert_channel_info(
gateway_name(),
emqx_types:clientid(),
emqx_types:infos(),
emqx_types:stats()
) -> ok.
insert_channel_info(GwName, ClientId, Info, Stats) ->
Chan = {ClientId, self()},
true = ets:insert(tabname(info, GwName), {Chan, Info, Stats}),
ok.
%% @doc Get info of a channel.
-spec get_chan_info(gateway_name(), emqx_types:clientid()) ->
emqx_types:infos() | undefined.
get_chan_info(GwName, ClientId) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
get_chan_info(GwName, ClientId, ChanPid)
end
).
-spec do_lookup_by_clientid(gateway_name(), emqx_types:clientid()) -> [pid()].
do_lookup_by_clientid(GwName, ClientId) ->
ChanTab = emqx_gateway_cm:tabname(chan, GwName),
[Pid || {_, Pid} <- ets:lookup(ChanTab, ClientId)].
-spec do_get_chan_info(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:infos() | undefined.
do_get_chan_info(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
Info = ets:lookup_element(tabname(info, GwName), Chan, 2),
Info#{node => node()}
catch
error:badarg -> undefined
end.
-spec get_chan_info(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:infos() | undefined.
get_chan_info(GwName, ClientId, ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:get_chan_info(GwName, ClientId, ChanPid)
).
-spec lookup_by_clientid(gateway_name(), emqx_types:clientid()) -> [pid()].
lookup_by_clientid(GwName, ClientId) ->
Nodes = mria_mnesia:running_nodes(),
case
emqx_gateway_cm_proto_v1:lookup_by_clientid(
Nodes, GwName, ClientId
)
of
{Pids, []} ->
lists:append(Pids);
{_, _BadNodes} ->
error(badrpc)
end.
%% @doc Update infos of the channel.
-spec set_chan_info(
gateway_name(),
emqx_types:clientid(),
emqx_types:infos()
) -> boolean().
set_chan_info(GwName, ClientId, Infos) ->
set_chan_info(GwName, ClientId, self(), Infos).
-spec do_set_chan_info(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:infos()
) -> boolean().
do_set_chan_info(GwName, ClientId, ChanPid, Infos) ->
Chan = {ClientId, ChanPid},
try
ets:update_element(tabname(info, GwName), Chan, {2, Infos})
catch
error:badarg -> false
end.
-spec set_chan_info(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:infos()
) -> boolean().
set_chan_info(GwName, ClientId, ChanPid, Infos) ->
wrap_rpc(emqx_gateway_cm_proto_v1:set_chan_info(GwName, ClientId, ChanPid, Infos)).
%% @doc Get channel's stats.
-spec get_chan_stats(gateway_name(), emqx_types:clientid()) ->
emqx_types:stats() | undefined.
get_chan_stats(GwName, ClientId) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
get_chan_stats(GwName, ClientId, ChanPid)
end
).
-spec do_get_chan_stats(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:stats() | undefined.
do_get_chan_stats(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
ets:lookup_element(tabname(info, GwName), Chan, 3)
catch
error:badarg -> undefined
end.
-spec get_chan_stats(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:stats() | undefined.
get_chan_stats(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:get_chan_stats(GwName, ClientId, ChanPid)).
-spec set_chan_stats(
gateway_name(),
emqx_types:clientid(),
emqx_types:stats()
) -> boolean().
set_chan_stats(GwName, ClientId, Stats) ->
set_chan_stats(GwName, ClientId, self(), Stats).
-spec do_set_chan_stats(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:stats()
) -> boolean().
do_set_chan_stats(GwName, ClientId, ChanPid, Stats) ->
Chan = {ClientId, ChanPid},
try
ets:update_element(tabname(info, GwName), Chan, {3, Stats})
catch
error:badarg -> false
end.
-spec set_chan_stats(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:stats()
) -> boolean().
set_chan_stats(GwName, ClientId, ChanPid, Stats) ->
wrap_rpc(emqx_gateway_cm_proto_v1:set_chan_stats(GwName, ClientId, ChanPid, Stats)).
-spec connection_closed(gateway_name(), emqx_types:clientid()) -> true.
connection_closed(GwName, ClientId) ->
%% XXX: Why we need to delete conn_mod tab ???
Chan = {ClientId, self()},
ets:delete_object(tabname(conn, GwName), Chan).
-spec open_session(
GwName :: gateway_name(),
CleanStart :: boolean(),
ClientInfo :: emqx_types:clientinfo(),
ConnInfo :: emqx_types:conninfo(),
CreateSessionFun :: fun(
(
emqx_types:clientinfo(),
emqx_types:conninfo()
) -> Session
)
) ->
{ok, #{
session := Session,
present := boolean(),
pendings => list()
}}
| {error, any()}.
open_session(GwName, CleanStart, ClientInfo, ConnInfo, CreateSessionFun) ->
open_session(GwName, CleanStart, ClientInfo, ConnInfo, CreateSessionFun, emqx_session).
open_session(GwName, true = _CleanStart, ClientInfo, ConnInfo, CreateSessionFun, SessionMod) ->
Self = self(),
ClientId = maps:get(clientid, ClientInfo),
Fun = fun(_) ->
_ = discard_session(GwName, ClientId),
Session = create_session(
GwName,
ClientInfo,
ConnInfo,
CreateSessionFun,
SessionMod
),
register_channel(GwName, ClientId, Self, ConnInfo),
{ok, #{session => Session, present => false}}
end,
locker_trans(GwName, ClientId, Fun);
open_session(
GwName,
false = _CleanStart,
ClientInfo = #{clientid := ClientId},
ConnInfo,
CreateSessionFun,
SessionMod
) ->
Self = self(),
ResumeStart =
fun(_) ->
CreateSess =
fun() ->
Session = create_session(
GwName,
ClientInfo,
ConnInfo,
CreateSessionFun,
SessionMod
),
register_channel(
GwName, ClientId, Self, ConnInfo
),
{ok, #{session => Session, present => false}}
end,
case takeover_session(GwName, ClientId) of
{ok, ConnMod, ChanPid, Session} ->
ok = emqx_session:resume(ClientInfo, Session),
case request_stepdown({takeover, 'end'}, ConnMod, ChanPid) of
{ok, Pendings} ->
register_channel(
GwName, ClientId, Self, ConnInfo
),
{ok, #{
session => Session,
present => true,
pendings => Pendings
}};
{error, _} ->
CreateSess()
end;
{error, _Reason} ->
CreateSess()
end
end,
locker_trans(GwName, ClientId, ResumeStart).
@private
create_session(GwName, ClientInfo, ConnInfo, CreateSessionFun, SessionMod) ->
try
Session = emqx_gateway_utils:apply(
CreateSessionFun,
[ClientInfo, ConnInfo]
),
ok = emqx_gateway_metrics:inc(GwName, 'session.created'),
SessionInfo =
case
is_tuple(Session) andalso
element(1, Session) == session
of
true ->
SessionMod:info(Session);
_ ->
case is_map(Session) of
false ->
throw(session_structure_should_be_map);
_ ->
Session
end
end,
ok = emqx_hooks:run('session.created', [ClientInfo, SessionInfo]),
Session
catch
Class:Reason:Stk ->
?SLOG(error, #{
msg => "failed_create_session",
clientid => maps:get(clientid, ClientInfo, undefined),
username => maps:get(username, ClientInfo, undefined),
reason => {Class, Reason},
stacktrace => Stk
}),
throw(Reason)
end.
%% @doc Try to takeover a session.
-spec takeover_session(gateway_name(), emqx_types:clientid()) ->
{error, term()}
| {ok, atom(), pid(), emqx_session:session()}.
takeover_session(GwName, ClientId) ->
case lookup_channels(GwName, ClientId) of
[] ->
{error, not_found};
[ChanPid] ->
do_takeover_session(GwName, ClientId, ChanPid);
ChanPids ->
[ChanPid | StalePids] = lists:reverse(ChanPids),
?SLOG(warning, #{
msg => "more_than_one_channel_found",
chan_pids => ChanPids
}),
lists:foreach(
fun(StalePid) ->
catch discard_session(GwName, ClientId, StalePid)
end,
StalePids
),
do_takeover_session(GwName, ClientId, ChanPid)
end.
do_takeover_session(GwName, ClientId, ChanPid) when node(ChanPid) == node() ->
case get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined ->
{error, not_found};
ConnMod when is_atom(ConnMod) ->
case request_stepdown({takeover, 'begin'}, ConnMod, ChanPid) of
{ok, Session} ->
{ok, ConnMod, ChanPid, Session};
{error, Reason} ->
{error, Reason}
end
end;
do_takeover_session(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:takeover_session(GwName, ClientId, ChanPid)).
@doc Discard all the sessions identified by the ClientId .
-spec discard_session(GwName :: gateway_name(), binary()) -> ok | {error, not_found}.
discard_session(GwName, ClientId) when is_binary(ClientId) ->
case lookup_channels(GwName, ClientId) of
[] -> {error, not_found};
ChanPids -> lists:foreach(fun(Pid) -> discard_session(GwName, ClientId, Pid) end, ChanPids)
end.
discard_session(GwName, ClientId, ChanPid) ->
kick_session(GwName, discard, ClientId, ChanPid).
-spec kick_session(gateway_name(), emqx_types:clientid()) -> ok | {error, not_found}.
kick_session(GwName, ClientId) ->
case lookup_channels(GwName, ClientId) of
[] ->
{error, not_found};
ChanPids ->
ChanPids > 1 andalso
begin
?SLOG(
warning,
#{
msg => "more_than_one_channel_found",
chan_pids => ChanPids
},
#{clientid => ClientId}
)
end,
lists:foreach(
fun(Pid) ->
_ = kick_session(GwName, ClientId, Pid)
end,
ChanPids
)
end.
kick_session(GwName, ClientId, ChanPid) ->
kick_session(GwName, kick, ClientId, ChanPid).
@private This function is shared for session ' kick ' and ' discard ' ( as the first arg Action ) .
kick_session(GwName, Action, ClientId, ChanPid) ->
try
wrap_rpc(emqx_gateway_cm_proto_v1:kick_session(GwName, Action, ClientId, ChanPid))
catch
Error:Reason ->
%% This should mostly be RPC failures.
%% However, if the node is still running the old version
code ( prior to emqx app 4.3.10 ) some of the RPC handler
%% exceptions may get propagated to a new version node
?SLOG(
error,
#{
msg => "failed_to_kick_session_on_remote_node",
node => node(ChanPid),
action => Action,
error => Error,
reason => Reason
},
#{clientid => ClientId}
)
end.
-spec do_kick_session(
gateway_name(),
kick | discard,
emqx_types:clientid(),
pid()
) -> ok.
do_kick_session(GwName, Action, ClientId, ChanPid) ->
case get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined ->
ok;
ConnMod when is_atom(ConnMod) ->
ok = request_stepdown(Action, ConnMod, ChanPid)
end.
@private call a local stale session to execute an Action .
%% If failed to response (e.g. timeout) force a kill.
%% Keeping the stale pid around, or returning error or raise an exception
%% benefits nobody.
-spec request_stepdown(Action, module(), pid()) ->
ok
| {ok, emqx_session:session() | list(emqx_type:deliver())}
| {error, term()}
when
Action :: kick | discard | {takeover, 'begin'} | {takeover, 'end'}.
request_stepdown(Action, ConnMod, Pid) ->
Timeout =
case Action == kick orelse Action == discard of
true -> ?T_KICK;
_ -> ?T_TAKEOVER
end,
Return =
%% this is essentailly a gen_server:call implemented in emqx_connection
%% and emqx_ws_connection.
the handle_call is implemented in emqx_channel
try apply(ConnMod, call, [Pid, Action, Timeout]) of
ok -> ok;
Reply -> {ok, Reply}
catch
% emqx_ws_connection: call
_:noproc ->
ok = ?tp(debug, "session_already_gone", #{pid => Pid, action => Action}),
{error, noproc};
% emqx_connection: gen_server:call
_:{noproc, _} ->
ok = ?tp(debug, "session_already_gone", #{pid => Pid, action => Action}),
{error, noproc};
_:Reason = {shutdown, _} ->
ok = ?tp(debug, "session_already_shutdown", #{pid => Pid, action => Action}),
{error, Reason};
_:Reason = {{shutdown, _}, _} ->
ok = ?tp(debug, "session_already_shutdown", #{pid => Pid, action => Action}),
{error, Reason};
_:{timeout, {gen_server, call, _}} ->
?tp(
warning,
"session_stepdown_request_timeout",
#{
pid => Pid,
action => Action,
stale_channel => stale_channel_info(Pid)
}
),
ok = force_kill(Pid),
{error, timeout};
_:Error:St ->
?tp(
error,
"session_stepdown_request_exception",
#{
pid => Pid,
action => Action,
reason => Error,
stacktrace => St,
stale_channel => stale_channel_info(Pid)
}
),
ok = force_kill(Pid),
{error, Error}
end,
case Action == kick orelse Action == discard of
true -> ok;
_ -> Return
end.
force_kill(Pid) ->
exit(Pid, kill),
ok.
stale_channel_info(Pid) ->
process_info(Pid, [status, message_queue_len, current_stacktrace]).
with_channel(GwName, ClientId, Fun) ->
case lookup_channels(GwName, ClientId) of
[] -> undefined;
[Pid] -> Fun(Pid);
Pids -> Fun(lists:last(Pids))
end.
%% @doc Lookup channels.
-spec lookup_channels(gateway_name(), emqx_types:clientid()) -> list(pid()).
lookup_channels(GwName, ClientId) ->
emqx_gateway_cm_registry:lookup_channels(GwName, ClientId).
-spec do_get_chann_conn_mod(gateway_name(), emqx_types:clientid(), pid()) -> atom().
do_get_chann_conn_mod(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
[ConnMod] = ets:lookup_element(tabname(conn, GwName), Chan, 2),
ConnMod
catch
error:badarg -> undefined
end.
-spec get_chann_conn_mod(gateway_name(), emqx_types:clientid(), pid()) -> atom().
get_chann_conn_mod(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:get_chann_conn_mod(GwName, ClientId, ChanPid)).
-spec call(gateway_name(), emqx_types:clientid(), term()) ->
undefined | term().
call(GwName, ClientId, Req) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:call(GwName, ClientId, ChanPid, Req)
)
end
).
-spec call(gateway_name(), emqx_types:clientid(), term(), timeout()) ->
undefined | term().
call(GwName, ClientId, Req, Timeout) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:call(
GwName, ClientId, ChanPid, Req, Timeout
)
)
end
).
do_call(GwName, ClientId, ChanPid, Req) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:call(ChanPid, Req)
end.
do_call(GwName, ClientId, ChanPid, Req, Timeout) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:call(ChanPid, Req, Timeout)
end.
-spec cast(gateway_name(), emqx_types:clientid(), term()) -> undefined | ok.
cast(GwName, ClientId, Req) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:cast(GwName, ClientId, ChanPid, Req)
)
end
),
ok.
do_cast(GwName, ClientId, ChanPid, Req) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:cast(ChanPid, Req)
end.
%% Locker
locker_trans(_GwName, undefined, Fun) ->
Fun([]);
locker_trans(GwName, ClientId, Fun) ->
Locker = lockername(GwName),
case locker_lock(Locker, ClientId) of
{true, Nodes} ->
try
Fun(Nodes)
after
locker_unlock(Locker, ClientId)
end;
{false, _Nodes} ->
{error, client_id_unavailable}
end.
locker_lock(Locker, ClientId) ->
ekka_locker:acquire(Locker, ClientId, quorum).
locker_unlock(Locker, ClientId) ->
ekka_locker:release(Locker, ClientId, quorum).
@private
wrap_rpc(Ret) ->
case Ret of
{badrpc, Reason} -> throw({badrpc, Reason});
Res -> Res
end.
cast(Name, Msg) ->
gen_server:cast(Name, Msg).
%%--------------------------------------------------------------------
%% gen_server callbacks
%%--------------------------------------------------------------------
init(Options) ->
GwName = proplists:get_value(gwname, Options),
TabOpts = [public, {write_concurrency, true}],
{ChanTab, ConnTab, InfoTab} = cmtabs(GwName),
ok = emqx_tables:new(ChanTab, [bag, {read_concurrency, true} | TabOpts]),
ok = emqx_tables:new(ConnTab, [bag | TabOpts]),
ok = emqx_tables:new(InfoTab, [ordered_set, compressed | TabOpts]),
%% Start link cm-registry process
%% XXX: Should I hang it under a higher level supervisor?
{ok, Registry} = emqx_gateway_cm_registry:start_link(GwName),
%% Start locker process
{ok, Locker} = ekka_locker:start_link(lockername(GwName)),
%% Interval update stats
%% TODO: v0.2
%ok = emqx_stats:update_interval(chan_stats, fun ?MODULE:stats_fun/0),
{ok, #state{
gwname = GwName,
locker = Locker,
registry = Registry,
chan_pmon = emqx_pmon:new()
}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({registered, {ClientId, ChanPid}}, State = #state{chan_pmon = PMon}) ->
PMon1 = emqx_pmon:monitor(ChanPid, ClientId, PMon),
{noreply, State#state{chan_pmon = PMon1}};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(
{'DOWN', _MRef, process, Pid, _Reason},
State = #state{gwname = GwName, chan_pmon = PMon}
) ->
ChanPids = [Pid | emqx_misc:drain_down(?DEFAULT_BATCH_SIZE)],
{Items, PMon1} = emqx_pmon:erase_all(ChanPids, PMon),
CmTabs = cmtabs(GwName),
ok = emqx_pool:async_submit(fun do_unregister_channel_task/3, [Items, GwName, CmTabs]),
{noreply, State#state{chan_pmon = PMon1}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, #state{registry = Registry, locker = Locker}) ->
_ = gen_server:stop(Registry),
_ = ekka_locker:stop(Locker),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
do_unregister_channel_task(Items, GwName, CmTabs) ->
lists:foreach(
fun({ChanPid, ClientId}) ->
do_unregister_channel(GwName, {ClientId, ChanPid}, CmTabs)
end,
Items
).
%%--------------------------------------------------------------------
Internal funcs
%%--------------------------------------------------------------------
do_unregister_channel(GwName, Chan, {ChanTab, ConnTab, InfoTab}) ->
ok = emqx_gateway_cm_registry:unregister_channel(GwName, Chan),
true = ets:delete(ConnTab, Chan),
true = ets:delete(InfoTab, Chan),
ets:delete_object(ChanTab, Chan).
| null | https://raw.githubusercontent.com/emqx/emqx/33b3c4fa9a1a60e4b1574328043100aa93d655cf/apps/emqx_gateway/src/emqx_gateway_cm.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 The Gateway Channel Manager
For a certain type of protocol, this is a single instance of the manager.
It means that no matter how many instances of the stomp gateway are created,
they all share a single this Connection-Manager
APIs
Internal funcs for getting tabname by GatewayId
gen_server callbacks
RPC targets
Gateway Name
--------------------------------------------------------------------
APIs
--------------------------------------------------------------------
@doc Unregister a channel.
@doc Insert/Update the channel info and stats
@doc Get info of a channel.
@doc Update infos of the channel.
@doc Get channel's stats.
XXX: Why we need to delete conn_mod tab ???
@doc Try to takeover a session.
This should mostly be RPC failures.
However, if the node is still running the old version
exceptions may get propagated to a new version node
If failed to response (e.g. timeout) force a kill.
Keeping the stale pid around, or returning error or raise an exception
benefits nobody.
this is essentailly a gen_server:call implemented in emqx_connection
and emqx_ws_connection.
emqx_ws_connection: call
emqx_connection: gen_server:call
@doc Lookup channels.
Locker
--------------------------------------------------------------------
gen_server callbacks
--------------------------------------------------------------------
Start link cm-registry process
XXX: Should I hang it under a higher level supervisor?
Start locker process
Interval update stats
TODO: v0.2
ok = emqx_stats:update_interval(chan_stats, fun ?MODULE:stats_fun/0),
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_gateway_cm).
-behaviour(gen_server).
-include("include/emqx_gateway.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("snabbkaffe/include/snabbkaffe.hrl").
-export([start_link/1]).
-export([
open_session/5,
open_session/6,
kick_session/2,
kick_session/3,
takeover_session/2,
register_channel/4,
unregister_channel/2,
insert_channel_info/4,
lookup_by_clientid/2,
set_chan_info/3,
set_chan_info/4,
get_chan_info/2,
get_chan_info/3,
set_chan_stats/3,
set_chan_stats/4,
get_chan_stats/2,
get_chan_stats/3,
connection_closed/2
]).
-export([
call/3,
call/4,
cast/3
]).
-export([
with_channel/3,
lookup_channels/2
]).
-export([cmtabs/1, tabname/2]).
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-export([
do_lookup_by_clientid/2,
do_get_chan_info/3,
do_set_chan_info/4,
do_get_chan_stats/3,
do_set_chan_stats/4,
do_kick_session/4,
do_takeover_session/3,
do_get_chann_conn_mod/3,
do_call/4,
do_call/5,
do_cast/4
]).
-export_type([gateway_name/0]).
-record(state, {
gwname :: gateway_name(),
ClientId Locker for CM
locker :: pid(),
ClientId Registry server
registry :: pid(),
chan_pmon :: emqx_pmon:pmon()
}).
-type option() :: {gwname, gateway_name()}.
-type options() :: list(option()).
-define(T_KICK, 5000).
-define(T_GET_INFO, 5000).
-define(T_TAKEOVER, 15000).
-define(DEFAULT_BATCH_SIZE, 10000).
-elvis([{elvis_style, invalid_dynamic_call, disable}]).
-spec start_link(options()) -> {ok, pid()} | ignore | {error, any()}.
start_link(Options) ->
GwName = proplists:get_value(gwname, Options),
gen_server:start_link({local, procname(GwName)}, ?MODULE, Options, []).
procname(GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_cm'])).
-spec cmtabs(GwName :: gateway_name()) ->
{ChanTab :: atom(), ConnTab :: atom(), ChannInfoTab :: atom()}.
cmtabs(GwName) ->
Record : { ClientId , Pid }
{
tabname(chan, GwName),
Record : { { ClientId , Pid } , ConnMod }
tabname(conn, GwName),
Record : { { ClientId , Pid } , Info , Stats }
tabname(info, GwName)
}.
tabname(chan, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel']));
tabname(conn, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel_conn']));
tabname(info, GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_channel_info'])).
lockername(GwName) ->
list_to_atom(lists:concat([emqx_gateway_, GwName, '_locker'])).
-spec register_channel(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:conninfo()
) -> ok.
register_channel(GwName, ClientId, ChanPid, #{conn_mod := ConnMod}) when is_pid(ChanPid) ->
Chan = {ClientId, ChanPid},
true = ets:insert(tabname(chan, GwName), Chan),
true = ets:insert(tabname(conn, GwName), {Chan, ConnMod}),
ok = emqx_gateway_cm_registry:register_channel(GwName, Chan),
cast(procname(GwName), {registered, Chan}).
-spec unregister_channel(gateway_name(), emqx_types:clientid()) -> ok.
unregister_channel(GwName, ClientId) when is_binary(ClientId) ->
true = do_unregister_channel(GwName, {ClientId, self()}, cmtabs(GwName)),
ok.
-spec insert_channel_info(
gateway_name(),
emqx_types:clientid(),
emqx_types:infos(),
emqx_types:stats()
) -> ok.
insert_channel_info(GwName, ClientId, Info, Stats) ->
Chan = {ClientId, self()},
true = ets:insert(tabname(info, GwName), {Chan, Info, Stats}),
ok.
-spec get_chan_info(gateway_name(), emqx_types:clientid()) ->
emqx_types:infos() | undefined.
get_chan_info(GwName, ClientId) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
get_chan_info(GwName, ClientId, ChanPid)
end
).
-spec do_lookup_by_clientid(gateway_name(), emqx_types:clientid()) -> [pid()].
do_lookup_by_clientid(GwName, ClientId) ->
ChanTab = emqx_gateway_cm:tabname(chan, GwName),
[Pid || {_, Pid} <- ets:lookup(ChanTab, ClientId)].
-spec do_get_chan_info(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:infos() | undefined.
do_get_chan_info(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
Info = ets:lookup_element(tabname(info, GwName), Chan, 2),
Info#{node => node()}
catch
error:badarg -> undefined
end.
-spec get_chan_info(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:infos() | undefined.
get_chan_info(GwName, ClientId, ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:get_chan_info(GwName, ClientId, ChanPid)
).
-spec lookup_by_clientid(gateway_name(), emqx_types:clientid()) -> [pid()].
lookup_by_clientid(GwName, ClientId) ->
Nodes = mria_mnesia:running_nodes(),
case
emqx_gateway_cm_proto_v1:lookup_by_clientid(
Nodes, GwName, ClientId
)
of
{Pids, []} ->
lists:append(Pids);
{_, _BadNodes} ->
error(badrpc)
end.
-spec set_chan_info(
gateway_name(),
emqx_types:clientid(),
emqx_types:infos()
) -> boolean().
set_chan_info(GwName, ClientId, Infos) ->
set_chan_info(GwName, ClientId, self(), Infos).
-spec do_set_chan_info(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:infos()
) -> boolean().
do_set_chan_info(GwName, ClientId, ChanPid, Infos) ->
Chan = {ClientId, ChanPid},
try
ets:update_element(tabname(info, GwName), Chan, {2, Infos})
catch
error:badarg -> false
end.
-spec set_chan_info(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:infos()
) -> boolean().
set_chan_info(GwName, ClientId, ChanPid, Infos) ->
wrap_rpc(emqx_gateway_cm_proto_v1:set_chan_info(GwName, ClientId, ChanPid, Infos)).
-spec get_chan_stats(gateway_name(), emqx_types:clientid()) ->
emqx_types:stats() | undefined.
get_chan_stats(GwName, ClientId) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
get_chan_stats(GwName, ClientId, ChanPid)
end
).
-spec do_get_chan_stats(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:stats() | undefined.
do_get_chan_stats(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
ets:lookup_element(tabname(info, GwName), Chan, 3)
catch
error:badarg -> undefined
end.
-spec get_chan_stats(gateway_name(), emqx_types:clientid(), pid()) ->
emqx_types:stats() | undefined.
get_chan_stats(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:get_chan_stats(GwName, ClientId, ChanPid)).
-spec set_chan_stats(
gateway_name(),
emqx_types:clientid(),
emqx_types:stats()
) -> boolean().
set_chan_stats(GwName, ClientId, Stats) ->
set_chan_stats(GwName, ClientId, self(), Stats).
-spec do_set_chan_stats(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:stats()
) -> boolean().
do_set_chan_stats(GwName, ClientId, ChanPid, Stats) ->
Chan = {ClientId, ChanPid},
try
ets:update_element(tabname(info, GwName), Chan, {3, Stats})
catch
error:badarg -> false
end.
-spec set_chan_stats(
gateway_name(),
emqx_types:clientid(),
pid(),
emqx_types:stats()
) -> boolean().
set_chan_stats(GwName, ClientId, ChanPid, Stats) ->
wrap_rpc(emqx_gateway_cm_proto_v1:set_chan_stats(GwName, ClientId, ChanPid, Stats)).
-spec connection_closed(gateway_name(), emqx_types:clientid()) -> true.
connection_closed(GwName, ClientId) ->
Chan = {ClientId, self()},
ets:delete_object(tabname(conn, GwName), Chan).
-spec open_session(
GwName :: gateway_name(),
CleanStart :: boolean(),
ClientInfo :: emqx_types:clientinfo(),
ConnInfo :: emqx_types:conninfo(),
CreateSessionFun :: fun(
(
emqx_types:clientinfo(),
emqx_types:conninfo()
) -> Session
)
) ->
{ok, #{
session := Session,
present := boolean(),
pendings => list()
}}
| {error, any()}.
open_session(GwName, CleanStart, ClientInfo, ConnInfo, CreateSessionFun) ->
open_session(GwName, CleanStart, ClientInfo, ConnInfo, CreateSessionFun, emqx_session).
open_session(GwName, true = _CleanStart, ClientInfo, ConnInfo, CreateSessionFun, SessionMod) ->
Self = self(),
ClientId = maps:get(clientid, ClientInfo),
Fun = fun(_) ->
_ = discard_session(GwName, ClientId),
Session = create_session(
GwName,
ClientInfo,
ConnInfo,
CreateSessionFun,
SessionMod
),
register_channel(GwName, ClientId, Self, ConnInfo),
{ok, #{session => Session, present => false}}
end,
locker_trans(GwName, ClientId, Fun);
open_session(
GwName,
false = _CleanStart,
ClientInfo = #{clientid := ClientId},
ConnInfo,
CreateSessionFun,
SessionMod
) ->
Self = self(),
ResumeStart =
fun(_) ->
CreateSess =
fun() ->
Session = create_session(
GwName,
ClientInfo,
ConnInfo,
CreateSessionFun,
SessionMod
),
register_channel(
GwName, ClientId, Self, ConnInfo
),
{ok, #{session => Session, present => false}}
end,
case takeover_session(GwName, ClientId) of
{ok, ConnMod, ChanPid, Session} ->
ok = emqx_session:resume(ClientInfo, Session),
case request_stepdown({takeover, 'end'}, ConnMod, ChanPid) of
{ok, Pendings} ->
register_channel(
GwName, ClientId, Self, ConnInfo
),
{ok, #{
session => Session,
present => true,
pendings => Pendings
}};
{error, _} ->
CreateSess()
end;
{error, _Reason} ->
CreateSess()
end
end,
locker_trans(GwName, ClientId, ResumeStart).
@private
create_session(GwName, ClientInfo, ConnInfo, CreateSessionFun, SessionMod) ->
try
Session = emqx_gateway_utils:apply(
CreateSessionFun,
[ClientInfo, ConnInfo]
),
ok = emqx_gateway_metrics:inc(GwName, 'session.created'),
SessionInfo =
case
is_tuple(Session) andalso
element(1, Session) == session
of
true ->
SessionMod:info(Session);
_ ->
case is_map(Session) of
false ->
throw(session_structure_should_be_map);
_ ->
Session
end
end,
ok = emqx_hooks:run('session.created', [ClientInfo, SessionInfo]),
Session
catch
Class:Reason:Stk ->
?SLOG(error, #{
msg => "failed_create_session",
clientid => maps:get(clientid, ClientInfo, undefined),
username => maps:get(username, ClientInfo, undefined),
reason => {Class, Reason},
stacktrace => Stk
}),
throw(Reason)
end.
-spec takeover_session(gateway_name(), emqx_types:clientid()) ->
{error, term()}
| {ok, atom(), pid(), emqx_session:session()}.
takeover_session(GwName, ClientId) ->
case lookup_channels(GwName, ClientId) of
[] ->
{error, not_found};
[ChanPid] ->
do_takeover_session(GwName, ClientId, ChanPid);
ChanPids ->
[ChanPid | StalePids] = lists:reverse(ChanPids),
?SLOG(warning, #{
msg => "more_than_one_channel_found",
chan_pids => ChanPids
}),
lists:foreach(
fun(StalePid) ->
catch discard_session(GwName, ClientId, StalePid)
end,
StalePids
),
do_takeover_session(GwName, ClientId, ChanPid)
end.
do_takeover_session(GwName, ClientId, ChanPid) when node(ChanPid) == node() ->
case get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined ->
{error, not_found};
ConnMod when is_atom(ConnMod) ->
case request_stepdown({takeover, 'begin'}, ConnMod, ChanPid) of
{ok, Session} ->
{ok, ConnMod, ChanPid, Session};
{error, Reason} ->
{error, Reason}
end
end;
do_takeover_session(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:takeover_session(GwName, ClientId, ChanPid)).
@doc Discard all the sessions identified by the ClientId .
-spec discard_session(GwName :: gateway_name(), binary()) -> ok | {error, not_found}.
discard_session(GwName, ClientId) when is_binary(ClientId) ->
case lookup_channels(GwName, ClientId) of
[] -> {error, not_found};
ChanPids -> lists:foreach(fun(Pid) -> discard_session(GwName, ClientId, Pid) end, ChanPids)
end.
discard_session(GwName, ClientId, ChanPid) ->
kick_session(GwName, discard, ClientId, ChanPid).
-spec kick_session(gateway_name(), emqx_types:clientid()) -> ok | {error, not_found}.
kick_session(GwName, ClientId) ->
case lookup_channels(GwName, ClientId) of
[] ->
{error, not_found};
ChanPids ->
ChanPids > 1 andalso
begin
?SLOG(
warning,
#{
msg => "more_than_one_channel_found",
chan_pids => ChanPids
},
#{clientid => ClientId}
)
end,
lists:foreach(
fun(Pid) ->
_ = kick_session(GwName, ClientId, Pid)
end,
ChanPids
)
end.
kick_session(GwName, ClientId, ChanPid) ->
kick_session(GwName, kick, ClientId, ChanPid).
@private This function is shared for session ' kick ' and ' discard ' ( as the first arg Action ) .
kick_session(GwName, Action, ClientId, ChanPid) ->
try
wrap_rpc(emqx_gateway_cm_proto_v1:kick_session(GwName, Action, ClientId, ChanPid))
catch
Error:Reason ->
code ( prior to emqx app 4.3.10 ) some of the RPC handler
?SLOG(
error,
#{
msg => "failed_to_kick_session_on_remote_node",
node => node(ChanPid),
action => Action,
error => Error,
reason => Reason
},
#{clientid => ClientId}
)
end.
-spec do_kick_session(
gateway_name(),
kick | discard,
emqx_types:clientid(),
pid()
) -> ok.
do_kick_session(GwName, Action, ClientId, ChanPid) ->
case get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined ->
ok;
ConnMod when is_atom(ConnMod) ->
ok = request_stepdown(Action, ConnMod, ChanPid)
end.
@private call a local stale session to execute an Action .
-spec request_stepdown(Action, module(), pid()) ->
ok
| {ok, emqx_session:session() | list(emqx_type:deliver())}
| {error, term()}
when
Action :: kick | discard | {takeover, 'begin'} | {takeover, 'end'}.
request_stepdown(Action, ConnMod, Pid) ->
Timeout =
case Action == kick orelse Action == discard of
true -> ?T_KICK;
_ -> ?T_TAKEOVER
end,
Return =
the handle_call is implemented in emqx_channel
try apply(ConnMod, call, [Pid, Action, Timeout]) of
ok -> ok;
Reply -> {ok, Reply}
catch
_:noproc ->
ok = ?tp(debug, "session_already_gone", #{pid => Pid, action => Action}),
{error, noproc};
_:{noproc, _} ->
ok = ?tp(debug, "session_already_gone", #{pid => Pid, action => Action}),
{error, noproc};
_:Reason = {shutdown, _} ->
ok = ?tp(debug, "session_already_shutdown", #{pid => Pid, action => Action}),
{error, Reason};
_:Reason = {{shutdown, _}, _} ->
ok = ?tp(debug, "session_already_shutdown", #{pid => Pid, action => Action}),
{error, Reason};
_:{timeout, {gen_server, call, _}} ->
?tp(
warning,
"session_stepdown_request_timeout",
#{
pid => Pid,
action => Action,
stale_channel => stale_channel_info(Pid)
}
),
ok = force_kill(Pid),
{error, timeout};
_:Error:St ->
?tp(
error,
"session_stepdown_request_exception",
#{
pid => Pid,
action => Action,
reason => Error,
stacktrace => St,
stale_channel => stale_channel_info(Pid)
}
),
ok = force_kill(Pid),
{error, Error}
end,
case Action == kick orelse Action == discard of
true -> ok;
_ -> Return
end.
force_kill(Pid) ->
exit(Pid, kill),
ok.
stale_channel_info(Pid) ->
process_info(Pid, [status, message_queue_len, current_stacktrace]).
with_channel(GwName, ClientId, Fun) ->
case lookup_channels(GwName, ClientId) of
[] -> undefined;
[Pid] -> Fun(Pid);
Pids -> Fun(lists:last(Pids))
end.
-spec lookup_channels(gateway_name(), emqx_types:clientid()) -> list(pid()).
lookup_channels(GwName, ClientId) ->
emqx_gateway_cm_registry:lookup_channels(GwName, ClientId).
-spec do_get_chann_conn_mod(gateway_name(), emqx_types:clientid(), pid()) -> atom().
do_get_chann_conn_mod(GwName, ClientId, ChanPid) ->
Chan = {ClientId, ChanPid},
try
[ConnMod] = ets:lookup_element(tabname(conn, GwName), Chan, 2),
ConnMod
catch
error:badarg -> undefined
end.
-spec get_chann_conn_mod(gateway_name(), emqx_types:clientid(), pid()) -> atom().
get_chann_conn_mod(GwName, ClientId, ChanPid) ->
wrap_rpc(emqx_gateway_cm_proto_v1:get_chann_conn_mod(GwName, ClientId, ChanPid)).
-spec call(gateway_name(), emqx_types:clientid(), term()) ->
undefined | term().
call(GwName, ClientId, Req) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:call(GwName, ClientId, ChanPid, Req)
)
end
).
-spec call(gateway_name(), emqx_types:clientid(), term(), timeout()) ->
undefined | term().
call(GwName, ClientId, Req, Timeout) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:call(
GwName, ClientId, ChanPid, Req, Timeout
)
)
end
).
do_call(GwName, ClientId, ChanPid, Req) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:call(ChanPid, Req)
end.
do_call(GwName, ClientId, ChanPid, Req, Timeout) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:call(ChanPid, Req, Timeout)
end.
-spec cast(gateway_name(), emqx_types:clientid(), term()) -> undefined | ok.
cast(GwName, ClientId, Req) ->
with_channel(
GwName,
ClientId,
fun(ChanPid) ->
wrap_rpc(
emqx_gateway_cm_proto_v1:cast(GwName, ClientId, ChanPid, Req)
)
end
),
ok.
do_cast(GwName, ClientId, ChanPid, Req) ->
case do_get_chann_conn_mod(GwName, ClientId, ChanPid) of
undefined -> undefined;
ConnMod -> ConnMod:cast(ChanPid, Req)
end.
locker_trans(_GwName, undefined, Fun) ->
Fun([]);
locker_trans(GwName, ClientId, Fun) ->
Locker = lockername(GwName),
case locker_lock(Locker, ClientId) of
{true, Nodes} ->
try
Fun(Nodes)
after
locker_unlock(Locker, ClientId)
end;
{false, _Nodes} ->
{error, client_id_unavailable}
end.
locker_lock(Locker, ClientId) ->
ekka_locker:acquire(Locker, ClientId, quorum).
locker_unlock(Locker, ClientId) ->
ekka_locker:release(Locker, ClientId, quorum).
@private
wrap_rpc(Ret) ->
case Ret of
{badrpc, Reason} -> throw({badrpc, Reason});
Res -> Res
end.
cast(Name, Msg) ->
gen_server:cast(Name, Msg).
init(Options) ->
GwName = proplists:get_value(gwname, Options),
TabOpts = [public, {write_concurrency, true}],
{ChanTab, ConnTab, InfoTab} = cmtabs(GwName),
ok = emqx_tables:new(ChanTab, [bag, {read_concurrency, true} | TabOpts]),
ok = emqx_tables:new(ConnTab, [bag | TabOpts]),
ok = emqx_tables:new(InfoTab, [ordered_set, compressed | TabOpts]),
{ok, Registry} = emqx_gateway_cm_registry:start_link(GwName),
{ok, Locker} = ekka_locker:start_link(lockername(GwName)),
{ok, #state{
gwname = GwName,
locker = Locker,
registry = Registry,
chan_pmon = emqx_pmon:new()
}}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({registered, {ClientId, ChanPid}}, State = #state{chan_pmon = PMon}) ->
PMon1 = emqx_pmon:monitor(ChanPid, ClientId, PMon),
{noreply, State#state{chan_pmon = PMon1}};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(
{'DOWN', _MRef, process, Pid, _Reason},
State = #state{gwname = GwName, chan_pmon = PMon}
) ->
ChanPids = [Pid | emqx_misc:drain_down(?DEFAULT_BATCH_SIZE)],
{Items, PMon1} = emqx_pmon:erase_all(ChanPids, PMon),
CmTabs = cmtabs(GwName),
ok = emqx_pool:async_submit(fun do_unregister_channel_task/3, [Items, GwName, CmTabs]),
{noreply, State#state{chan_pmon = PMon1}};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, #state{registry = Registry, locker = Locker}) ->
_ = gen_server:stop(Registry),
_ = ekka_locker:stop(Locker),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
do_unregister_channel_task(Items, GwName, CmTabs) ->
lists:foreach(
fun({ChanPid, ClientId}) ->
do_unregister_channel(GwName, {ClientId, ChanPid}, CmTabs)
end,
Items
).
Internal funcs
do_unregister_channel(GwName, Chan, {ChanTab, ConnTab, InfoTab}) ->
ok = emqx_gateway_cm_registry:unregister_channel(GwName, Chan),
true = ets:delete(ConnTab, Chan),
true = ets:delete(InfoTab, Chan),
ets:delete_object(ChanTab, Chan).
|
865419ade898e38c4976cbffd3c069bfa6ea50672d70cd45b0096cce947bd202 | cky/guile | curried-definitions.scm | Copyright ( C ) 2010 , 2013 Free Software Foundation , Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (ice-9 curried-definitions)
#:replace ((cdefine . define)
(cdefine* . define*)
define-public
define*-public))
(define-syntax cdefine
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine head
(lambda rest body body* ...)))
((_ name val)
(define name val))))
(define-syntax cdefine*
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine* head
(lambda* rest body body* ...)))
((_ name val)
(define* name val))))
(define-syntax define-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define-public head
(lambda rest body body* ...)))
((_ name val)
(begin
(define name val)
(export name)))))
(define-syntax define*-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define*-public head
(lambda* rest body body* ...)))
((_ name val)
(begin
(define* name val)
(export name)))))
| null | https://raw.githubusercontent.com/cky/guile/89ce9fb31b00f1f243fe6f2450db50372cc0b86d/module/ice-9/curried-definitions.scm | scheme |
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software | Copyright ( C ) 2010 , 2013 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (ice-9 curried-definitions)
#:replace ((cdefine . define)
(cdefine* . define*)
define-public
define*-public))
(define-syntax cdefine
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine head
(lambda rest body body* ...)))
((_ name val)
(define name val))))
(define-syntax cdefine*
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine* head
(lambda* rest body body* ...)))
((_ name val)
(define* name val))))
(define-syntax define-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define-public head
(lambda rest body body* ...)))
((_ name val)
(begin
(define name val)
(export name)))))
(define-syntax define*-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define*-public head
(lambda* rest body body* ...)))
((_ name val)
(begin
(define* name val)
(export name)))))
|
7d02f4e9d3e296df8fa9efee1a381348c97f9afeb0da6e4a86cfad297e57c290 | fortytools/holumbus | IndexM.hs | -- ----------------------------------------------------------------------------
|
Module : . Build . Crawl
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Indexer functions for the monadic index class
Module : Holumbus.Build.Crawl
Copyright : Copyright (C) 2008 Sebastian M. Schlatt
License : MIT
Maintainer : Sebastian M. Schlatt ()
Stability : experimental
Portability: portable
Version : 0.1
Indexer functions for the monadic index class
-}
-- -----------------------------------------------------------------------------
{-# OPTIONS -fglasgow-exts #-}
-- -----------------------------------------------------------------------------
module Holumbus.Build.IndexM
(
-- * Building indexes
buildIndex
-- * Indexer Configuration
, IndexerConfig (..)
, ContextConfig (..)
, mergeIndexerConfigs
)
where
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
-- import Control.Exception
import Control.Monad
import Holumbus.Build.Config
import Holumbus.Control.MapReduce.ParallelWithClassPersistent
import Holumbus.Index.Common
import Holumbus.Utility
import System.Time
import Text.XML.HXT.Arrow hiding (getXPathTrees) -- import all stuff for parsing, validating, and transforming XML
import Text.XML.HXT.Arrow.XPathSimple --(getXPathTrees)
-- -----------------------------------------------------------------------------
buildIndex :: (HolDocuments d a, HolIndex i, HolCache c) =>
Int -- ^ Number of parallel threads for MapReduce
-> Int -- ^ TraceLevel for Arrows
-> d a -- ^ List of input Data
-> IndexerConfig -- ^ Configuration for the Indexing process
^ An empty HolIndex . This is used to determine which kind of index to use .
-> Maybe c
^ returns a HolIndex
buildIndex workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
-- assert ((sizeWords emptyIndex) == 0)
(mapReduce
workerThreads
(( fromMaybe "/tmp/" (ic_tmpPath idxConfig)) ++ "MapReduce.db")
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tmpPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
-- | The MAP function in a MapReduce computation for building indexes.
The first three parameters have to be passed to the function to receive
-- a function with a valid MapReduce-map signature.
--
-- The function optionally outputs some debug information and then starts
-- the processing of a file by passing it together with the configuration
-- for different contexts to the @processDocument@ function where the file
-- is read and then the interesting parts configured in the
-- context configurations are extracted.
computeOccurrences :: HolCache c =>
Int -> Bool -> [ContextConfig] -> Attributes -> Maybe c
-> DocId -> String -> IO [((Context, Word), Occurrences)]
computeOccurrences traceLevel fromTmp contextConfigs attrs cache docId theUri
= do
clt <- getClockTime
cat <- toCalendarTime clt
res <- runX ( setTraceLevel traceLevel
>>> traceMsg 1 ((calendarTimeToString cat) ++ " - indexing document: "
++ show docId ++ " -> "
++ show theUri)
>>> processDocument traceLevel attrs' contextConfigs cache docId theUri
-- >>> arr (\ (c, w, d, p) -> (c, (w, d, p)))
>>> strictA
)
return $ buildPositions res
where
attrs' = if fromTmp then addEntries standardReadTmpDocumentAttributes attrs else attrs
buildPositions :: [(Context, Word, DocId, Position)] -> [((Context, Word), Occurrences)]
buildPositions l = M.foldWithKey (\(c,w,d) ps acc -> ((c,w),IM.singleton d ps) : acc) [] $
foldl (\m (c,w,d,p) -> M.insertWith IS.union (c,w,d) (IS.singleton p) m) M.empty l
-- | The REDUCE function in a MapReduce computation for building indexes .
-- Even though there might be faster ways to build an index , this function
-- works with completely on the HolIndex class functions . So it is possible
-- to use the Indexer with different Index implementations .
insertPositions : : ( HolIndex i ) = > i - > String - > [ ( String , String , DocId , Position ) ] - > IO ( Maybe i )
insertPositions idx _ l =
return $ ! Just ( foldl ' theFunc idx l )
where
theFunc i ( _ , " " , _ , _ ) = i -- TODO Filter but make sure that phrase searching is still possible
theFunc i ( context , word , docId , pos ) = insertPosition context word docId pos i
-- | The REDUCE function in a MapReduce computation for building indexes.
-- Even though there might be faster ways to build an index, this function
-- works with completely on the HolIndex class functions. So it is possible
-- to use the Indexer with different Index implementations.
insertPositions :: (HolIndex i) => i -> String -> [(String, String, DocId, Position)] -> IO (Maybe i)
insertPositions idx _ l =
return $! Just (foldl' theFunc idx l)
where
theFunc i (_, "", _ , _) = i -- TODO Filter but make sure that phrase searching is still possible
theFunc i (context, word, docId, pos) = insertPosition context word docId pos i
-}
-- -----------------------------------------------------------------------------
-- | Downloads a document and calls the function to process the data for the
-- different contexts of the index
processDocument :: HolCache c =>
Int
-> Attributes
-> [ContextConfig]
-> Maybe c
-> DocId
-> URI
-> IOSLA (XIOState s) b (Context, Word, DocId, Position)
processDocument traceLevel attrs ccs cache docId theUri =
withTraceLevel (traceLevel - traceOffset) (readDocument attrs theUri)
>>> (catA $ map (processContext cache docId) ccs ) -- process all context configurations
-- | Process a Context. Applies the given context to extract information from
-- the XmlTree that is passed in the arrow.
processContext ::
( HolCache c) =>
Maybe c
-> DocId
-> ContextConfig
-> IOSLA (XIOState s) XmlTree (Context, Word, DocId, Position)
processContext cache docId cc =
( cc_preFilter cc ) -- convert XmlTree
> > > listA (
getXPathTrees ( cc_XPath cc ) -- extract interesting parts
> > > deep isText -- Search deep for text nodes
> > > getText
)
> > > arr concat -- convert text nodes into strings
> > > ( cc_fTokenize cc ) -- apply tokenizer function
> > > arr ( filter ( \w - > w /= " " ) ) -- filter empty words
> > > perform ( ( const $ ( isJust cache ) & & ( cc_addToCache cc ) ) -- write cache data if configured
` guardsP `
( arr unwords > > > arrIO ( putDocText ( fromJust cache ) ( cc_name cc ) docId ) )
)
> > > arr ( zip [ 1 .. ] ) -- number words
> > > arr ( filter ( \(_,s ) - > not ( ( cc_fIsStopWord cc ) s ) ) ) -- remove stop words
> > > arrL ( map ( \(p , w ) - > ( cc_name cc , w , docId , p ) ) ) -- make a list of result tupels
> > > strictA -- force strict evaluation
processContext cache docId cc =
(cc_preFilter cc) -- convert XmlTree
>>> listA (
getXPathTrees (cc_XPath cc) -- extract interesting parts
>>> deep isText -- Search deep for text nodes
>>> getText
)
>>> arr concat -- convert text nodes into strings
>>> arr (cc_fTokenize cc) -- apply tokenizer function
>>> arr (filter (\w -> w /= "")) -- filter empty words
>>> perform ( (const $ (isJust cache) && (cc_addToCache cc)) -- write cache data if configured
`guardsP`
( arr unwords >>> arrIO ( putDocText (fromJust cache) (cc_name cc) docId))
)
>>> arr (zip [1..]) -- number words
>>> arr (filter (\(_,s) -> not ((cc_fIsStopWord cc) s))) -- remove stop words
>>> arrL (map (\(p, w) -> (cc_name cc, w, docId, p) )) -- make a list of result tupels
>>> strictA -- force strict evaluation
-}
processContext cache docId cc
= cc_preFilter cc -- convert XmlTree
>>>
fromLA extractWords
>>>
( if ( isJust cache
&&
cc_addToCache cc
)
then perform (arrIO storeInCache)
else this
)
>>>
arrL genWordList
>>>
strictA
where
extractWords :: LA XmlTree [String]
extractWords
= listA
( xshow ( getXPathTrees (cc_XPath cc) -- extract interesting parts
>>>
getTexts
)
>>>
arrL ( filter (not . null) . cc_fTokenize cc )
)
genWordList :: [String] -> [(Context, Word, DocId, Position)]
genWordList
= zip [1..] -- number words
>>> -- arrow for pure functions
filter (not . (cc_fIsStopWord cc) . snd) -- delete boring words
>>>
map ( \ (p, w) -> (cc_name cc, w, docId, p) ) -- attach context and docId
storeInCache s
= let t = unwords s in
if t /= "" then putDocText (fromJust cache) (cc_name cc) docId t
else return()
getTexts :: LA XmlTree XmlTree
getTexts -- select all text nodes
= choiceA
[ isElem :-> ( space -- substitute tags by a single space
<+> -- so tags act as word delimiter
(getChildren >>> getTexts)
<+>
space
) -- tags are interpreted as word delimiter
, isText :-> this -- take the text nodes
, this :-> none -- ignore anything else
]
where
space = txt " "
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/searchengine/source/Holumbus/Build/IndexM.hs | haskell | ----------------------------------------------------------------------------
-----------------------------------------------------------------------------
# OPTIONS -fglasgow-exts #
-----------------------------------------------------------------------------
* Building indexes
* Indexer Configuration
import Control.Exception
import all stuff for parsing, validating, and transforming XML
(getXPathTrees)
-----------------------------------------------------------------------------
^ Number of parallel threads for MapReduce
^ TraceLevel for Arrows
^ List of input Data
^ Configuration for the Indexing process
assert ((sizeWords emptyIndex) == 0)
| The MAP function in a MapReduce computation for building indexes.
a function with a valid MapReduce-map signature.
The function optionally outputs some debug information and then starts
the processing of a file by passing it together with the configuration
for different contexts to the @processDocument@ function where the file
is read and then the interesting parts configured in the
context configurations are extracted.
>>> arr (\ (c, w, d, p) -> (c, (w, d, p)))
| The REDUCE function in a MapReduce computation for building indexes .
Even though there might be faster ways to build an index , this function
works with completely on the HolIndex class functions . So it is possible
to use the Indexer with different Index implementations .
TODO Filter but make sure that phrase searching is still possible
| The REDUCE function in a MapReduce computation for building indexes.
Even though there might be faster ways to build an index, this function
works with completely on the HolIndex class functions. So it is possible
to use the Indexer with different Index implementations.
TODO Filter but make sure that phrase searching is still possible
-----------------------------------------------------------------------------
| Downloads a document and calls the function to process the data for the
different contexts of the index
process all context configurations
| Process a Context. Applies the given context to extract information from
the XmlTree that is passed in the arrow.
convert XmlTree
extract interesting parts
Search deep for text nodes
convert text nodes into strings
apply tokenizer function
filter empty words
write cache data if configured
number words
remove stop words
make a list of result tupels
force strict evaluation
convert XmlTree
extract interesting parts
Search deep for text nodes
convert text nodes into strings
apply tokenizer function
filter empty words
write cache data if configured
number words
remove stop words
make a list of result tupels
force strict evaluation
convert XmlTree
extract interesting parts
number words
arrow for pure functions
delete boring words
attach context and docId
select all text nodes
substitute tags by a single space
so tags act as word delimiter
tags are interpreted as word delimiter
take the text nodes
ignore anything else |
|
Module : . Build . Crawl
Copyright : Copyright ( C ) 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.1
Indexer functions for the monadic index class
Module : Holumbus.Build.Crawl
Copyright : Copyright (C) 2008 Sebastian M. Schlatt
License : MIT
Maintainer : Sebastian M. Schlatt ()
Stability : experimental
Portability: portable
Version : 0.1
Indexer functions for the monadic index class
-}
module Holumbus.Build.IndexM
(
buildIndex
, IndexerConfig (..)
, ContextConfig (..)
, mergeIndexerConfigs
)
where
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
import Control.Monad
import Holumbus.Build.Config
import Holumbus.Control.MapReduce.ParallelWithClassPersistent
import Holumbus.Index.Common
import Holumbus.Utility
import System.Time
buildIndex :: (HolDocuments d a, HolIndex i, HolCache c) =>
^ An empty HolIndex . This is used to determine which kind of index to use .
-> Maybe c
^ returns a HolIndex
buildIndex workerThreads traceLevel docs idxConfig emptyIndex cache
= let docs' = (map (\(i,d) -> (i, uri d)) (IM.toList $ toMap docs)) in
(mapReduce
workerThreads
(( fromMaybe "/tmp/" (ic_tmpPath idxConfig)) ++ "MapReduce.db")
emptyIndex
(computeOccurrences traceLevel
(isJust $ ic_tmpPath idxConfig)
(ic_contextConfigs idxConfig)
(ic_readAttributes idxConfig)
cache
)
docs'
)
The first three parameters have to be passed to the function to receive
computeOccurrences :: HolCache c =>
Int -> Bool -> [ContextConfig] -> Attributes -> Maybe c
-> DocId -> String -> IO [((Context, Word), Occurrences)]
computeOccurrences traceLevel fromTmp contextConfigs attrs cache docId theUri
= do
clt <- getClockTime
cat <- toCalendarTime clt
res <- runX ( setTraceLevel traceLevel
>>> traceMsg 1 ((calendarTimeToString cat) ++ " - indexing document: "
++ show docId ++ " -> "
++ show theUri)
>>> processDocument traceLevel attrs' contextConfigs cache docId theUri
>>> strictA
)
return $ buildPositions res
where
attrs' = if fromTmp then addEntries standardReadTmpDocumentAttributes attrs else attrs
buildPositions :: [(Context, Word, DocId, Position)] -> [((Context, Word), Occurrences)]
buildPositions l = M.foldWithKey (\(c,w,d) ps acc -> ((c,w),IM.singleton d ps) : acc) [] $
foldl (\m (c,w,d,p) -> M.insertWith IS.union (c,w,d) (IS.singleton p) m) M.empty l
insertPositions : : ( HolIndex i ) = > i - > String - > [ ( String , String , DocId , Position ) ] - > IO ( Maybe i )
insertPositions idx _ l =
return $ ! Just ( foldl ' theFunc idx l )
where
theFunc i ( context , word , docId , pos ) = insertPosition context word docId pos i
insertPositions :: (HolIndex i) => i -> String -> [(String, String, DocId, Position)] -> IO (Maybe i)
insertPositions idx _ l =
return $! Just (foldl' theFunc idx l)
where
theFunc i (context, word, docId, pos) = insertPosition context word docId pos i
-}
processDocument :: HolCache c =>
Int
-> Attributes
-> [ContextConfig]
-> Maybe c
-> DocId
-> URI
-> IOSLA (XIOState s) b (Context, Word, DocId, Position)
processDocument traceLevel attrs ccs cache docId theUri =
withTraceLevel (traceLevel - traceOffset) (readDocument attrs theUri)
processContext ::
( HolCache c) =>
Maybe c
-> DocId
-> ContextConfig
-> IOSLA (XIOState s) XmlTree (Context, Word, DocId, Position)
processContext cache docId cc =
> > > listA (
> > > getText
)
` guardsP `
( arr unwords > > > arrIO ( putDocText ( fromJust cache ) ( cc_name cc ) docId ) )
)
processContext cache docId cc =
>>> listA (
>>> getText
)
`guardsP`
( arr unwords >>> arrIO ( putDocText (fromJust cache) (cc_name cc) docId))
)
-}
processContext cache docId cc
>>>
fromLA extractWords
>>>
( if ( isJust cache
&&
cc_addToCache cc
)
then perform (arrIO storeInCache)
else this
)
>>>
arrL genWordList
>>>
strictA
where
extractWords :: LA XmlTree [String]
extractWords
= listA
>>>
getTexts
)
>>>
arrL ( filter (not . null) . cc_fTokenize cc )
)
genWordList :: [String] -> [(Context, Word, DocId, Position)]
genWordList
>>>
storeInCache s
= let t = unwords s in
if t /= "" then putDocText (fromJust cache) (cc_name cc) docId t
else return()
getTexts :: LA XmlTree XmlTree
= choiceA
(getChildren >>> getTexts)
<+>
space
]
where
space = txt " "
|
1dc45396041d74fe43c116cd4b52a315558db63262b8d2026120fbb1ea3412dc | realworldocaml/mdx | label.ml |
* Copyright ( c ) 2018 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Relation = struct
type t = Eq | Neq | Le | Lt | Ge | Gt
let pp ppf = function
| Eq -> Fmt.string ppf "="
| Neq -> Fmt.string ppf "<>"
| Gt -> Fmt.string ppf ">"
| Ge -> Fmt.string ppf ">="
| Lt -> Fmt.string ppf "<"
| Le -> Fmt.string ppf "<="
let compare = function
| Eq -> ( = )
| Neq -> ( <> )
| Lt -> ( < )
| Le -> ( <= )
| Gt -> ( > )
| Ge -> ( >= )
let of_string = function
| "<>" -> Neq
| ">=" -> Ge
| ">" -> Gt
| "<=" -> Le
| "<" -> Lt
| "=" -> Eq
| _ -> (* can not happen, filtered by the regexp *) assert false
let re =
let open Re in
compile
@@ seq
[
bos;
group (rep (alt [ alnum; char '-'; char '_' ]));
group
(alt [ str "<="; str ">="; str "<>"; str "<"; str ">"; str "=" ]);
group (rep any);
eos;
]
let raw_parse s =
match Re.exec_opt re s with
| None -> (s, None)
| Some g -> (
try
let label = Re.Group.get g 1 in
let op = of_string (Re.Group.get g 2) in
let value = Re.Group.get g 3 in
(label, Some (op, value))
with Not_found -> (s, None))
end
type non_det = Nd_output | Nd_command
let default_non_det = Nd_output
type block_kind = OCaml | Cram | Toplevel | Include
TODO : [ t ] needs to be refactored because it usually is used as a [ t list ]
but most of these tags are not supposed to be specified multiple times .
There can be at most one Language_tag , similarly specifying multiple
Block_kind and Version labels is confusing at best . [ t ] should probably
be refactored to represent all labels and make sure that some labels
can be specified 0 or 1 times , while others are indeed lists .
but most of these tags are not supposed to be specified multiple times.
There can be at most one Language_tag, similarly specifying multiple
Block_kind and Version labels is confusing at best. [t] should probably
be refactored to represent all labels and make sure that some labels
can be specified 0 or 1 times, while others are indeed lists. *)
type t =
| Dir of string
| Source_tree of string
| File of string
| Part of string
| Env of string
| Skip
| Non_det of non_det option
| Version of Relation.t * Ocaml_version.t
| Set of string * string
| Unset of string
| Block_kind of block_kind
(* Specifies the language tag that is specified in the [mli] syntax, if
any. Can be left out if none is specified, in such case it will also
not be added back. *)
| Language_tag of string
let pp_block_kind ppf = function
| OCaml -> Fmt.string ppf "ocaml"
| Cram -> Fmt.string ppf "cram"
| Toplevel -> Fmt.string ppf "toplevel"
| Include -> Fmt.string ppf "include"
let pp ppf = function
| Dir d -> Fmt.pf ppf "dir=%s" d
| Source_tree s -> Fmt.pf ppf "source-tree=%s" s
| File f -> Fmt.pf ppf "file=%s" f
| Part p -> Fmt.pf ppf "part=%s" p
| Env e -> Fmt.pf ppf "env=%s" e
| Skip -> Fmt.string ppf "skip"
| Non_det None -> Fmt.string ppf "non-deterministic"
| Non_det (Some Nd_output) -> Fmt.string ppf "non-deterministic=output"
| Non_det (Some Nd_command) -> Fmt.string ppf "non-deterministic=command"
| Version (op, v) ->
Fmt.pf ppf "version%a%a" Relation.pp op Ocaml_version.pp v
| Set (v, x) -> Fmt.pf ppf "set-%s=%s" v x
| Unset x -> Fmt.pf ppf "unset-%s" x
| Block_kind bk -> pp_block_kind ppf bk
| Language_tag language_tag -> Fmt.string ppf language_tag
let is_prefix ~prefix s =
let len_prefix = String.length prefix in
if String.length s > len_prefix then
String.equal (String.sub s 0 len_prefix) prefix
else false
[ is_prefix ~prefix s ] is always checked before .
let split_prefix ~prefix s =
let len_prefix = String.length prefix in
String.sub s len_prefix (String.length s - len_prefix)
let non_eq_op ~label =
Util.Result.errorf "Label `%s` requires assignment using the `=` operator."
label
let invalid_value ~label ~allowed_values value =
Util.Result.errorf
"%S is not a valid value for label `%s`. Valid values are %s." value label
(Util.String.english_conjonction allowed_values)
let doesnt_accept_value ~label ~value res =
match value with
| Some _ -> Util.Result.errorf "Label `%s` does not allow a value." label
| None -> Ok res
let requires_value ~label ~value f =
match value with
| Some (op, v) -> f op v
| None -> Util.Result.errorf "Label `%s` requires a value." label
let requires_eq_value ~label ~value f =
requires_value ~label ~value (fun op value ->
match op with Relation.Eq -> Ok (f value) | _ -> non_eq_op ~label)
let interpret label value =
match label with
| "skip" -> doesnt_accept_value ~label ~value Skip
| "ocaml" -> doesnt_accept_value ~label ~value (Block_kind OCaml)
| "cram" -> doesnt_accept_value ~label ~value (Block_kind Cram)
| "toplevel" -> doesnt_accept_value ~label ~value (Block_kind Toplevel)
| "include" -> doesnt_accept_value ~label ~value (Block_kind Include)
| v when is_prefix ~prefix:"unset-" v ->
doesnt_accept_value ~label ~value
(Unset (split_prefix ~prefix:"unset-" v))
| "version" ->
requires_value ~label ~value (fun op v ->
match Ocaml_version.of_string v with
| Ok v -> Ok (Version (op, v))
| Error (`Msg e) ->
Util.Result.errorf "Invalid `version` label value: %s." e)
| "non-deterministic" -> (
match value with
| None -> Ok (Non_det None)
| Some (Relation.Eq, "output") -> Ok (Non_det (Some Nd_output))
| Some (Relation.Eq, "command") -> Ok (Non_det (Some Nd_command))
| Some (Relation.Eq, v) ->
let allowed_values = [ "<none>"; {|"command"|}; {|"output"|} ] in
invalid_value ~label ~allowed_values v
| Some _ -> non_eq_op ~label)
| "dir" -> requires_eq_value ~label ~value (fun x -> Dir x)
| "source-tree" -> requires_eq_value ~label ~value (fun x -> Source_tree x)
| "file" -> requires_eq_value ~label ~value (fun x -> File x)
| "part" -> requires_eq_value ~label ~value (fun x -> Part x)
| "env" -> requires_eq_value ~label ~value (fun x -> Env x)
| l when is_prefix ~prefix:"set-" l ->
requires_eq_value ~label ~value (fun x ->
Set (split_prefix ~prefix:"set-" l, x))
| l -> Error (`Msg (Format.sprintf "`%s` is not a valid label." l))
let of_string s =
let f acc s =
let label, value = Relation.raw_parse s in
match (acc, interpret label value) with
| Ok labels, Ok label -> Ok (label :: labels)
| Error msgs, Ok _ -> Error msgs
| Ok _, Error msg -> Error [ msg ]
| Error msgs, Error msg -> Error (msg :: msgs)
in
match s with
| "" -> Ok []
| s -> (
let split = String.split_on_char ',' s in
match List.fold_left f (Ok []) split with
| Ok labels -> Ok (List.rev labels)
| Error msgs -> Error (List.rev msgs))
| null | https://raw.githubusercontent.com/realworldocaml/mdx/aa5551a8eb0669fa4561aeee55d6f1528661a510/lib/label.ml | ocaml | can not happen, filtered by the regexp
Specifies the language tag that is specified in the [mli] syntax, if
any. Can be left out if none is specified, in such case it will also
not be added back. |
* Copyright ( c ) 2018 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Relation = struct
type t = Eq | Neq | Le | Lt | Ge | Gt
let pp ppf = function
| Eq -> Fmt.string ppf "="
| Neq -> Fmt.string ppf "<>"
| Gt -> Fmt.string ppf ">"
| Ge -> Fmt.string ppf ">="
| Lt -> Fmt.string ppf "<"
| Le -> Fmt.string ppf "<="
let compare = function
| Eq -> ( = )
| Neq -> ( <> )
| Lt -> ( < )
| Le -> ( <= )
| Gt -> ( > )
| Ge -> ( >= )
let of_string = function
| "<>" -> Neq
| ">=" -> Ge
| ">" -> Gt
| "<=" -> Le
| "<" -> Lt
| "=" -> Eq
let re =
let open Re in
compile
@@ seq
[
bos;
group (rep (alt [ alnum; char '-'; char '_' ]));
group
(alt [ str "<="; str ">="; str "<>"; str "<"; str ">"; str "=" ]);
group (rep any);
eos;
]
let raw_parse s =
match Re.exec_opt re s with
| None -> (s, None)
| Some g -> (
try
let label = Re.Group.get g 1 in
let op = of_string (Re.Group.get g 2) in
let value = Re.Group.get g 3 in
(label, Some (op, value))
with Not_found -> (s, None))
end
type non_det = Nd_output | Nd_command
let default_non_det = Nd_output
type block_kind = OCaml | Cram | Toplevel | Include
TODO : [ t ] needs to be refactored because it usually is used as a [ t list ]
but most of these tags are not supposed to be specified multiple times .
There can be at most one Language_tag , similarly specifying multiple
Block_kind and Version labels is confusing at best . [ t ] should probably
be refactored to represent all labels and make sure that some labels
can be specified 0 or 1 times , while others are indeed lists .
but most of these tags are not supposed to be specified multiple times.
There can be at most one Language_tag, similarly specifying multiple
Block_kind and Version labels is confusing at best. [t] should probably
be refactored to represent all labels and make sure that some labels
can be specified 0 or 1 times, while others are indeed lists. *)
type t =
| Dir of string
| Source_tree of string
| File of string
| Part of string
| Env of string
| Skip
| Non_det of non_det option
| Version of Relation.t * Ocaml_version.t
| Set of string * string
| Unset of string
| Block_kind of block_kind
| Language_tag of string
let pp_block_kind ppf = function
| OCaml -> Fmt.string ppf "ocaml"
| Cram -> Fmt.string ppf "cram"
| Toplevel -> Fmt.string ppf "toplevel"
| Include -> Fmt.string ppf "include"
let pp ppf = function
| Dir d -> Fmt.pf ppf "dir=%s" d
| Source_tree s -> Fmt.pf ppf "source-tree=%s" s
| File f -> Fmt.pf ppf "file=%s" f
| Part p -> Fmt.pf ppf "part=%s" p
| Env e -> Fmt.pf ppf "env=%s" e
| Skip -> Fmt.string ppf "skip"
| Non_det None -> Fmt.string ppf "non-deterministic"
| Non_det (Some Nd_output) -> Fmt.string ppf "non-deterministic=output"
| Non_det (Some Nd_command) -> Fmt.string ppf "non-deterministic=command"
| Version (op, v) ->
Fmt.pf ppf "version%a%a" Relation.pp op Ocaml_version.pp v
| Set (v, x) -> Fmt.pf ppf "set-%s=%s" v x
| Unset x -> Fmt.pf ppf "unset-%s" x
| Block_kind bk -> pp_block_kind ppf bk
| Language_tag language_tag -> Fmt.string ppf language_tag
let is_prefix ~prefix s =
let len_prefix = String.length prefix in
if String.length s > len_prefix then
String.equal (String.sub s 0 len_prefix) prefix
else false
[ is_prefix ~prefix s ] is always checked before .
let split_prefix ~prefix s =
let len_prefix = String.length prefix in
String.sub s len_prefix (String.length s - len_prefix)
let non_eq_op ~label =
Util.Result.errorf "Label `%s` requires assignment using the `=` operator."
label
let invalid_value ~label ~allowed_values value =
Util.Result.errorf
"%S is not a valid value for label `%s`. Valid values are %s." value label
(Util.String.english_conjonction allowed_values)
let doesnt_accept_value ~label ~value res =
match value with
| Some _ -> Util.Result.errorf "Label `%s` does not allow a value." label
| None -> Ok res
let requires_value ~label ~value f =
match value with
| Some (op, v) -> f op v
| None -> Util.Result.errorf "Label `%s` requires a value." label
let requires_eq_value ~label ~value f =
requires_value ~label ~value (fun op value ->
match op with Relation.Eq -> Ok (f value) | _ -> non_eq_op ~label)
let interpret label value =
match label with
| "skip" -> doesnt_accept_value ~label ~value Skip
| "ocaml" -> doesnt_accept_value ~label ~value (Block_kind OCaml)
| "cram" -> doesnt_accept_value ~label ~value (Block_kind Cram)
| "toplevel" -> doesnt_accept_value ~label ~value (Block_kind Toplevel)
| "include" -> doesnt_accept_value ~label ~value (Block_kind Include)
| v when is_prefix ~prefix:"unset-" v ->
doesnt_accept_value ~label ~value
(Unset (split_prefix ~prefix:"unset-" v))
| "version" ->
requires_value ~label ~value (fun op v ->
match Ocaml_version.of_string v with
| Ok v -> Ok (Version (op, v))
| Error (`Msg e) ->
Util.Result.errorf "Invalid `version` label value: %s." e)
| "non-deterministic" -> (
match value with
| None -> Ok (Non_det None)
| Some (Relation.Eq, "output") -> Ok (Non_det (Some Nd_output))
| Some (Relation.Eq, "command") -> Ok (Non_det (Some Nd_command))
| Some (Relation.Eq, v) ->
let allowed_values = [ "<none>"; {|"command"|}; {|"output"|} ] in
invalid_value ~label ~allowed_values v
| Some _ -> non_eq_op ~label)
| "dir" -> requires_eq_value ~label ~value (fun x -> Dir x)
| "source-tree" -> requires_eq_value ~label ~value (fun x -> Source_tree x)
| "file" -> requires_eq_value ~label ~value (fun x -> File x)
| "part" -> requires_eq_value ~label ~value (fun x -> Part x)
| "env" -> requires_eq_value ~label ~value (fun x -> Env x)
| l when is_prefix ~prefix:"set-" l ->
requires_eq_value ~label ~value (fun x ->
Set (split_prefix ~prefix:"set-" l, x))
| l -> Error (`Msg (Format.sprintf "`%s` is not a valid label." l))
let of_string s =
let f acc s =
let label, value = Relation.raw_parse s in
match (acc, interpret label value) with
| Ok labels, Ok label -> Ok (label :: labels)
| Error msgs, Ok _ -> Error msgs
| Ok _, Error msg -> Error [ msg ]
| Error msgs, Error msg -> Error (msg :: msgs)
in
match s with
| "" -> Ok []
| s -> (
let split = String.split_on_char ',' s in
match List.fold_left f (Ok []) split with
| Ok labels -> Ok (List.rev labels)
| Error msgs -> Error (List.rev msgs))
|
894941b060ec18e0c9a732476ec9dc505adcce5d9aa6fb0318c9a78f3fa1d5b5 | fortytools/holumbus | Core.hs | {-# OPTIONS -XBangPatterns #-}
-- ------------------------------------------------------------
module Holumbus.Crawler.Core
where
import Control.Concurrent.MapFold ( mapFold )
import Control.Sequential.MapFoldBinary ( mapFoldBinaryM )
import Control.DeepSeq
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.ReaderStateIO
import Data.Binary ( Binary )
else naming conflict with put and get from Monad . State
import Data.Function.Selector
import Data.List
import Holumbus.Crawler.CrawlerAction
import Holumbus.Crawler.Constants
import Holumbus.Crawler.Logger
import Holumbus.Crawler.URIs
import Holumbus.Crawler.Robots
import Holumbus.Crawler.Types
import Holumbus.Crawler.Util ( mkTmpFile )
import Holumbus.Crawler.XmlArrows
import Text.XML.HXT.Core hiding
( when
, getState
)
-- ------------------------------------------------------------
saveCrawlerState :: (Binary r) => FilePath -> CrawlerAction a r ()
saveCrawlerState fn = do
s <- get
liftIO $ B.encodeFile fn s
loadCrawlerState :: (Binary r) => FilePath -> CrawlerAction a r ()
loadCrawlerState fn = do
s <- liftIO $ B.decodeFile fn
put s
uriProcessed :: URI -> CrawlerAction a r ()
uriProcessed uri = do
modifyState theToBeProcessed $ deleteURI uri
modifyState theAlreadyProcessed $ insertURI uri
urisProcessed :: URIs -> CrawlerAction a r ()
urisProcessed uris = do
modifyState theToBeProcessed $ deleteURIs uris
modifyState theAlreadyProcessed $ flip unionURIs uris
uriToBeProcessed :: URI -> CrawlerAction a r ()
uriToBeProcessed uri = do
aps <- getState theAlreadyProcessed
when ( not $ uri `memberURIs` aps )
( modifyState theToBeProcessed $ insertURI uri )
urisToBeProcessed :: URIs -> CrawlerAction a r ()
urisToBeProcessed uris = do
aps <- getState theAlreadyProcessed
let newUris = deleteURIs aps uris
modifyState theToBeProcessed $ flip unionURIs newUris
uriAddToRobotsTxt :: URI -> CrawlerAction a r ()
uriAddToRobotsTxt uri = do
conf <- ask
let raa = getS theAddRobotsAction conf
modifyStateIO theRobots (raa conf uri)
accumulateRes :: (NFData r) => (URI, a) -> CrawlerAction a r ()
accumulateRes res = do
combine <- getConf theAccumulateOp
acc0 <- getState theResultAccu
acc1 <- liftIO $ combine res acc0
putState theResultAccu acc1
-- ------------------------------------------------------------
crawlDocs :: (NFData a, NFData r, Binary r) => [URI] -> CrawlerAction a r ()
crawlDocs uris = do
noticeC "crawlDocs" ["init crawler state and start crawler loop"]
putState theToBeProcessed (fromListURIs uris)
crawlerLoop
noticeC "crawlDocs" ["crawler loop finished"]
crawlerSaveState
crawlerLoop :: (NFData a, NFData r, Binary r) => CrawlerAction a r ()
crawlerLoop = do
n <- getState theNoOfDocs
m <- getConf theMaxNoOfDocs
t <- getConf theMaxParThreads
when (n < m)
( do
noticeC "crawlerLoop" ["iteration", show $ n+1]
tbp <- getState theToBeProcessed
noticeC "crawlerLoop" [show $ cardURIs tbp, "uri(s) remain to be processed"]
when (not . nullURIs $ tbp)
( do
case t of
0 -> crawlNextDoc -- sequential crawling
1 -> crawlNextDocs mapFoldBinaryM -- sequential crawling with binary mapFold
_ -> crawlNextDocs (mapFold t) -- parallel mapFold crawling
crawlerCheckSaveState
crawlerLoop
)
)
crawlerResume :: (NFData a, NFData r, Binary r) => String -> CrawlerAction a r ()
crawlerResume fn = do
noticeC "crawlerResume" ["read crawler state from", fn]
loadCrawlerState fn
noticeC "crawlerResume" ["resume crawler"]
crawlerLoop
crawlerCheckSaveState :: Binary r => CrawlerAction a r ()
crawlerCheckSaveState = do
n1 <- getState theNoOfDocs
n0 <- getState theNoOfDocsSaved
m <- getConf theSaveIntervall
when ( m > 0 && n1 - n0 >= m)
crawlerSaveState
crawlerSaveState :: Binary r => CrawlerAction a r ()
crawlerSaveState = do
n1 <- getState theNoOfDocs
fn <- getConf theSavePathPrefix
let fn' = mkTmpFile 10 fn n1
noticeC "crawlerSaveState" [show n1, "documents into", show fn']
putState theNoOfDocsSaved n1
saveCrawlerState fn'
noticeC "crawlerSaveState" ["saving state finished"]
-- ------------------------------------------------------------
type MapFold a r = (a -> IO r) -> (r -> r -> IO r) -> [a] -> IO r
crawlNextDocs :: (NFData r) => MapFold URI (URIs, URIs, r) -> CrawlerAction a r ()
crawlNextDocs mapf = do
uris <- getState theToBeProcessed
nd <- getState theNoOfDocs
mp <- getConf theMaxParDocs
md <- getConf theMaxNoOfDocs
let n = mp `min` (md - nd)
let urisTBP = nextURIs n uris
modifyState theNoOfDocs (+ (length urisTBP))
noticeC "crawlNextDocs" ["next", show (length urisTBP), "uri(s) will be processed"]
urisProcessed $ fromListURIs urisTBP
urisAllowed <- filterM isAllowedByRobots urisTBP
when (not . null $ urisAllowed) $
do
conf <- ask
let mergeOp = getS theFoldOp conf
state <- get
( ! urisMoved,
! urisNew,
! results
) <- liftIO $
mapf (processCmd conf state) (combineDocResults' mergeOp) $
urisAllowed
noticeC "crawlNextDocs" [show . cardURIs $ urisNew, "hrefs found, accumulating results"]
mapM_ (debugC "crawlNextDocs") $ map (("href" :) . (:[])) $ toListURIs urisNew
urisProcessed urisMoved
urisToBeProcessed urisNew
acc0 <- getState theResultAccu
! acc1 <- liftIO $ mergeOp results acc0
putState theResultAccu acc1
noticeC "crawlNextDocs" ["document results accumulated"]
where
processCmd c s u = do
noticeC' "processCmd" ["processing document:", show u]
((m1, n1, rawRes), _) <- runCrawler (processDoc' u) c s
r1 <- foldM (flip accOp) res0 rawRes
rnf r1 `seq` rnf m1 `seq` rnf r1 `seq`
noticeC' "processCmd" ["document processed: ", show u]
return (m1, n1, r1)
where
res0 = getS theResultInit s
accOp = getS theAccumulateOp c
-- ------------------------------------------------------------
processDoc' :: URI -> CrawlerAction a r (URIs, URIs, [(URI, a)])
processDoc' uri = do
conf <- ask
[(uri', (uris', docRes))] <- liftIO $ runX (processDocArrow conf uri)
let toBeFollowed = getS theFollowRef conf
let movedUris = if null uri'
then emptyURIs
else singletonURIs uri'
let newUris = fromListURIs .
filter toBeFollowed $ uris'
return (movedUris, newUris, docRes)
-- ------------------------------------------------------------
combineDocResults' :: (NFData r) => MergeDocResults r -> (URIs, URIs, r) -> (URIs, URIs, r) -> IO (URIs, URIs, r)
combineDocResults' mergeOp (m1, n1, r1) (m2, n2, r2)
= do
noticeC' "crawlNextDocs" ["combining results"]
r <- mergeOp r1 r2
m <- return $ unionURIs m1 m2
n <- return $ unionURIs n1 n2
res <- return $ (m, n, r)
rnf res `seq`
noticeC' "crawlNextDocs" ["results combined"]
return res
-- ------------------------------------------------------------
--
-- | crawl a single doc, mark doc as processed, collect new hrefs and combine doc result with accumulator in state
crawlNextDoc :: (NFData a, NFData r) => CrawlerAction a r ()
crawlNextDoc = do
uris <- getState theToBeProcessed
modifyState theNoOfDocs (+1)
let uri = nextURI uris
noticeC "crawlNextDoc" [show uri]
uriProcessed uri -- uri is put into processed URIs
isGood <- isAllowedByRobots uri
when isGood $
do
res <- processDoc uri -- get document and extract new refs and result
(uri', uris', resList') <- rnf res `seq` -- force evaluation
return res
when (not . null $ uri') $
uriProcessed uri' -- doc has been moved, uri' is real uri, so it's also put into the set of processed URIs
noticeC "crawlNextDoc" [show . length . nub . sort $ uris', "new uris found"]
mapM_ uriToBeProcessed uris' -- insert new uris into toBeProcessed set
mapM_ accumulateRes resList' -- combine results with state accu
-- | Run the process document arrow and prepare results
processDoc :: URI -> CrawlerAction a r (URI, [URI], [(URI, a)])
processDoc uri = do
conf <- ask
[(uri', (uris, res))] <- liftIO $ runX (processDocArrow conf uri)
return ( if uri' /= uri
then uri'
else ""
, filter (getS theFollowRef conf) uris
, res -- usually in case of normal processing this list consists of a singleton list
)
-- and in case of an error it's an empty list
-- ------------------------------------------------------------
-- | filter uris rejected by robots.txt
isAllowedByRobots :: URI -> CrawlerAction a r Bool
isAllowedByRobots uri = do
uriAddToRobotsTxt uri -- for the uri host, a robots.txt is loaded, if neccessary
rdm <- getState theRobots
if (robotsDisallow rdm uri) -- check, whether uri is disallowed by host/robots.txt
then do
noticeC "isAllowedByRobots" ["uri rejected by robots.txt", show uri]
return False
else return True
-- ------------------------------------------------------------
| From a document two results are computed , 1 . the list of all hrefs in the contents ,
and 2 . the collected info contained in the page . This result is augmented with the transfer uri
such that following functions know the source of this contents . The transfer - URI may be another one
-- as the input uri, there could happen a redirect in the http request.
--
The two listA arrows make the whole arrow deterministic , so it never fails
processDocArrow :: CrawlerConfig c r -> URI -> IOSArrow a (URI, ([URI], [(URI, c)]))
processDocArrow c uri = ( hxtSetTraceAndErrorLogger (getS theTraceLevelHxt c)
>>>
readDocument [getS theSysConfig c] uri
>>>
perform ( ( getAttrValue transferStatus
&&&
getAttrValue transferMessage
)
>>>
( arr2 $ \ s m -> unwords ["processDocArrow: response code:", s, m] )
>>>
traceString 1 id
)
>>>
( getRealDocURI
&&&
listA ( checkDocumentStatus
>>>
getS thePreRefsFilter c
>>>
getS theProcessRefs c
)
&&&
listA ( getS thePreDocFilter c
>>>
( getAttrValue transferURI
&&&
getS theProcessDoc c
)
)
)
)
`withDefault` ("", ([], []))
-- ------------------------------------------------------------
| compute the real URI in case of a 301 or 302 response ( moved permanently or temporary ) ,
-- else the arrow will fail
getLocationReference :: ArrowXml a => a XmlTree String
getLocationReference = fromLA $
( getAttrValue0 transferStatus
>>>
isA (`elem` ["301", "302"])
)
`guards`
getAttrValue0 http_location
-- | compute the real URI of the document, in case of a move response
-- this is contained in the \"http-location\" attribute, else it's the
-- tranferURI.
getRealDocURI :: ArrowXml a => a XmlTree String
getRealDocURI = fromLA $
getLocationReference
`orElse`
getAttrValue transferURI
-- ------------------------------------------------------------
initCrawler :: CrawlerAction a r ()
initCrawler = do
conf <- ask
setLogLevel "" (getS theTraceLevel conf)
runCrawler :: CrawlerAction a r x -> CrawlerConfig a r -> CrawlerState r -> IO (x, CrawlerState r)
runCrawler a = runReaderStateIO (initCrawler >> a)
-- run a crawler and deliver just the accumulated result value
execCrawler :: CrawlerAction a r x -> CrawlerConfig a r -> CrawlerState r -> IO (CrawlerState r)
execCrawler cmd config initState
= runCrawler cmd config initState >>= return . snd
-- ------------------------------------------------------------
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/crawl2/src/Holumbus/Crawler/Core.hs | haskell | # OPTIONS -XBangPatterns #
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
sequential crawling
sequential crawling with binary mapFold
parallel mapFold crawling
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
| crawl a single doc, mark doc as processed, collect new hrefs and combine doc result with accumulator in state
uri is put into processed URIs
get document and extract new refs and result
force evaluation
doc has been moved, uri' is real uri, so it's also put into the set of processed URIs
insert new uris into toBeProcessed set
combine results with state accu
| Run the process document arrow and prepare results
usually in case of normal processing this list consists of a singleton list
and in case of an error it's an empty list
------------------------------------------------------------
| filter uris rejected by robots.txt
for the uri host, a robots.txt is loaded, if neccessary
check, whether uri is disallowed by host/robots.txt
------------------------------------------------------------
as the input uri, there could happen a redirect in the http request.
------------------------------------------------------------
else the arrow will fail
| compute the real URI of the document, in case of a move response
this is contained in the \"http-location\" attribute, else it's the
tranferURI.
------------------------------------------------------------
run a crawler and deliver just the accumulated result value
------------------------------------------------------------ |
module Holumbus.Crawler.Core
where
import Control.Concurrent.MapFold ( mapFold )
import Control.Sequential.MapFoldBinary ( mapFoldBinaryM )
import Control.DeepSeq
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.ReaderStateIO
import Data.Binary ( Binary )
else naming conflict with put and get from Monad . State
import Data.Function.Selector
import Data.List
import Holumbus.Crawler.CrawlerAction
import Holumbus.Crawler.Constants
import Holumbus.Crawler.Logger
import Holumbus.Crawler.URIs
import Holumbus.Crawler.Robots
import Holumbus.Crawler.Types
import Holumbus.Crawler.Util ( mkTmpFile )
import Holumbus.Crawler.XmlArrows
import Text.XML.HXT.Core hiding
( when
, getState
)
saveCrawlerState :: (Binary r) => FilePath -> CrawlerAction a r ()
saveCrawlerState fn = do
s <- get
liftIO $ B.encodeFile fn s
loadCrawlerState :: (Binary r) => FilePath -> CrawlerAction a r ()
loadCrawlerState fn = do
s <- liftIO $ B.decodeFile fn
put s
uriProcessed :: URI -> CrawlerAction a r ()
uriProcessed uri = do
modifyState theToBeProcessed $ deleteURI uri
modifyState theAlreadyProcessed $ insertURI uri
urisProcessed :: URIs -> CrawlerAction a r ()
urisProcessed uris = do
modifyState theToBeProcessed $ deleteURIs uris
modifyState theAlreadyProcessed $ flip unionURIs uris
uriToBeProcessed :: URI -> CrawlerAction a r ()
uriToBeProcessed uri = do
aps <- getState theAlreadyProcessed
when ( not $ uri `memberURIs` aps )
( modifyState theToBeProcessed $ insertURI uri )
urisToBeProcessed :: URIs -> CrawlerAction a r ()
urisToBeProcessed uris = do
aps <- getState theAlreadyProcessed
let newUris = deleteURIs aps uris
modifyState theToBeProcessed $ flip unionURIs newUris
uriAddToRobotsTxt :: URI -> CrawlerAction a r ()
uriAddToRobotsTxt uri = do
conf <- ask
let raa = getS theAddRobotsAction conf
modifyStateIO theRobots (raa conf uri)
accumulateRes :: (NFData r) => (URI, a) -> CrawlerAction a r ()
accumulateRes res = do
combine <- getConf theAccumulateOp
acc0 <- getState theResultAccu
acc1 <- liftIO $ combine res acc0
putState theResultAccu acc1
crawlDocs :: (NFData a, NFData r, Binary r) => [URI] -> CrawlerAction a r ()
crawlDocs uris = do
noticeC "crawlDocs" ["init crawler state and start crawler loop"]
putState theToBeProcessed (fromListURIs uris)
crawlerLoop
noticeC "crawlDocs" ["crawler loop finished"]
crawlerSaveState
crawlerLoop :: (NFData a, NFData r, Binary r) => CrawlerAction a r ()
crawlerLoop = do
n <- getState theNoOfDocs
m <- getConf theMaxNoOfDocs
t <- getConf theMaxParThreads
when (n < m)
( do
noticeC "crawlerLoop" ["iteration", show $ n+1]
tbp <- getState theToBeProcessed
noticeC "crawlerLoop" [show $ cardURIs tbp, "uri(s) remain to be processed"]
when (not . nullURIs $ tbp)
( do
case t of
crawlerCheckSaveState
crawlerLoop
)
)
crawlerResume :: (NFData a, NFData r, Binary r) => String -> CrawlerAction a r ()
crawlerResume fn = do
noticeC "crawlerResume" ["read crawler state from", fn]
loadCrawlerState fn
noticeC "crawlerResume" ["resume crawler"]
crawlerLoop
crawlerCheckSaveState :: Binary r => CrawlerAction a r ()
crawlerCheckSaveState = do
n1 <- getState theNoOfDocs
n0 <- getState theNoOfDocsSaved
m <- getConf theSaveIntervall
when ( m > 0 && n1 - n0 >= m)
crawlerSaveState
crawlerSaveState :: Binary r => CrawlerAction a r ()
crawlerSaveState = do
n1 <- getState theNoOfDocs
fn <- getConf theSavePathPrefix
let fn' = mkTmpFile 10 fn n1
noticeC "crawlerSaveState" [show n1, "documents into", show fn']
putState theNoOfDocsSaved n1
saveCrawlerState fn'
noticeC "crawlerSaveState" ["saving state finished"]
type MapFold a r = (a -> IO r) -> (r -> r -> IO r) -> [a] -> IO r
crawlNextDocs :: (NFData r) => MapFold URI (URIs, URIs, r) -> CrawlerAction a r ()
crawlNextDocs mapf = do
uris <- getState theToBeProcessed
nd <- getState theNoOfDocs
mp <- getConf theMaxParDocs
md <- getConf theMaxNoOfDocs
let n = mp `min` (md - nd)
let urisTBP = nextURIs n uris
modifyState theNoOfDocs (+ (length urisTBP))
noticeC "crawlNextDocs" ["next", show (length urisTBP), "uri(s) will be processed"]
urisProcessed $ fromListURIs urisTBP
urisAllowed <- filterM isAllowedByRobots urisTBP
when (not . null $ urisAllowed) $
do
conf <- ask
let mergeOp = getS theFoldOp conf
state <- get
( ! urisMoved,
! urisNew,
! results
) <- liftIO $
mapf (processCmd conf state) (combineDocResults' mergeOp) $
urisAllowed
noticeC "crawlNextDocs" [show . cardURIs $ urisNew, "hrefs found, accumulating results"]
mapM_ (debugC "crawlNextDocs") $ map (("href" :) . (:[])) $ toListURIs urisNew
urisProcessed urisMoved
urisToBeProcessed urisNew
acc0 <- getState theResultAccu
! acc1 <- liftIO $ mergeOp results acc0
putState theResultAccu acc1
noticeC "crawlNextDocs" ["document results accumulated"]
where
processCmd c s u = do
noticeC' "processCmd" ["processing document:", show u]
((m1, n1, rawRes), _) <- runCrawler (processDoc' u) c s
r1 <- foldM (flip accOp) res0 rawRes
rnf r1 `seq` rnf m1 `seq` rnf r1 `seq`
noticeC' "processCmd" ["document processed: ", show u]
return (m1, n1, r1)
where
res0 = getS theResultInit s
accOp = getS theAccumulateOp c
processDoc' :: URI -> CrawlerAction a r (URIs, URIs, [(URI, a)])
processDoc' uri = do
conf <- ask
[(uri', (uris', docRes))] <- liftIO $ runX (processDocArrow conf uri)
let toBeFollowed = getS theFollowRef conf
let movedUris = if null uri'
then emptyURIs
else singletonURIs uri'
let newUris = fromListURIs .
filter toBeFollowed $ uris'
return (movedUris, newUris, docRes)
combineDocResults' :: (NFData r) => MergeDocResults r -> (URIs, URIs, r) -> (URIs, URIs, r) -> IO (URIs, URIs, r)
combineDocResults' mergeOp (m1, n1, r1) (m2, n2, r2)
= do
noticeC' "crawlNextDocs" ["combining results"]
r <- mergeOp r1 r2
m <- return $ unionURIs m1 m2
n <- return $ unionURIs n1 n2
res <- return $ (m, n, r)
rnf res `seq`
noticeC' "crawlNextDocs" ["results combined"]
return res
crawlNextDoc :: (NFData a, NFData r) => CrawlerAction a r ()
crawlNextDoc = do
uris <- getState theToBeProcessed
modifyState theNoOfDocs (+1)
let uri = nextURI uris
noticeC "crawlNextDoc" [show uri]
isGood <- isAllowedByRobots uri
when isGood $
do
return res
when (not . null $ uri') $
noticeC "crawlNextDoc" [show . length . nub . sort $ uris', "new uris found"]
processDoc :: URI -> CrawlerAction a r (URI, [URI], [(URI, a)])
processDoc uri = do
conf <- ask
[(uri', (uris, res))] <- liftIO $ runX (processDocArrow conf uri)
return ( if uri' /= uri
then uri'
else ""
, filter (getS theFollowRef conf) uris
)
isAllowedByRobots :: URI -> CrawlerAction a r Bool
isAllowedByRobots uri = do
rdm <- getState theRobots
then do
noticeC "isAllowedByRobots" ["uri rejected by robots.txt", show uri]
return False
else return True
| From a document two results are computed , 1 . the list of all hrefs in the contents ,
and 2 . the collected info contained in the page . This result is augmented with the transfer uri
such that following functions know the source of this contents . The transfer - URI may be another one
The two listA arrows make the whole arrow deterministic , so it never fails
processDocArrow :: CrawlerConfig c r -> URI -> IOSArrow a (URI, ([URI], [(URI, c)]))
processDocArrow c uri = ( hxtSetTraceAndErrorLogger (getS theTraceLevelHxt c)
>>>
readDocument [getS theSysConfig c] uri
>>>
perform ( ( getAttrValue transferStatus
&&&
getAttrValue transferMessage
)
>>>
( arr2 $ \ s m -> unwords ["processDocArrow: response code:", s, m] )
>>>
traceString 1 id
)
>>>
( getRealDocURI
&&&
listA ( checkDocumentStatus
>>>
getS thePreRefsFilter c
>>>
getS theProcessRefs c
)
&&&
listA ( getS thePreDocFilter c
>>>
( getAttrValue transferURI
&&&
getS theProcessDoc c
)
)
)
)
`withDefault` ("", ([], []))
| compute the real URI in case of a 301 or 302 response ( moved permanently or temporary ) ,
getLocationReference :: ArrowXml a => a XmlTree String
getLocationReference = fromLA $
( getAttrValue0 transferStatus
>>>
isA (`elem` ["301", "302"])
)
`guards`
getAttrValue0 http_location
getRealDocURI :: ArrowXml a => a XmlTree String
getRealDocURI = fromLA $
getLocationReference
`orElse`
getAttrValue transferURI
initCrawler :: CrawlerAction a r ()
initCrawler = do
conf <- ask
setLogLevel "" (getS theTraceLevel conf)
runCrawler :: CrawlerAction a r x -> CrawlerConfig a r -> CrawlerState r -> IO (x, CrawlerState r)
runCrawler a = runReaderStateIO (initCrawler >> a)
execCrawler :: CrawlerAction a r x -> CrawlerConfig a r -> CrawlerState r -> IO (CrawlerState r)
execCrawler cmd config initState
= runCrawler cmd config initState >>= return . snd
|
5422a4c2ed97ab389fbc266b620f6b23cc9d6d0286f118088c6cfdc2585c9724 | ananthakumaran/webify | Webify.hs | # OPTIONS_GHC -fno - warn - missing - signatures #
# LANGUAGE RecordWildCards #
import Control.Exception
import Control.Monad
import Data.Binary.Strict.Get
import qualified Data.ByteString as B
import Data.Monoid
import EOT
import Font hiding (str)
import Options.Applicative hiding (header)
import OTF
import SVG
import System.FilePath
import TTF
import Utils
import WOFF
platformAppleUnicode = 0
platformMacintosh = 1
platformISO = 2
platformMicrosoft = 3
encodingUndefined = 0
encodingUGL = 1
data Opts = Opts { noEot :: Bool
, noWoff :: Bool
, noSvg :: Bool
, enableSvgKern :: Bool
, zopfli :: Bool
, svgPlatformId :: UShort
, svgEncodingId :: UShort
, inputs :: [String]}
optsDef :: Parser Opts
optsDef = Opts <$> switch (long "no-eot" <> help "Disable eot")
<*> switch (long "no-woff" <> help "Disable woff")
<*> switch (long "no-svg" <> help "Disable svg")
<*> switch (long "svg-enable-kerning" <> help "Enable svg kerning")
<*> switch (long "zopfli" <> help "Use Zopfli Compression Algorithm")
<*> option auto (long "svg-cmap-platform-id" <> value platformMicrosoft <> help "Svg cmap platform id")
<*> option auto (long "svg-cmap-encoding-id" <> value encodingUGL <> help "Svg cmap encoding id")
<*> some (argument str (metavar "FONTS"))
changeExtension :: FilePath -> FilePath -> FilePath
changeExtension ext = flip addExtension ext . dropExtension
cmapDescription :: (Integral a) => a -> a -> String
cmapDescription 0 0 = "Unicode 1.0 semantics"
cmapDescription 0 1 = "Unicode 1.1 semantics"
cmapDescription 0 2 = "ISO/IEC 10646 semantics"
cmapDescription 0 3 = "Unicode 2.0 and onwards semantics, Unicode BMP only"
cmapDescription 0 4 = "Unicode 2.0 and onwards semantics, Unicode full repertoire"
cmapDescription 0 5 = "Unicode Variation Sequences"
cmapDescription 0 6 = "Unicode full repertoire"
cmapDescription 0 _ = "Unicode unknown"
cmapDescription 1 0 = "Macintosh Roman 8-bit simple"
cmapDescription 1 _ = "Macintosh unknown"
cmapDescription 3 0 = "Microsoft Symbol"
cmapDescription 3 1 = "Microsoft Unicode BMP (UCS-2)"
cmapDescription 3 2 = "Microsoft ShiftJIS"
cmapDescription 3 3 = "Microsoft PRC"
cmapDescription 3 4 = "Microsoft Big5"
cmapDescription 3 5 = "Microsoft Wansung"
cmapDescription 3 6 = "Microsoft Johab"
cmapDescription 3 7 = "Microsoft Reserved"
cmapDescription 3 8 = "Microsoft Reserved"
cmapDescription 3 9 = "Microsoft Reserved"
cmapDescription 3 10 = "Microsoft Unicode UCS-4"
cmapDescription 3 _ = "Microsoft Unknown"
cmapDescription _ _ = "Unknown"
showCmap :: Cmap -> String
showCmap cmap' =
formatTable $ header : map pluck (encodingDirectories cmap')
where header = ["PlatformId", "EncodingId", "Description"]
pluck dir = [show $ cmapPlatformId dir, show $ cmapEncodingId dir, cmapDescription (cmapPlatformId dir) (cmapEncodingId dir)]
eotgen :: Font f => f -> B.ByteString -> FilePath -> IO ()
eotgen font input filename = do
putStrLn $ "Generating " ++ target
B.writeFile target $ EOT.generate font input
where target = changeExtension "eot" filename
woffgen :: Font f => f -> B.ByteString -> FilePath -> Opts -> IO ()
woffgen font input filename Opts{..}= do
putStrLn $ "Generating " ++ target
B.writeFile target $ WOFF.generate font input zopfli
where target = changeExtension "woff" filename
svggen :: TTF -> B.ByteString -> FilePath -> Opts -> IO ()
svggen ttf input filename Opts{..} = do
putStrLn $ "Generating " ++ target
putStrLn "Available cmaps"
putStr $ showCmap $ cmap ttf
putStrLn $ "Selecting platformId " ++ show svgPlatformId ++ " encodingId " ++ show svgEncodingId ++ " -- " ++ cmapDescription svgPlatformId svgEncodingId
B.writeFile target $ SVG.generate ttf input cmapTable enableSvgKern
where target = changeExtension "svg" filename
cmapTable = cmapTableFind ttf svgPlatformId svgEncodingId
convert :: Opts -> FilePath -> IO ()
convert opts@Opts{..} filename = do
input <- B.readFile filename
if takeExtension filename == ".otf"
then let otf = fromRight $ runGet (OTF.parse input) input in
do
unless noEot (eotgen otf input filename)
unless noWoff (woffgen otf input filename opts)
else let ttf = fromRight $ runGet (TTF.parse input) input in
do
unless noEot (eotgen ttf input filename)
unless noWoff (woffgen ttf input filename opts)
unless noSvg (svggen ttf input filename opts)
convertFiles :: Opts -> IO ()
convertFiles opts@Opts{inputs = fonts} =
forM_ fonts $ safeConvert opts
where safeConvert opts' file = convert opts' file `catch` displayError file
displayError :: FilePath -> SomeException -> IO ()
displayError file e = (putStrLn $ "Failed to convert " ++ file) >> (putStrLn $ show e)
webifyVersion = "0.1.7.0"
main :: IO ()
main = do
opts <- execParser optsSpec
maybe (putStrLn $ "webify " ++ webifyVersion) convertFiles opts
where
parser = flag' Nothing (long "version" <> help "Display version") <|> (Just <$> optsDef)
optsSpec = info (helper <*> parser) mempty
| null | https://raw.githubusercontent.com/ananthakumaran/webify/e73fa2e3aa01512fe735dbf00a81e5909ccabbc9/src/Webify.hs | haskell | # OPTIONS_GHC -fno - warn - missing - signatures #
# LANGUAGE RecordWildCards #
import Control.Exception
import Control.Monad
import Data.Binary.Strict.Get
import qualified Data.ByteString as B
import Data.Monoid
import EOT
import Font hiding (str)
import Options.Applicative hiding (header)
import OTF
import SVG
import System.FilePath
import TTF
import Utils
import WOFF
platformAppleUnicode = 0
platformMacintosh = 1
platformISO = 2
platformMicrosoft = 3
encodingUndefined = 0
encodingUGL = 1
data Opts = Opts { noEot :: Bool
, noWoff :: Bool
, noSvg :: Bool
, enableSvgKern :: Bool
, zopfli :: Bool
, svgPlatformId :: UShort
, svgEncodingId :: UShort
, inputs :: [String]}
optsDef :: Parser Opts
optsDef = Opts <$> switch (long "no-eot" <> help "Disable eot")
<*> switch (long "no-woff" <> help "Disable woff")
<*> switch (long "no-svg" <> help "Disable svg")
<*> switch (long "svg-enable-kerning" <> help "Enable svg kerning")
<*> switch (long "zopfli" <> help "Use Zopfli Compression Algorithm")
<*> option auto (long "svg-cmap-platform-id" <> value platformMicrosoft <> help "Svg cmap platform id")
<*> option auto (long "svg-cmap-encoding-id" <> value encodingUGL <> help "Svg cmap encoding id")
<*> some (argument str (metavar "FONTS"))
changeExtension :: FilePath -> FilePath -> FilePath
changeExtension ext = flip addExtension ext . dropExtension
cmapDescription :: (Integral a) => a -> a -> String
cmapDescription 0 0 = "Unicode 1.0 semantics"
cmapDescription 0 1 = "Unicode 1.1 semantics"
cmapDescription 0 2 = "ISO/IEC 10646 semantics"
cmapDescription 0 3 = "Unicode 2.0 and onwards semantics, Unicode BMP only"
cmapDescription 0 4 = "Unicode 2.0 and onwards semantics, Unicode full repertoire"
cmapDescription 0 5 = "Unicode Variation Sequences"
cmapDescription 0 6 = "Unicode full repertoire"
cmapDescription 0 _ = "Unicode unknown"
cmapDescription 1 0 = "Macintosh Roman 8-bit simple"
cmapDescription 1 _ = "Macintosh unknown"
cmapDescription 3 0 = "Microsoft Symbol"
cmapDescription 3 1 = "Microsoft Unicode BMP (UCS-2)"
cmapDescription 3 2 = "Microsoft ShiftJIS"
cmapDescription 3 3 = "Microsoft PRC"
cmapDescription 3 4 = "Microsoft Big5"
cmapDescription 3 5 = "Microsoft Wansung"
cmapDescription 3 6 = "Microsoft Johab"
cmapDescription 3 7 = "Microsoft Reserved"
cmapDescription 3 8 = "Microsoft Reserved"
cmapDescription 3 9 = "Microsoft Reserved"
cmapDescription 3 10 = "Microsoft Unicode UCS-4"
cmapDescription 3 _ = "Microsoft Unknown"
cmapDescription _ _ = "Unknown"
showCmap :: Cmap -> String
showCmap cmap' =
formatTable $ header : map pluck (encodingDirectories cmap')
where header = ["PlatformId", "EncodingId", "Description"]
pluck dir = [show $ cmapPlatformId dir, show $ cmapEncodingId dir, cmapDescription (cmapPlatformId dir) (cmapEncodingId dir)]
eotgen :: Font f => f -> B.ByteString -> FilePath -> IO ()
eotgen font input filename = do
putStrLn $ "Generating " ++ target
B.writeFile target $ EOT.generate font input
where target = changeExtension "eot" filename
woffgen :: Font f => f -> B.ByteString -> FilePath -> Opts -> IO ()
woffgen font input filename Opts{..}= do
putStrLn $ "Generating " ++ target
B.writeFile target $ WOFF.generate font input zopfli
where target = changeExtension "woff" filename
svggen :: TTF -> B.ByteString -> FilePath -> Opts -> IO ()
svggen ttf input filename Opts{..} = do
putStrLn $ "Generating " ++ target
putStrLn "Available cmaps"
putStr $ showCmap $ cmap ttf
putStrLn $ "Selecting platformId " ++ show svgPlatformId ++ " encodingId " ++ show svgEncodingId ++ " -- " ++ cmapDescription svgPlatformId svgEncodingId
B.writeFile target $ SVG.generate ttf input cmapTable enableSvgKern
where target = changeExtension "svg" filename
cmapTable = cmapTableFind ttf svgPlatformId svgEncodingId
convert :: Opts -> FilePath -> IO ()
convert opts@Opts{..} filename = do
input <- B.readFile filename
if takeExtension filename == ".otf"
then let otf = fromRight $ runGet (OTF.parse input) input in
do
unless noEot (eotgen otf input filename)
unless noWoff (woffgen otf input filename opts)
else let ttf = fromRight $ runGet (TTF.parse input) input in
do
unless noEot (eotgen ttf input filename)
unless noWoff (woffgen ttf input filename opts)
unless noSvg (svggen ttf input filename opts)
convertFiles :: Opts -> IO ()
convertFiles opts@Opts{inputs = fonts} =
forM_ fonts $ safeConvert opts
where safeConvert opts' file = convert opts' file `catch` displayError file
displayError :: FilePath -> SomeException -> IO ()
displayError file e = (putStrLn $ "Failed to convert " ++ file) >> (putStrLn $ show e)
webifyVersion = "0.1.7.0"
main :: IO ()
main = do
opts <- execParser optsSpec
maybe (putStrLn $ "webify " ++ webifyVersion) convertFiles opts
where
parser = flag' Nothing (long "version" <> help "Display version") <|> (Just <$> optsDef)
optsSpec = info (helper <*> parser) mempty
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.